IF OBJECT_ID(N'KAAS_CP_AcitvateNewUserAccount',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_AcitvateNewUserAccount]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_AcitvateNewUserAccount]
    (@EmailId       VARCHAR(200),
	 @PasswordHash  NVARCHAR(512))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_AcitvateNewUserAccount]									   *
* Description: To activate new user account with password hash										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-08    Aakif        Created                                                                   *
* 2021-07-09    Aakif        #12608 - Name and email has to be removed while account activation		   *
 *******************************************************************************************************/

BEGIN

-- Update user details to activate account
UPDATE [dbo].[ClientLogin]
	SET
		[PasswordHash]						 = @PasswordHash,
		[IsEmailConfirmed]					 = 1,
		[IsUserVerifiedEmail]				 = 1,
		[EmailActivationToken]				 = NULL,
		[EmailActivationTokenExpirationTime] = NULL
	WHERE [Email] = @EmailId


END

GO
IF OBJECT_ID(N'KAAS_CP_AddEditRecentMatterList',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_AddEditRecentMatterList]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_AddEditRecentMatterList]
    (@LoginId	BIGINT,
	 @CaseCode	VARCHAR(15))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_AddEditRecentMatterList]									   *
* Description: TO ADD OR EDIT CLIENT PORTAL USER'S RECENT MATTER LIST								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-07-06    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN

IF NOT EXISTS (SELECT TOP 1 1 
				 FROM [dbo].[ClientPortalRecentMatter] [RML]
				WHERE [RML].ClientLoginId = @LoginId
				  AND [RML].[MatterCode] = @CaseCode)
BEGIN
	INSERT INTO 
		   [dbo].[ClientPortalRecentMatter]
		  ([ClientLoginId],
		   [MatterCode])
	VALUES
		  (@LoginId,
		   @CaseCode)

END
ELSE
BEGIN
	UPDATE [dbo].[ClientPortalRecentMatter]
	   SET [LastAccessDate] = GETUTCDATE()
	 WHERE [ClientLoginId] = @LoginId
	   AND [MatterCode] = @CaseCode
END
END

GO

IF OBJECT_ID(N'KAAS_CP_AddEditUserSetting',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_AddEditUserSetting]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_AddEditUserSetting]
    (@LoginId       BIGINT,
	 @SettingKey    VARCHAR(100),
	 @SettingValue  NVARCHAR(MAX))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_AddEditUserSetting]										   *
* Description: TO ADD OR EDIT CLIENT PORTAL USER SETTING											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-07-06    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN

IF NOT EXISTS (SELECT TOP 1 1 
				 FROM [dbo].[ClientPortalUserSetting] [US]
				WHERE [US].ClientLoginId = @LoginId
				  AND [US].[Key] = @SettingKey)
BEGIN
	INSERT INTO 
		   [dbo].[ClientPortalUserSetting]
		  ([ClientLoginId],
		   [Key],
		   [Value])
	VALUES
		  (@LoginId,
		   @SettingKey,
		   @SettingValue)
END
ELSE
BEGIN
	UPDATE [dbo].[ClientPortalUserSetting]
	   SET [Value] = @SettingValue
	 WHERE [ClientLoginId] = @LoginId
	   AND [Key] = @SettingKey
END
END

GO

IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_CreateActionForFECode'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_CreateActionForFECode]
  END
GO

CREATE PROCEDURE [KAAS_CP_CreateActionForFECode]
(
    @CASECODE                 VARCHAR(20),
    @FNCODE                   VARCHAR(10),
    @TEAMCODE                 VARCHAR(10),
	@SUBJECT				  VARCHAR(MAX),
	@TEXT					  VARCHAR(MAX),
    @Result                      INT    OUTPUT
)

/*******************************************************************************************************
* This sp used to insert blank action.																   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[CreateActionForFECode]											       *
* Copied from			: [dbo].[ky_NETInsertTasksAction]											   *
* Copied from			: [dbo].[KAAS_InsertTasksAction]											   *
* Copied from			: [dbo].[KAAS_CP_GetActionId]											       *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
* 2022-02-10	Vinodhkumar.M   Created for Client Portal - upload doument                             *
* 2022-02-10	Vinodhkumar.M   KAAS_CP_GetNextActionId is created instead of KAAS_GetNextActionID     *
							    KAAS_CP_ConvertTime is created Instead of ky_ConvertTimeToClarion      *
						        for client Portal                                                      *
* 2022-02-15   Vinodhkumar.M   In Inserting diary passing values for due date priority value,          *
							   Action type and Publish fields										   *
* 2022-04-18   Vinodhkumar.M   Created																   *
* 2022-04-26   Vinodhkumar.M   Updated - action code in insert statement     						   *
*******************************************************************************************************/ 

AS
BEGIN
SET NOCOUNT ON
--Diary
    DECLARE @TIMECONVERT INT
    SET @TIMECONVERT = dbo.KAAS_CP_ConvertTime(GETDATE())
    DECLARE @ACTIONID    INT

    --Pino 2015-09-30 Start
   -- EXEC @ACTIONID = [dbo].[KAAS_GetNextActionID] 
    --SET @ACTIONID = (SELECT ISNULL(MAX(ACTIONID + 1), 1) FROM [dbo].[diary])
    --Pino 2015-09-30 End

	 -- This SP created for Client Portal Upload
	 EXEC @ACTIONID = [dbo].[KAAS_CP_GetNextActionId] 

    INSERT
      INTO [dbo].[diary]
          ([CASECODE],
           [DATE],
           [STATUS],
           [ACTIONCODE],
           [ACTIONSTATUS],
           [ACTIONTYPE],
           [PROCESSTYPE],
           [FNCODE],
           [TEAMCODE],
           [TEXT1],
           [TEXT2],
           [DELEGATEDFNR],
           [DELEGATEDDATE],
           [DELEGATEDBACKDATE],
           [DEFERRED],
           [DUEDATE],
           [PUBLISH],
           [DYSTARTTIME],
           [DYENDTIME],
           [DURATION],
           [ACTIONID],
           [ORGINALACTIONID],
           [PRIORITY],
           [HIGHLIGHTED],
           [MILESTEONETYPE],
           [ATTACHMENTS],
           [PROCESSSTATUS],
           [WORKPROCESS],
           [BILLABLE],
           [BILLDESCRIPTION],
           [EMAILADDRESS],
           [ADDRESSTO],
           [CCTo],
           [BCCTo],
           [EMAIL],
           [SUBJECT],
           [DELEGATIONSTATUS],
           [DRAFTBILLNO],
           [CHEQUEREQNO],
           [TxmSent],
           [Location],
           [HearingType],
           [ForCopy],
           [TxmDate],
           [TxmSeqNo],
           [DisplayText],
           [Flag])
    VALUES(@CASECODE,
           GETDATE(),
           0,
           'ADMNT',
           null,
           'N',
           null,
           @FNCODE,
           @TEAMCODE,
           @TEXT,
           null,
           null,
           null,
           null,
           null,
           GETDATE(),
           'P',
           @TIMECONVERT,
           @TIMECONVERT,
           0,
           @ACTIONID,
           0,
           'N',
           null,
           null,
           null,
           0,
           0,
           0,
           null,
           null,
           null,
           null,
           null,
           null,
           @SUBJECT,
           0,
           0,
           0,
           0,
           null,
           'Not Applicable',
           null,
           null,
           0,
          null,
           0)
    INSERT
              INTO [dbo].[DiaryDelegations]
                  ([ACTIONID],
                   [HANDLER],
                   [TEAM],
                   [DATE],
                   [TIME],
                   [DATER],
                   [TIMER],
                   [DUEDATE],
                   [DUETIME],
                   [REVIEW],
                   [STATUS],
                   [OWNER],
                   [DELEGATE],
                   [DELEGATESTATUS],
                   [ActionType],
                   [FromHandler],
                   [ReturnedBy],
                   [DelType])
            VALUES(@ACTIONID,
                   @FNCODE,
                   @TEAMCODE,
                   GETDATE(),
                   @TIMECONVERT,
                   null,
                   @TIMECONVERT,
                   GETDATE(),
                   @TIMECONVERT,
                   null,
                   0,
                   'Y',
                   @FNCODE,
                   0,
                   null,
                   @FNCODE,
                   null,
                   'Created')
    SET @Result = @ACTIONID
SET NOCOUNT OFF
END

GO
IF OBJECT_ID(N'KAAS_CP_CreateActionForNewInstruction',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_CreateActionForNewInstruction]
GO

CREATE PROCEDURE [KAAS_CP_CreateActionForNewInstruction]
(
    @CASECODE	VARCHAR(20),
    @FormId		INT
)

/*******************************************************************************************************
* This sp used to create action based on Template provided by new instruction form type				   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[CreateActionForFECode]											       *
*                                                                                                      *
* Modification History	:                                                                              *
* 2022-06-07   Aakif   Created																		   *
*******************************************************************************************************/ 

AS
BEGIN
SET NOCOUNT ON
--Diary INSERT IF TEMPLATE ACTION IS PRESENT FOR FORM
	DECLARE @NewActionCode VARCHAR(15) = NULL;
	DECLARE @FECode nvarchar(20) = '';
	DECLARE @ActionDesc VARCHAR(100) = '';
	DECLARE @ActionType CHAR(1) = '';
	DECLARE @HandlerTeamCode VARCHAR(10) = '';

	SELECT @NewActionCode = LTRIM(RTRIM(ISNULL(InitialActionCode, ''))),
		   @FECode = LTRIM(RTRIM(FeCode))
	  FROM [dbo].[WebForms]
	 WHERE [FormId] = @FormId

	SELECT @ActionDesc = [Description],
		   @ActionType = [ACTTYPE]
	  FROM [dbo].[TemplateActions]
	 WHERE ACTIONCODE = @NewActionCode

	SELECT @HandlerTeamCode = [Team] 
	  FROM [dbo].[Handlers]
	 WHERE [CODE] = @FECode


    DECLARE @TIMECONVERT INT
    SET @TIMECONVERT = dbo.KAAS_CP_ConvertTime(GETDATE())
    DECLARE @ACTIONID    INT

	 -- This SP created for Client Portal Upload
	 EXEC @ACTIONID = [dbo].[KAAS_CP_GetNextActionId] 

    INSERT
      INTO [dbo].[diary]
          ([CASECODE],
           [DATE],
           [STATUS],
           [ACTIONCODE],
           [ACTIONSTATUS],
           [ACTIONTYPE],
           [PROCESSTYPE],
           [FNCODE],
           [TEAMCODE],
           [TEXT1],
           [TEXT2],
           [DELEGATEDFNR],
           [DELEGATEDDATE],
           [DELEGATEDBACKDATE],
           [DEFERRED],
           [DUEDATE],
           [PUBLISH],
           [DYSTARTTIME],
           [DYENDTIME],
           [DURATION],
           [ACTIONID],
           [ORGINALACTIONID],
           [PRIORITY],
           [HIGHLIGHTED],
           [MILESTEONETYPE],
           [ATTACHMENTS],
           [PROCESSSTATUS],
           [WORKPROCESS],
           [BILLABLE],
           [BILLDESCRIPTION],
           [EMAILADDRESS],
           [ADDRESSTO],
           [CCTo],
           [BCCTo],
           [EMAIL],
           [SUBJECT],
           [DELEGATIONSTATUS],
           [DRAFTBILLNO],
           [CHEQUEREQNO],
           [TxmSent],
           [Location],
           [HearingType],
           [ForCopy],
           [TxmDate],
           [TxmSeqNo],
           [DisplayText],
           [Flag])
    VALUES(@CASECODE,
           GETDATE(),
           0,
           @NewActionCode,
           null,
           @ActionType,
           null,
           @FECode,
           @HandlerTeamCode,
           @ActionDesc,
           null,
           null,
           null,
           null,
           null,
           GETUTCDATE(),
           'P',
           @TIMECONVERT,
           @TIMECONVERT,
           0,
           @ACTIONID,
           0,
           'N',
           null,
           null,
           null,
           0,
           0,
           0,
           null,
           null,
           null,
           null,
           null,
           null,
           @ActionDesc,
           0,
           0,
           0,
           0,
           null,
           'Not Applicable',
           null,
           null,
           0,
          null,
           0)
    INSERT
              INTO [dbo].[DiaryDelegations]
                  ([ACTIONID],
                   [HANDLER],
                   [TEAM],
                   [DATE],
                   [TIME],
                   [DATER],
                   [TIMER],
                   [DUEDATE],
                   [DUETIME],
                   [REVIEW],
                   [STATUS],
                   [OWNER],
                   [DELEGATE],
                   [DELEGATESTATUS],
                   [ActionType],
                   [FromHandler],
                   [ReturnedBy],
                   [DelType])
            VALUES(@ACTIONID,
                   @FECode,
                   @HandlerTeamCode,
                   GETUTCDATE(),
                   @TIMECONVERT,
                   null,
                   @TIMECONVERT,
                   GETDATE(),
                   @TIMECONVERT,
                   null,
                   0,
                   'Y',
                   @FECode,
                   0,
                   null,
                   @FECode,
                   null,
                   'Created')

    --SET @Result = @ACTIONID

SET NOCOUNT OFF
END

GO

IF OBJECT_ID(N'KAAS_CP_DeleteAction',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_DeleteAction]
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_DeleteAction]
      (@ACTIONID        INT,
       @HANDLERCODE     VARCHAR(10),
       @IsAddAction     BIT)

/*******************************************************************************************************
* This procedure is used Delete an Action from the Case Diary.                                         *
*                                                                                                      *
* Stored Procedure Name    : [dbo].[KAAS_CP_DeleteAction]                                              *
* Copied from            : [dbo].[KAAS_DeleteAction]                                                   *
*                                                                                                      *
* Modification History    :                                                                            *
* 2019-04-22    Vinodhan K      Created                                                                *
* 2021-03-17    Sadiq           Added condition to check Config settings @AllowUserToDeleteAction from *
                                Settings Table and returning Error if @AllowUserToDeleteAction is false*
* 2021-03-18    Sadiq           Need to delete Action if user cancels delete action                    *
* 2021-03-18    Vinodhkumar.M   Created                                                                *
* 2024-03-13    Pino Carafa     Handle the absence of triggers                                         *
*                               Please use the following Aliases for the [deletedrow]:                 *
*                               [dbo].[diary]            - [Diary]                                     *
*                               [dbo].[DiaryAttachments] - [DiaryAttachments]                          *
*                               [dbo].[DiaryDelegations] - [DiaryDelegations]                          *
*                                                                                                      *
*******************************************************************************************************/
AS
BEGIN

DECLARE @Error VARCHAR(200)
DECLARE @NCOMMAND nvarchar(MAX)

DECLARE @AllowUserToDeleteOthersAction BIT;
DECLARE @AllowUserToDeleteAction BIT;

DECLARE @Loginame NVARCHAR(128)

SELECT @Loginame = RTRIM([P].[loginame]) FROM sys.sysprocesses [P] WHERE [P].[spid] = @@SPID --2024-03-13

SET NOCOUNT ON

IF @IsAddAction = 0
BEGIN
  SELECT @AllowUserToDeleteAction = CASE WHEN [SET].[KeyValue] = '1'
                                              THEN 1
                                         ELSE 0 END
    FROM [dbo].[Settings] [SET]
   WHERE [SET].[KeyName] = 'AllowToDeleteAction'

  SET @AllowUserToDeleteAction = ISNULL(@AllowUserToDeleteAction, 0);-- If null '0', So that, Settings screen data and functionality is matched

  IF @AllowUserToDeleteAction = 0
    BEGIN
      SELECT 'you are not allowed to delete this action.!'
      RETURN;
    END
END

SELECT @AllowUserToDeleteOthersAction = CASE WHEN [SET].[KeyValue] = '1'
                                                  THEN 1
                                             ELSE 0 END
  FROM [dbo].[Settings] [SET]
 WHERE [SET].[KeyName] = 'AllowToDeleteOtherAction'

SET @AllowUserToDeleteOthersAction = ISNULL(@AllowUserToDeleteOthersAction, 0);-- If null '0', So that, Settings screen data and functionality is matched

IF @AllowUserToDeleteOthersAction = 0
BEGIN
  IF NOT EXISTS(SELECT TOP 1 1 FROM diary  WHERE ACTIONID = @ACTIONID AND FNCODE = @HANDLERCODE)
  BEGIN
    SELECT 'You are not allowed to delete other user action!'
    RETURN;
  END
END

  IF [dbo].[ISSAM4]() = 0
    BEGIN
      SET @NCOMMAND = N'
      IF EXISTS
        (SELECT TOP 1 1
           FROM [dbo].[BillHeader] [BH]
          WHERE [BH].[RELEASED] = ''Y''
            AND [BH].[BILLNO] <> 0
            AND [BH].[ACTIONID] = ' + CONVERT(NVARCHAR(10), @ActionID) + N')
        BEGIN
          SET @Error = ''You cannot delete a Draft Bill Action.''
        END
      ELSE
        BEGIN
          SET @Error = NULL
        END'

      EXECUTE sp_executesql @NCOMMAND, N'@ActionID INT,@Error VARCHAR(200) OUTPUT', @ActionID = @ActionID, @Error=@Error OUTPUT
    END
  ELSE
    BEGIN
      SET @NCOMMAND = N'
      IF EXISTS
        (SELECT TOP 1 1
           FROM [dbo].[diary] [DIA]
                INNER JOIN [dbo].[Billhead] [BH]
                        ON [BH].[BillingID] = [DIA].[DRAFTBILLNO]
                       AND [BH].[InvoiceNo] <> 0
          WHERE [DIA].[ACTIONID] = ' + CONVERT(NVARCHAR(10), @ActionID) + N')
        BEGIN
          SET @Error = ''You cannot delete a Draft Bill Action.''
        END
      ELSE
        BEGIN
          SET @Error = NULL
        END'

      EXECUTE sp_executesql @NCOMMAND, N'@ActionID INT,@Error VARCHAR(200) OUTPUT', @ActionID = @ActionID, @Error=@Error OUTPUT
    END

  IF [dbo].[ISSAM4]() = 0
    BEGIN
      SET @NCOMMAND = N'
      IF EXISTS
        (SELECT TOP 1 1
           FROM [dbo].[diary] [DIA]
                INNER JOIN [dbo].[ChequeRequisitionHeader] [CRH]
                        ON [CRH].[REQNO] = [DIA].[CHEQUEREQNO]
                       AND [CRH].[REQNO] <> 0
                       AND [CRH].[Status] = 2
          WHERE [DIA].[ACTIONID] = ' + CONVERT(NVARCHAR(10), @ActionID) + N')
        BEGIN
          SET @Error = ''You cannot delete an approved Cheque.''
        END
      ELSE
        BEGIN
          SET @Error = NULL
        END'

      EXECUTE sp_executesql @NCOMMAND, N'@ActionID INT,@Error VARCHAR(200) OUTPUT', @ActionID = @ActionID, @Error=@Error OUTPUT
    END
  ELSE
    BEGIN
      SET @NCOMMAND = N'
      IF EXISTS
        (SELECT TOP 1 1
           FROM [dbo].[diary] [DIA]
                INNER JOIN [dbo].[ChequeRequisitions] [CRQ]
                        ON [CRQ].[RecordID] = [DIA].[CHEQUEREQNO]
                       AND [CRQ].[RecordID] <> 0
                       AND [CRQ].[ChequeStatus] = ''Approved''
          WHERE [DIA].[ACTIONID] = ' + CONVERT(NVARCHAR(10), @ActionID) + N')
        BEGIN
          SET @Error = ''You cannot delete an approved Cheque.''
        END
      ELSE
        BEGIN
          SET @Error = NULL
        END'

      EXECUTE sp_executesql @NCOMMAND, N'@ActionID INT,@Error VARCHAR(200) OUTPUT', @ActionID = @ActionID, @Error=@Error OUTPUT
    END

  IF (@Error IS NULL)
    BEGIN
      IF EXISTS(SELECT TOP 1 1
                  FROM [dbo].[diary] [DIA]
                 WHERE [DIA].[STATUS] = 1
                   AND [DIA].[ACTIONID] = @ACTIONID)
        BEGIN
          SET @Error = 'You cannot delete ANY Complete Action'
        END
    END

  IF (@Error IS NULL)
    BEGIN
      IF EXISTS(SELECT TOP 1 1
                  FROM [dbo].[diary] [DIA]
                 WHERE [DIA].[ACTIONTYPE] = 'U'
                   AND [DIA].[ACTIONID] = @ACTIONID)
        BEGIN
          SET @Error = 'You cannot delete Undertakings Action.'
        END
    END

  IF (@Error IS NULL)
    BEGIN
      IF EXISTS(SELECT TOP 1 1
                  FROM [dbo].[diary] [DIA]
                 WHERE [DIA].[ACTIONTYPE] = 'S'
                   AND [DIA].[ACTIONID] = @ACTIONID)
        BEGIN
          SET @Error = 'You cannot delete a Statute of Limitations Action.'
        END
    END

  IF (@Error IS NULL)
    BEGIN
      IF EXISTS(SELECT TOP 1 1
                  FROM [dbo].[diary] [DIA]
                 WHERE [DIA].[ACTIONTYPE] = 'C'
                   AND [DIA].[ACTIONID] = @ACTIONID)
        BEGIN
          SET @Error = 'You cannot delete a Critical Date Action'
        END
    END

  IF (@Error IS NULL)
    BEGIN
      IF [dbo].[ISSAM4]() = 0
        BEGIN
          SET @NCOMMAND = N'
            IF EXISTS
              (SELECT TOP 1 1
                 FROM [dbo].[diary] [DIA]
                      INNER JOIN [dbo].[BillHeader] [BH]
                              ON [BH].[BILLNO] <> 0
                             AND [BH].[DRAFTNO] = [DIA].[DRAFTBILLNO]
                WHERE [DIA].[ACTIONID] = ' + CONVERT(NVARCHAR(10), @ActionID) + N')
              BEGIN
                SET @Error = ''You cannot delete a Draft Bill Action.''
              END
            ELSE
              BEGIN
                SET @Error = NULL
              END'
        END
    END

  IF (@Error IS NULL)
    BEGIN
      IF EXISTS(SELECT 1
                  FROM [dbo].[diary] [DIA]
                       INNER JOIN [dbo].[TemplateActions] [TAC]
                               ON [TAC].[ACTIONCODE] = [DIA].[ACTIONCODE]
                              AND [TAC].[RequiredAction] = 'Y'
                 WHERE [DIA].[ACTIONID] = @ACTIONID)
        BEGIN
          SET @Error = 'This is a required action for this case and cannot be removed.'
        END
    END

  IF (@Error IS NULL)
    BEGIN
      -- 2024-03-13 START (1)
      IF NOT EXISTS
        (SELECT TOP 1 1
           FROM sys.objects [SO]
          WHERE [SO].[name] = 'ky_NETTRDeleteDiaryAttachment'
            AND [SO].[type] = 'TR')
      BEGIN
        INSERT
          INTO [dbo].[DiaryAttachmentDeletionLog]
              ([on],
               [by],
               [Login],
               [HandlerCode],
               [ActionID],
               [TrackReference],
               [deletedrow])
        SELECT GetDate(),
               APP_NAME(),
               @Loginame,
               @HANDLERCODE,
               [DEL].[DiaryID],
               [DEL].[TrackReference],
               (SELECT * FROM [dbo].[DiaryAttachments] [DiaryAttachments] WHERE [DiaryAttachments].[TrackReference] = [DEL].[TrackReference] FOR XML AUTO) AS [deletedrow]
          FROM [dbo].[DiaryAttachments] [DEL]
         WHERE [DEL].[DiaryID] = @ACTIONID

        INSERT
          INTO [dbo].[DiaryAttachmentAccess]
              ([TrackReference],
               [Handler],
               [Comment])
        SELECT [DEL].[TrackReference],
               @HANDLERCODE,
               'Deleted'
          FROM [dbo].[DiaryAttachments] [DEL]
         WHERE [DEL].[DiaryID] = @ACTIONID
      END
      -- 2024-03-13 END (1)
      DELETE [DAT]
        FROM [dbo].[DiaryAttachments] [DAT]
       WHERE DAT.[DiaryID] = @ACTIONID

      -- 2024-03-13 START (2)
      IF NOT EXISTS
        (SELECT TOP 1 1
           FROM sys.objects [SO]
          WHERE [SO].[name] = 'ky_NETTRDeleteDiaryDelegations'
            AND [SO].[type] = 'TR')
      BEGIN
        INSERT
          INTO [dbo].[DiaryDelegationDeletionLog]
              ([on],
               [by],
               [Login],
               [HandlerCode],
               [deletedrow],
               [ActionID],
               [AssignNo])
        SELECT GetDate(),
               APP_NAME(),
               @Loginame,
               @HANDLERCODE,
               (SELECT * FROM [dbo].[DiaryDelegations] [DiaryDelegations] WHERE [DiaryDelegations].[AssignNo] = [DEL].[AssignNo] FOR XML AUTO) AS [deletedrow],
               [DEL].[ActionID],
               [DEL].[AssignNo]
          FROM [dbo].[DiaryDelegations] [DEL]
         WHERE [DEL].[ACTIONID] = @ACTIONID
      END
      -- 2024-03-13 END (2)
      DELETE [DEL]
        FROM [dbo].[DiaryDelegations] [DEL]
       WHERE DEL.[ACTIONID] = @ACTIONID

      DELETE [DLK]
        FROM [dbo].[DiaryLinks] [DLK]
       WHERE DLK.[ACTIONID] = @ACTIONID

      DELETE [DTM]
        FROM [dbo].[DiaryTemp] [DTM]
       WHERE DTM.[ACTIONID] = @ACTIONID

      DELETE [OLA]
        FROM [dbo].[OLApptXref] [OLA]
       WHERE OLA.[ACTIONID] = @ACTIONID

      DECLARE @COMMAND VARCHAR(MAX)

      DECLARE @DRAFTBILLNO INT

      SELECT @DRAFTBILLNO = [DIA].[DRAFTBILLNO]
        FROM [dbo].[diary] [DIA]
       WHERE [DIA].[ACTIONID] = @ACTIONID

      IF ISNULL(@DRAFTBILLNO, 0) > 0
        BEGIN
            DECLARE @SQL NVARCHAR(MAX)
            SET @SQL = 'EXEC [dbo].[KAAS_DeleteDraftBillOnly{SAM4}] ' + CONVERT(VARCHAR(10), @DRAFTBILLNO) + ', ''' + @HANDLERCODE + ''''

            IF [dbo].[ISSAM4]() = 0
            BEGIN
                SET @SQL = REPLACE(@SQL, '{SAM4}', '')
            END
            ELSE
            BEGIN
                SET @SQL = REPLACE(@SQL, '{SAM4}', 'SAM4')
            END

            EXEC sp_executesql @SQL
        END

      IF EXISTS
        (SELECT TOP 1 1
           FROM SYS.[objects] [SO]
          WHERE [SO].[name] = 'ChequeRequisitions'
            AND [SO].[type] = 'U')
      BEGIN
        SET @COMMAND = '
        DELETE [CHRQ]
          FROM [dbo].[diary] [DIA]
               INNER JOIN [dbo].[ChequeRequisitions] [CHRQ]
                       ON [CHRQ].[RecordId] = [DIA].[CHEQUEREQNO]
         WHERE [DIA].[ACTIONID] = ' + CONVERT(VARCHAR(10), @ACTIONID)

        EXEC (@COMMAND)
      END

      IF EXISTS
        (SELECT TOP 1 1
           FROM SYS.[objects] SO
          WHERE SO.[name] = 'ChequeRequisitionDetail'
            AND SO.[type] = 'U')
      BEGIN
        SET @COMMAND = '
        DELETE [CHRD]
          FROM [dbo].[diary] [DIA]
               INNER JOIN [dbo].[ChequeRequisitionDetail] [CHRD]
                       ON [CHRD].[REQNO] = [DIA].[CHEQUEREQNO]
         WHERE [DIA].[ACTIONID] = ' + CONVERT(VARCHAR(10), @ACTIONID)

        EXEC (@COMMAND)
      END

      IF EXISTS
        (SELECT TOP 1 1
           FROM SYS.[objects] SO
          WHERE SO.[name] = 'ChequeRequisitionHeader'
            AND SO.[type] = 'U')
      BEGIN
        SET @COMMAND = '
        DELETE [CHRH]
          FROM [dbo].[diary] [DIA]
               INNER JOIN [dbo].[ChequeRequisitionHeader] [CHRH]
                       ON [CHRH].[REQNO] = [DIA].[CHEQUEREQNO]
         WHERE [DIA].[ACTIONID] = ' + CONVERT(VARCHAR(10), @ACTIONID)

        EXEC (@COMMAND)
      END

      IF EXISTS
        (SELECT TOP 1 1
           FROM SYS.[objects] SO
          WHERE SO.[name] = 'ChequeRequisitionLog'
            AND SO.[type] = 'U')
      BEGIN
        SET @COMMAND = '
        DELETE [CRL]
          FROM [dbo].[diary] AS [DIA]
               INNER JOIN [ChequeRequisitionLog] AS [CRL]
                       ON [CRL].[ID] = [DIA].[CHEQUEREQNO]
         WHERE [DIA].[ACTIONID] = ' + CONVERT(VARCHAR(10), @ACTIONID)

        EXEC (@COMMAND)
      END

      EXEC [dbo].[KAAS_UpdateActionAlarm] @ACTIONID

      -- 2024-03-13 START (3)
      IF NOT EXISTS
        (SELECT TOP 1 1
           FROM sys.objects [SO]
          WHERE [SO].[name] = 'ky_NETTRDeleteDiary'
            AND [SO].[type] = 'TR')
      BEGIN
        INSERT
          INTO [dbo].[DiaryDeletionLog]
              ([on],
               [by],
               [Login],
               [HandlerCode],
               [ActionId],
               [CASECODE],
               [deletedrow])
        SELECT GetDate(),
               APP_NAME(),
               @Loginame,
               @HANDLERCODE,
               [DEL].[ActionID],
               [DEL].[CASECODE],
               (SELECT * FROM [dbo].[diary] [Diary] WHERE [Diary].[ActionID] = [DEL].[ActionID] FOR XML AUTO) AS [deletedrow]
          FROM [dbo].[diary] [DEL]
         WHERE [DEL].[ACTIONID] = @ACTIONID
      END
      -- 2024-03-13 END (3)
      DELETE [DIA]
        FROM [dbo].[diary] [DIA]
       WHERE [DIA].[ACTIONID] = @ACTIONID

      SELECT 'True'
    END
  ELSE
    BEGIN
      SELECT @Error
    END

  SET NOCOUNT OFF

END

GO
IF OBJECT_ID(N'KAAS_CP_FetchDiaryByMatterCode',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_FetchDiaryByMatterCode]
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_FetchDiaryByMatterCode]
      (@Matter        VARCHAR(20),
       @Search        VARCHAR(200) = NULL,
       @PageNumber    INT          = NULL,
       @PageSize      INT          = NULL,
       @ActionTypeXML XML          = NULL,
       @PriorityXML   XML          = NULL,
       @FlagXML       XML          = NULL,
       @DateXML       XML          = NULL,
	   @LoginId		  BIGINT	   = NULL )
AS
/*************************************************************************************************************
 *                                                                                                           *
 * Copied From: [dbo].[KEYHM_FetchDiaryByMatterCode]                                                         *
 *                                                                                                           *
 * Fetch Diary Items by Matter Code, with support for pagination and for filtering on ActionType,            *
 * Priority and/or Flag.                                                                                     *
 *                                                                                                           *
 * @Search can be any string. Wildcard % will be appended at start and finish                                *
 * @ActionTypeXML: example - '<ActionType Value="A" /><ActionType Value="N" />'                              *
 * @PriorityXML: example -  '<Priority Value="N" />'                                                         *
 * @DateXML: example -  '<Dates FromDate="20190101" ToDate="20190430"/>'                                     *
 * @FlagXML: example-  '<Flag Value="0" /><Flag Value="1" /><Flag Value="2" /><Flag Value="3" />'            *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              [dbo].[ky_NETCASEDIARYFetchDiarybyMatterCode]            *   *
 *   * Original:                                [dbo].[ky_NETSPFetchDiaryByMatterCode]                   *   *
 *   * First compatible version:                5.7.2.1                                                  *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History                                                                                      *
  * 2019-04-02   Pino Carafa			Created                                                              *
 * 2019-04-30   Pino Carafa			Added Subject search and Date Range                                      *
 * 2019-05-21   Saravanan			Performance tuning done                                                  *
 * 2019-05-29   Arun				KEYHM-402 - Sorting order was correct till @FOUND table					 *
									variable(Line No: 232), after this, few column have joined for desired	 *
									output, at that time, sorting  order gets changed, so explicitily have	 * 
									soredted by id column after join operation completed(Line no: 380).		 *
 * 2019-10-23   Vinodhan            If Flag is null, it be replaced with 0 and filtered while filtering the
                                    case diary data                                                          *
									soredted by id column after join operation completed(Line no: 380).		 *	
 * 2019-10-29   Arun                Have used KEYHM_FNConvertUTCDateToTargetTimeZone function to convert     * 
									action date to utc									                     *
 * 2021-06-14   Aakif				Created                                                                  *
 * 2022-06-08   Aakif				Included TEXT2 field that retains word wrapping							 *
 *************************************************************************************************************/

BEGIN

SET NOCOUNT ON

DECLARE @ShowFromToSynopsis BIT
DECLARE @FromDate DATETIME
DECLARE @ToDate   DATETIME

SET @ShowFromToSynopsis = CASE WHEN ISNULL((SELECT TOP 1
                                                   [SET].[KeyValue]
                                              FROM [dbo].[Settings] [SET]
                                       WHERE [SET].[KeyName] = 'ShowFromToSynopsis'),
                                           'True') = 'False'
                                    THEN 0
                               ELSE 1 END

-- Convert @ActionTypesXML etc into Table Variables for easier reference in later scripts START
DECLARE @ACTIONTYPES TABLE
       ([ActionType] VARCHAR(1)       PRIMARY KEY)



DECLARE @ACTIONTYPESFILTERED BIT
SET @ACTIONTYPESFILTERED = 0 --Squeeze the last little bit of performance out of this

DECLARE @PRIORITIES  TABLE
       ([Priority]   VARCHAR(1)       PRIMARY KEY)

DECLARE @PRIORITIESFILTERED BIT
SET @PRIORITIESFILTERED = 0  --Squeeze the last little bit of performance out of this

DECLARE @Flags  TABLE
       ([Flag]       TINYINT       PRIMARY KEY)

DECLARE @FLAGSFILTERED BIT
SET @FLAGSFILTERED = 0       --Squeeze the last little bit of performance out of this

IF NOT (@DateXML IS NULL)
  IF NOT (CONVERT(VARCHAR(MAX), @DateXML) = '')
    BEGIN
      SELECT [FromDate], [ToDate]
        FROM (SELECT [DT].[COL].value('@FromDate', 'DATETIME')                  AS [FromDate], -- Use >= for comparison
                     DATEADD(DAY, 1, [DT].[COL].value('@ToDate', 'DATETIME'))   AS [ToDate]    -- Add 1 Day to ToDate so that we can use < for comparison
                FROM @DateXML.nodes('/Dates') AS [DT]([COL])) [DTP]
    END

IF NOT (@ActionTypeXML IS NULL)
  IF NOT (CONVERT(VARCHAR(MAX), @ActionTypeXML) = '')
    BEGIN
      INSERT
        INTO @ACTIONTYPES
            ([ActionType])
      SELECT [ActionType]
        FROM (SELECT [AT].[COL].value('@Value', 'VARCHAR(10)') AS [ActionType]
                FROM @ActionTypeXML.nodes('/ActionType') AS [AT]([COL])) [ATP]

      SELECT @ACTIONTYPESFILTERED = CASE COUNT(1) WHEN 0 THEN 0 ELSE 1 END FROM @ACTIONTYPES
    END


    --Select * from @ActionTypes

IF NOT (@PriorityXML IS NULL)
  IF NOT (CONVERT(VARCHAR(MAX), @PriorityXML) = '')
    BEGIN
      INSERT
        INTO @PRIORITIES
            ([Priority])
      SELECT [Priority]
        FROM (SELECT [PT].[COL].value('@Value', 'VARCHAR(10)') AS [Priority]
                FROM @PriorityXML.nodes('/Priority') AS [PT]([COL])) [PTY]

      SELECT @PRIORITIESFILTERED = CASE COUNT(1) WHEN 0 THEN 0 ELSE 1 END FROM @PRIORITIES
    END

IF NOT (@FlagXML IS NULL)
  IF NOT (CONVERT(VARCHAR(MAX), @FlagXML) = '')
    BEGIN
      INSERT
        INTO @Flags
            ([Flag])
      SELECT [Flag]
        FROM (SELECT [FG].[COL].value('@Value', 'INT') AS [Flag]
                FROM @FlagXML.nodes('/Flag') AS [FG]([COL])) [FLG]

      SELECT @FLAGSFILTERED = CASE COUNT(1) WHEN 0 THEN 0 ELSE 1 END FROM @Flags
    END
-- Convert @ActionTypesXML etc into Table Variables for easier reference in later scripts END

-- Set @SearchText to NULL if nothing entered, otherwise ensure search starts and ends with
-- a wildcard character % - START
DECLARE @SEARCHTEXT VARCHAR(202)

SET @SearchText = CASE WHEN RTRIM(ISNULL(@Search, '')) = '' THEN NULL ELSE RTRIM(ISNULL(@Search, '')) END

IF @SearchText IS NOT NULL
  BEGIN
    IF SUBSTRING(@SearchText, 1, 1) <> '%'
      BEGIN
        SET @SearchText = '%' + @SearchText
      END

    IF SUBSTRING(@SearchText, LEN(@SearchText), 1) <> '%'
      BEGIN
        SET @SearchText = @SearchText + '%'
      END
  END
-- Set @SearchText to NULL if nothing entered, otherwise ensure search starts and ends with
-- a wildcard character % - END

-- Avoid Unnecessary Join START
DECLARE @ChargeArrangement VARCHAR(3)
SELECT @ChargeArrangement = RTRIM(ISNULL([MAT].[ChargeArrangement], '')) FROM [dbo].[matters] [MAT] WHERE [MAT].[Code] = @Matter
-- Avoid Unnecessary Join END

--SELECT ActionType FROM #ACTIONTYPES

-- Table to contain all matching ActionIDs in the desired order
DECLARE @FOUND TABLE
       ([id]        INT        IDENTITY(1, 1)         PRIMARY KEY,
        [ActionID]  INT)

-- Insert ONLY the Primary Keys into the @FOUND Table so that it's much faster to retrieve only the requested page - Performance!
INSERT
  INTO @FOUND
      ([ActionID])
SELECT [DIA].[ActionID]
  FROM [dbo].[diary] [DIA]
       LEFT OUTER JOIN [dbo].[Handlers] [FN]
                    ON [FN].[CODE] = [DIA].[FNCODE]
 WHERE [DIA].[CASECODE] = @Matter
	   AND ISNULL([DIA].PUBLISH, '') = 'P'

   --    -- Use the CASE Construct to ensure it doesn't perform the PATINDEX unless it's actually necessary - Performance!
   AND CASE WHEN @SEARCHTEXT IS NULL
                 THEN 0
            WHEN PATINDEX(@SEARCHTEXT, [DIA].[TEXT1]) > 0
                 THEN 0
            WHEN PATINDEX(@SEARCHTEXT, [DIA].[SUBJECT]) > 0
                 THEN 0
            WHEN [FN].[NAME] IS NULL
                 THEN 1
            WHEN PATINDEX(@SEARCHTEXT, [FN].[NAME]) > 0
                 THEN 0
            ELSE 1 END = 0

       -- Use the CASE Construct to ensure it doesn't perform SELECT until an actual filter is specified - Performance!
   AND CASE WHEN @FromDate IS NULL
                 THEN 0
            WHEN [DIA].[DATE] >= @FromDate
                 THEN 0
            ELSE 1 END = 0

       -- Use the CASE Construct to ensure it doesn't perform SELECT until an actual filter is specified - Performance!
   AND CASE WHEN @ToDate IS NULL
                 THEN 0
            WHEN [DIA].[DATE] < @ToDate
                 THEN 0
            ELSE 1 END = 0

       -- Use the CASE Construct to ensure it doesn't perform SELECT until an actual filter is specified - Performance!
   AND (@ACTIONTYPESFILTERED = 0 Or ([DIA].[ActionType] in (SELECT * FROM @ACTIONTYPES)))

   --    -- Use the CASE Construct to ensure it doesn't perform SELECT until an actual filter is specified - Performance!
   AND (@PRIORITIESFILTERED = 0 OR ([DIA].[Priority] IN (SELECT * FROM @Priorities)))

   --    -- Use the CASE Construct to ensure it doesn't perform SELECT until an actual filter is specified - Performance!
   AND (@FLAGSFILTERED = 0 OR (ISNULL([DIA].[Flag], 0) IN (SELECT * FROM @Flags)))

-- The Order By Clause is only required here, as further down the @FOUND table will return values ordered by [id]
-- which is the exact order they were entered into it here - Again, Performance!
ORDER BY [DIA].[CASECODE] ASC,
         [DIA].[STATUS] ASC,
         [DIA].[DATE] DESC,
         [DIA].[DYSTARTTIME] DESC,
         [DIA].[ACTIONID] DESC

--for debugging uncomment this below line, after completion please dont forget to uncomment
--select * from @FOUND

DECLARE @TOTAL INT
SET @TOTAL = (SELECT COUNT(1) FROM @FOUND)

SELECT @TOTAL AS [TotalRecords]


declare @HandlerTimeZone nvarchar(100)




-- Only do the full SELECT with all columns when returning the actual result set. Driven from @FOUND
SELECT --[FND].[id],
        RTRIM(ISNULL([DIA].[CASECODE], ''))                                                                 AS [CASECODE],
        --CONVERT(VARCHAR, [DIA].[DATE], 20)    AS [DATE],
        --CONVERT(VARCHAR(5), [DIA].[DATE], 108)                                                              AS [Time],
		dbo.KAAS_CP_FNConvertUTCDateToTargetTimeZone([DIA].[DATE], @LoginId)								AS [DATE],
		CONVERT(VARCHAR(5),dbo.KAAS_CP_FNConvertUTCDateToTargetTimeZone([DIA].[DATE], @LoginId), 108)		AS [Time],
        RTRIM(ISNULL([DIA].[STATUS], 0))                                                                    AS [DStatus],
        RTRIM(ISNULL([DIA].[ACTIONCODE], ''))                                                               AS [ACTIONCODE],
        RTRIM(ISNULL([DIA].[ACTIONTYPE], ''))                                                               AS [ACTIONTYPE],
        RTRIM(ISNULL([DIA].[PROCESSTYPE], ''))                                                              AS [PROCESSTYPE],
        RTRIM(ISNULL([DIA].[FNCODE], ''))                                                                   AS [FNCODE],
        RTRIM(ISNULL([FN].[NAME], ''))                                                                      AS [FNNAME],
        RTRIM(ISNULL([DIA].[TEAMCODE], ''))                                                                 AS [TEAMCODE],
        RTRIM(ISNULL([DIA].[DisplayText], ''))                                                              AS [TEXT1],
		CAST(RTRIM(LTRIM(CAST([DIA].[TEXT1] AS nVARCHAR(max)))) AS TEXT)									AS [TEXT2],  
        ISNULL(CASE WHEN ISNUMERIC([DIA].[DYSTARTTIME]) = 1
                         THEN [DIA].[DYSTARTTIME]
                    ELSE [dbo].[ky_ConvertTimeToClarion]([DIA].[DYSTARTTIME]) END,
               0)                                                                                           AS [DYSTARTTIME],
        ISNULL(CASE WHEN ISNUMERIC([DIA].[DYENDTIME]) = 1
                         THEN [DIA].[DYENDTIME]
                    ELSE [dbo].[ky_ConvertTimeToClarion]([DIA].[DYENDTIME]) END,
               0)                                                                                           AS [DYENDTIME],
        ISNULL([DIA].[ACTIONID],0)                                                                          AS [ACTIONID],
        ISNULL([DIA].[ORGINALACTIONID],0)                                                                   AS [ORGINALACTIONID],
        RTRIM(ISNULL([DIA].[PRIORITY], ''))                                                                 AS [PRIORITY],
        RTRIM(ISNULL([DIA].[HIGHLIGHTED], 'N'))                                                             AS [HIGHLIGHTED],
        [HAT].[HasAttachments]                                                                              AS [ATTACHMENTS],
        ISNULL([DIA].[PROCESSSTATUS], 0)                                                                    AS [PROCESSSTATUS],
        ISNULL([DIA].[WORKPROCESS], 0)                                                                      AS [WORKPROCESS],
        ISNULL([DIA].[BILLABLE], 0)                                                                         AS [BILLABLE],
        RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))                                                             AS [EMAILADDRESS],
        RTRIM(ISNULL(CONVERT(VARCHAR(200), [DIA].[ADDRESSTO]), ''))                                         AS [ADDRESSTO],
        RTRIM(ISNULL([DIA].[EMAIL], 'N'))                                                                   AS [EMAIL],
        RTRIM(ISNULL(CONVERT(VARCHAR(200), [DIA].[SUBJECT]), ''))                                           AS [SUBJECT],
        ISNULL([DIA].[DELEGATIONSTATUS], 0)                                                                 AS [DELEGATIONSTATUS],
        ISNULL([DIA].[DRAFTBILLNO], 0)                                                                      AS [DRAFTBILLNO],
        ISNULL([DIA].[CHEQUEREQNO], 0)                                                                      AS [CHEQUEREQNO],
        CAST(CASE WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE],'')) ='E'
                   AND @ShowFromToSynopsis = 1
      THEN CASE WHEN ISNULL([DIA].[PROCESSTYPE],'O')='I'
                                      THEN   'Email From:'
                                           + (RTRIM(ISNULL(CAST([DIA].[EMAILADDRESS] AS VARCHAR(300)),
                                                           '')))
                                           + ' - '
                                           + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(300)),'')
                                 ELSE   'Email To:'
                                      + RTRIM(CAST(ISNULL([DIA].[AddressTo],
                                                          '') AS VARCHAR(300)))
                                      + ' - '
                                      + ISNULL(CAST([DIA].[Subject] AS VARCHAR(300)), '') END
                  ELSE CASE WHEN DATALENGTH([DIA].[SUBJECT]) = 0
                                 THEN CASE WHEN SUBSTRING([DIA].[DisplayText],
                                                          0,
                                                          CHARINDEX(CHAR(13),
                  [DIA].[DisplayText])) = ''
                                                THEN ISNULL([DIA].[TEXT1], '')
                                           ELSE SUBSTRING([DIA].[DisplayText],
                                                          0,
                                                          CHARINDEX(CHAR(13),
                                                                    [DIA].[DisplayText])) END
                            WHEN RTRIM(CAST([DIA].[SUBJECT] AS VARCHAR(300))) = ''
                                 THEN CASE WHEN SUBSTRING([DIA].[DisplayText],
                                                          0,
                                                          CHARINDEX(CHAR(13),
                                                                    [DIA].[DisplayText])) = ''
                                                THEN ISNULL([DIA].[TEXT1], '')
                                           ELSE SUBSTRING([DIA].[DisplayText],
                                                          0,
                                                          CHARINDEX(CHAR(13),
                                                                    [DIA].[DisplayText])) END
                            WHEN [DIA].[SUBJECT] IS NULL
                                 THEN CASE WHEN SUBSTRING([DIA].[DisplayText],
                                                          0,
                                                          CHARINDEX(CHAR(13),
                                                                    [DIA].[DisplayText])) = ''
                                                THEN ISNULL([DIA].[TEXT1], '')
                                           ELSE SUBSTRING([DIA].[DisplayText],
                                                          0,
                                                          CHARINDEX(CHAR(13),
                                                                    [DIA].[DisplayText])) END
                            ELSE [DIA].[SUBJECT] END END AS VARCHAR(300))                                   AS [Synopsis],
        ISNULL([DIA].[Flag],0)                                                                              AS [Flag],
        CASE WHEN RTRIM(ISNULL([DIA].[ForCopy], 0)) = '1'
                  THEN 'True'
             ELSE 'False' END                                                                               AS [ForCopy],
        CASE WHEN ISNULL([DIA].[WORKPROCESS], 0) = 1
              AND ISNULL([DIA].[STATUS], 0) <> 1
                  THEN 'G'
             WHEN ISNULL([DIA].[STATUS], 0) = 1
                  THEN 'C'
             ELSE '' END                                                                                    AS [COMPELETEORGENERATE],
        CASE WHEN ISNULL([DIA].[WORKPROCESS], 0) = 1
              AND ISNULL([DIA].[STATUS], 0) <> 1
          THEN 'G'
             WHEN ISNULL([DIA].[STATUS], 0) = 1
                  THEN 'C'
             ELSE '' END                                                                                    AS [COMPELETEORGENERATEDD],
        ISNULL([TAC].[DESC], '')                                                                            AS [ActionTitle],
        ISNULL([TMP].[WKDESC], '')                                                                          AS [WorkFlow],
        CASE WHEN ISNULL([UND].[NeedsAttention], 0) = 1
                  THEN 'Yes'
             ELSE 'No' END                                                                                  AS [Needs Attention],
        CASE WHEN ISNULL([UND].[NeedsAttention], 0) = 1
                  THEN 'Visible'
             ELSE 'Collapsed' END                                                                           AS [NeedsAttentionIcon],
        CASE WHEN @SearchText IS NULL
                  THEN ''
             WHEN PATINDEX(@SearchText, [DIA].[TEXT1]) > 0
                  THEN @Search
             ELSE '' END                                                                                    AS [SearchMatch],
        ISNULL([DIA].[CreationDate], CONVERT(DATETIME, [DIA].[DATE]))                                       AS [CreationDate],
		CASE
			WHEN [DIA].[DUEDATE] != NULL OR [DIA].[DUEDATE] != ''
				THEN CONVERT(VARCHAR, dbo.KAAS_CP_FNConvertUTCDateToTargetTimeZone([DIA].[DUEDATE], @LoginId)	, 20)
			ELSE
				CONVERT(VARCHAR, dbo.KAAS_CP_FNConvertUTCDateToTargetTimeZone([DIA].[DATE], @LoginId)	, 20)
		END                                                                                                 AS [DUEDATE], 
        RTRIM(ISNULL([DIA].[DELEGATEDFNR], ''))                                                             AS [DelegatedFE],
        RTRIM(ISNULL([TAC].[Arrangement], ''))                                                              AS [Arrangement],
        @ChargeArrangement                                                                                  AS [ChargeArrangement]

 FROM @FOUND [FND]
        INNER JOIN [dbo].[diary] [DIA]
                   LEFT OUTER JOIN [dbo].[Handlers] [FN]
                                ON [FN].[CODE] = [DIA].[FNCODE]
                ON [DIA].[ActionID] = [FND].[ActionID]
        LEFT OUTER JOIN [dbo].[TemplateActions] [TAC]
                        LEFT OUTER JOIN [dbo].[Templates] [TMP]
                                     ON [TMP].[WKCODE] = [TAC].[WKTCODE]
                    ON [TAC].[ACTIONCODE] = [DIA].[ACTIONCODE]
        LEFT OUTER JOIN [dbo].[Undertakings] [UND]
                    ON [UND].[ActionID] = [DIA].[ACTIONID]
                    AND [UND].[ActionID] <> 0
                    AND [UND].[ActionID] IS NOT NULL
        CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                      THEN 'N'
                                ELSE 'Y' END AS [HasAttachments]
                       FROM [dbo].[DiaryAttachments] [DAT]
                      WHERE [DAT].[DiaryID] = [DIA].[ACTIONID]) [HAT]
  WHERE CASE WHEN @PageNumber = 0
                  THEN 0
             WHEN [FND].[ID] <= (@PageNumber - 1) * @PageSize
                  THEN 1
             WHEN [FND].[ID] > @PageNumber * @PageSize
                  THEN 1
             ELSE 0 END = 0
			 AND ISNULL([DIA].PUBLISH, '') = 'P'
 ORDER BY [FND].[id]

End
GO

/****** Object:  StoredProcedure [dbo].[KAAS_GenerateCaseAssociateCode]    Script Date: 21/01/2015 12:44:29 ******/

IF OBJECT_ID(N'KAAS_CP_GenerateCaseAssociateCode',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_GenerateCaseAssociateCode]
GO
CREATE PROCEDURE
       [dbo].[KAAS_CP_GenerateCaseAssociateCode]      
      (@code    VARCHAR(100),      
       @result  VARCHAR(100) OUTPUT)      
      
AS        
/*******************************************************************************************************
* This procedure is used to Generate Case Associate code.				  							   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_GenerateCaseAssociateCode]									   *
* Copied from			: [dbo].[KAAS_GenerateCaseAssociateCode]									   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-05-31	Vinodhan K		    Created                                                            *
* 2022-04-20	Vinodhkumar.M		Created for client portal                                          *
 *******************************************************************************************************/
BEGIN      
 SET NOCOUNT ON      
 DECLARE @var    VARCHAR(100)      
 DECLARE @var1   VARCHAR(100)      
 DECLARE @zero   VARCHAR(100)      
 DECLARE @len    INT      
 DECLARE @i      INT      
 DECLARE @k      VARCHAR(100)      
       
 SET @k='0'      
 SET @i = 0      
 SET @zero = '';      
       
   IF(@code <> '')
       BEGIN
            SELECT 
                @var = MAX(SUBSTRING(CODE,LEN(@code)+1,6-LEN(@code)))+1 
            FROM 
                CaseAssociatesNames 
            WHERE 
                CODE 
            LIKE 
                @Code+'[0-9]%'  
       END
       ELSE
       BEGIN
            SELECT 
                @var = MAX(SUBSTRING(CODE,LEN(@code)+1,6-LEN(@code)))+1 
            FROM 
                CaseAssociatesNames 
            WHERE 
                CODE 
            NOT LIKE 
                @Code+'%[^0-9]%'  
       END  
   --PRINT @var;      
    IF @var <> ''      
    BEGIN      
        SET @var1 = (@code+@var);      
        SET @len = LEN(@var1);      
        --PRINT @var;      
        --PRINT @len;      

        WHILE @i < (6-@len) 
        BEGIN      
            SET @i = @i + 1      
            SET @zero = (@k+@zero);      
        END      
        SET @result = (@code+@zero+@var);      
    END      
    ELSE      
    BEGIN      
        --PRINT @code;      
        SET @len = LEN(@code);      
        --PRINT @code;      
        WHILE @i < (5-@len) 
        BEGIN      
            SET @i = @i + 1      
            SET @zero = (@k+@zero);      
        END     
        SET @result = (@code+@zero+'1');      
        IF(@len = 6) BEGIN      
            SET @result = @code;      
        END      
        --PRINT @result;      
    END      
 SET NOCOUNT OFF      
END   
  

GO


IF OBJECT_ID(N'KAAS_CP_GetAccountSummaryDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetAccountSummaryDetails]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_GetAccountSummaryDetails]
    (@MatterCode VARCHAR(20))
AS

/******************************************************************************************************************
*                                                                                                                 *
* Used to fetch account summary details							                                                  *
*                                                                                                                 *
* Stored Procedure Name: [dbo].[KAAS_CP_GetAccountSummaryDetails]                                                 *
* Copied from   :        [dbo].[KAAS_GetMatterLedgerDetail]														  *
*						 [dbo].[ky_NETGetMatterLedger]                                                            *
*						 [dbo].[ky_NETGetMatterLedgerSAM4]                                                        *
*                                                                                                                 *  
* Modification History:                                                                                           *  
* 2021-07-13    Vinodhkumar       Created                                                                         *  
 ******************************************************************************************************************/  
BEGIN    

DECLARE @IsSAM4 bit      
DECLARE @Query NVARCHAR(200)

SET @IsSAM4 = [dbo].[ISSAM4]()    

EXECUTE KAAS_GetMatterLedger @MatterCode

/*Account Summary*/  
DECLARE @NCOMMAND nvarchar(MAX)  
      
DECLARE @DraftBillValue DECIMAL(18, 2)  
      
IF @IsSAM4 = 0      
  BEGIN      
    SET @NCOMMAND = N'      
  SELECT @DraftBillValue = ISNULL(SUM(ISNULL(BD.[NET], 0)), 0) + ISNULL(SUM(ISNULL(BD.[VATVALUE], 0)), 0)      
    FROM [dbo].[BillHeader] HED      
         INNER JOIN [dbo].[BillDetails] BD      
                 ON BD.[DRAFTNO] = HED.[DRAFTNO]      
   WHERE HED.[MATTER] = @MatterCode      
     AND HED.[BILLNO] = 0'      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = N'      
  SELECT @DraftBillValue = ISNULL(SUM(ISNULL(BD.[NetValue], 0)), 0) + ISNULL(SUM(ISNULL(BD.[VatValue], 0)), 0)      
    FROM [dbo].[BillHead] HED      
         INNER JOIN [dbo].[BillDetail] BD      
                 ON BD.[BillID] = HED.[BillingID]      
   WHERE HED.[MatterCode] = @MatterCode      
     AND HED.[BillStatus] <> ''Approved''      
     AND ISNULL(HED.[ProForma], '''') = ''Y'''      
  END      
EXECUTE sp_executesql @NCOMMAND, N'@MatterCode VARCHAR(20),@DraftBillValue DECIMAL(18, 2) OUTPUT', @MatterCode = @MatterCode, @DraftBillValue=@DraftBillValue OUTPUT      
      
DECLARE @Section68    VARCHAR(10)      
DECLARE @IsApproved   VARCHAR(10)      
DECLARE @TimeBal      INT      
DECLARE @ChargeBal    DECIMAL(19, 2)      
DECLARE @TotalCharge  Decimal(19, 2)      
DECLARE @TotalTime    INT      
      
--Matter values that are re-used elsewhere in this procedure.      
SELECT @Section68 = ISNULL(MAT.[Section68],''),      
       @IsApproved = ISNULL(CON.[Approved],'')      
  FROM [dbo].[matters] MAT      
       LEFT OUTER JOIN [dbo].[Contacts] CON      
                    ON CON.[Code] = MAT.[ClientCode]      
 WHERE MAT.[Code]  = @MatterCode      
      
DECLARE @LDIADATE DATETIME      
DECLARE @LDIAACTIONTYPE VARCHAR(1)      
DECLARE @LDIATEXT1 VARCHAR(MAX)      
DECLARE @LDIAFNCODE VARCHAR(10)      
      
  SELECT TOP 1      
         @LDIADATE = LDIA.[DATE],      
         @LDIAACTIONTYPE = LDIA.[ACTIONTYPE],      
         @LDIATEXT1 = LDIA.[TEXT1],      
         @LDIAFNCODE = LDIA.[FNCODE]      
    FROM [dbo].[diary] LDIA      
   WHERE LDIA.[CASECODE] = @MatterCode      
ORDER BY LDIA.[DATE] DESC      
      
DECLARE @MDIADATE DATETIME      
DECLARE @MDIAACTIONTYPE VARCHAR(1)      
DECLARE @MDIATEXT1 VARCHAR(MAX)      
DECLARE @MDIAFNCODE VARCHAR(10)      
      
  SELECT TOP 1      
         @MDIADATE= MDIA.[DATE],      
         @MDIAACTIONTYPE = MDIA.[ACTIONTYPE],      
         @MDIATEXT1 = MDIA.[TEXT1],      
         @MDIAFNCODE = MDIA.[FNCODE]      
    FROM [dbo].[diary] MDIA      
   WHERE MDIA.[CASECODE] = @MatterCode      
     AND MDIA.[HIGHLIGHTED] = 'Y'      
ORDER BY MDIA.[DATE] DESC      
      
DECLARE @NDIADATE DATETIME      
DECLARE @NDIAACTIONTYPE VARCHAR(1)      
DECLARE @NDIATEXT1 VARCHAR(MAX)      
DECLARE @NDIAFNCODE VARCHAR(10)      
      
  SELECT TOP 1      
         @NDIADATE = NDIA.[DATE],      
         @NDIAACTIONTYPE = NDIA.[ACTIONTYPE],      
         @NDIATEXT1 = NDIA.[TEXT1],      
         @NDIAFNCODE = NDIA.[FNCODE]      
    FROM dbo.[diary] NDIA      
   WHERE NDIA.[CASECODE] = @MatterCode      
     AND NDIA.[STATUS] = 0      
ORDER BY NDIA.[DATE] ASC      
      
DECLARE @TIEDATE DATETIME      
      
--Pino 2015-05-27 Start      
--SELECT @TIEDATE = (MAX(TIE.[DATE]))      
--  FROM [dbo].[TimeEntry] TIE      
-- WHERE TIE.[Matter] = @MatterCode      
IF [dbo].[ISSAM4]() = 0      
  BEGIN      
    SET @NCOMMAND = N'      
        SELECT @TIEDATE = MAX(CASE WHEN DLG.[DATE] IS NULL      
                                        THEN CONVERT(DATETIME, NULL)      
                                   WHEN DLG.[DATE] > GETDATE()      
                                        THEN CONVERT(DATETIME, NULL)      
                                   ELSE DLG.[DATE] END)      
          FROM [dbo].[DebtorsLedger] DLG      
         WHERE DLG.[MATTER] = @MatterCode'      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = N'      
        SELECT @TIEDATE = MAX(CASE WHEN TRN.[TransDate] IS NULL      
                                        THEN CONVERT(DATETIME, NULL)      
                                   WHEN TRN.[TransDate] > GETDATE()      
  THEN CONVERT(DATETIME, NULL)      
                                   ELSE TRN.[TransDate] END)      
          FROM [dbo].[Transactions] TRN      
         WHERE TRN.[Posted] = ''Y''      
           AND TRN.[MatterCode] = @MatterCode      
           AND TRN.[DebtorsValue] <> 0      
           AND TRN.[CorrectionInd] = ''L''      
           AND (   (    TRN.[XnType] = ''I''      
                    AND TRN.[RecType] = ''H'')      
                OR (    TRN.[XnType] = ''J''      
                    AND TRN.[RecType] = ''D''))'      
  END      
      
EXECUTE sp_executesql @NCOMMAND, N'@MatterCode VARCHAR(20), @TIEDATE DATETIME OUTPUT', @MatterCode = @MatterCode, @TIEDATE = @TIEDATE OUTPUT      
--Pino 2015-05-27 End      
      
DECLARE @LastTimeEntryDate            DATETIME      
DECLARE @LastTimeEntryTime            INT      
DECLARE @LastTimeEntryRate            DECIMAL(10, 2)      
DECLARE @LastTimeEntryCharge          DECIMAL(10, 2)      
DECLARE @LastTimeEntryTask            VARCHAR(6)      
DECLARE @LastTimeEntryComment         VARCHAR(1000)      
DECLARE @LastTimeEntryFE              VARCHAR(10)      
DECLARE @TimeEntryTotalCharge         DECIMAL(19, 2)      
DECLARE @TimeEntryTotalTime           INT      
      
  SELECT TOP (1)      
         @LastTimeEntryDate    = TIE.[DATE],      
         @LastTimeEntryTime    = TIE.[Time],      
         @LastTimeEntryRate    = TIE.[Rate],      
         @LastTimeEntryCharge  = TIE.[Charge],      
         @LastTimeEntryTask    = TIE.[Task],      
         @LastTimeEntryComment = TIE.[Comment],      
         @LastTimeEntryFE      = TIE.[FeeEarn]      
    FROM [dbo].[TimeEntry] TIE      
   WHERE TIE.[Matter] = @MatterCode      
     AND (   (TIE.[TimeOrCharge] = 'T')      
          OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun      
ORDER BY TIE.[Date] DESC,      
         TIE.[Time] DESC      
      
SET @LastTimeEntryRate = ISNULL(@LastTimeEntryRate, 0)      
SET @LastTimeEntryCharge = ISNULL(@LastTimeEntryCharge, 0)      
      
-- Please see also: ky_NETFNMatterClosable. If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
--                  ky_NETPMatterClosable.  If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
--                  ky_NETTLFetchTimeEntry. If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
SELECT @TimeEntryTotalCharge = ISNULL(SUM(ISNULL(TIE.[Charge], 0)), 0),      
       @TimeEntryTotalTime = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0),      
       @TotalCharge = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'      
                                      THEN 0      
                                 ELSE ISNULL(TIE.[Charge], 0) END), 0),      
       @ChargeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'      
                                         THEN 0      
       WHEN @IsSAM4 = 1      
                                     AND ISNULL(TIE.[InvoiceNo], 0) <> 0      
                                         THEN 0      
                                    WHEN @IsSAM4 = 1      
                                         THEN ISNULL(TIE.[Charge], 0)      
                                    ELSE ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0) END), 0),      
       @TimeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'      
                                       THEN 0      
                                  WHEN @IsSAM4 = 1      
                                   AND ISNULL(TIE.[InvoiceNo], 0) <> 0      
                                       THEN 0      
                                  WHEN @IsSAM4 = 0      
                                       THEN CASE WHEN TIE.[Charge] = 0      
                                                      THEN 0      
                    ELSE CONVERT(INT,      
                                                              FLOOR(CONVERT(DECIMAL(18, 2), TIE.[TIME])      
                                                                    * (  (TIE.[Charge] - TIE.[BilledAmount])      
                                                                       /      
                                                                       TIE.[Charge]))) END      
                                  ELSE ISNULL(TIE.[Time], 0) END), 0),      
       @TotalTime = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'      
                                         THEN 0      
                                    ELSE ISNULL(TIE.[Time], 0) END), 0)      
  FROM [dbo].[TimeEntry] TIE      
 WHERE TIE.[Matter] = @MatterCode      
   AND (   (TIE.[TimeOrCharge] = 'T')      
        OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun      
      
DECLARE @DebtBal        DECIMAL(19, 2)      
DECLARE @OutlayBal      DECIMAL(19, 2)      
DECLARE @DebtBalDate    DATETIME      
DECLARE @OutlayBalDate  DATETIME      
DECLARE @ClientCurrent  DECIMAL(19, 2)      
DECLARE @ClientDeposit  DECIMAL(19, 2)      
      
-- Please see also: ky_NETFNMatterClosable. If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
--                  ky_NETTLFetchTimeEntry. If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
-- To ensure SAM3 will retrieve these from [dbo].[matters]      
SET @DebtBal = 0      
SET @OutlayBal = 0      
SET @ClientCurrent = 0      
SET @ClientDeposit = 0      
IF @IsSAM4 = 1      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT @DebtBal = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[DebtorsValue], 0)), 0)),      
       @DebtBalDate = MAX(CASE WHEN ISNULL(TRN.[DebtorsValue], 0) = 0 THEN NULL ELSE TRN.[TransDate] END),      
       @OutlayBal = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[OutlayValue], 0)), 0)),      
       @OutlayBalDate = MAX(CASE WHEN ISNULL(TRN.[OutlayValue], 0) = 0 THEN NULL ELSE TRN.[TransDate] END),      
       @ClientCurrent = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[ClientCurrent], 0)), 0)),      
       @ClientDeposit = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[ClientDeposit], 0)), 0))      
  FROM [dbo].[Transactions] TRN      
 WHERE TRN.[MatterCode] = @MatterCode      
   AND TRN.[Posted] = ''Y''      
   AND TRN.[RecType] <> ''V''      
   AND TRN.[CorrectionInd] = ''L'''      
EXECUTE sp_executesql @NCOMMAND,      
                      N'@MatterCode VARCHAR(20),      
                        @DebtBal DECIMAL(19, 2) OUTPUT,      
                        @DebtBalDate DATETIME OUTPUT,      
                        @OutlayBal DECIMAL(19, 2) OUTPUT,      
                        @OutlayBalDate DATETIME OUTPUT,      
                        @ClientCurrent DECIMAL(19, 2) OUTPUT,      
                        @ClientDeposit DECIMAL(19, 2) OUTPUT',      
                      @MatterCode      = @MatterCode,      
                      @DebtBal       = @DebtBal OUTPUT,      
        @DebtBalDate   = @DebtBalDate OUTPUT,      
                      @OutlayBal     = @OutlayBal OUTPUT,      
                      @OutlayBalDate = @OutlayBalDate OUTPUT,      
                      @ClientCurrent = @ClientCurrent OUTPUT,      
                      @ClientDeposit = @ClientDeposit OUTPUT      
  END      

--Result Set 0      
--Matter Data      
SELECT RTRIM(ISNULL(MAT.[Code], ''))                                                  AS [Code],   
       RTRIM(ISNULL(MAT.[Description], ''))                                           AS [Description],      
       RTRIM(ISNULL(MAT.[ClientCode], ''))                                            AS [ClientCode],      
       RTRIM(ISNULL(CLT.[CLNAME], ''))                                                AS [CLName],      
       RTRIM(ISNULL(CLT.[CLADDR], ''))                                                AS [CLAddr],      
       RTRIM(ISNULL(MAT.[FECode], ''))                                                AS [FECode],      
       RTRIM(ISNULL(HAN.[NAME], ''))                                                  AS [HandlerName],      
       RTRIM(ISNULL(MAT.[Dept], ''))                                                  AS [Dept],      
       RTRIM(ISNULL(DPT.[DESC], ''))                                                  AS [Desc],      
       RTRIM(MAT.WType)                                                               AS [WType],      
       RTRIM(ISNULL(WKT.[DESC], ''))                                                  AS [WorkType],      
       MAT.[Started]                                                                  AS [Started],      
       MAT.[EstFee]                                                                   AS [EstFee],      
       MAT.[ExpBillD]                                                                 AS [ExpBillD],      
       CONVERT(DECIMAL(19, 2), CASE WHEN @DebtBal <> 0      
                                         THEN @DebtBal      
                                    ELSE ISNULL(MAT.[DebtBal], 0) END)                AS [DebtBal],      
       CONVERT(DECIMAL(19, 2), CASE WHEN @OutlayBal <> 0      
                                         THEN @OutlayBal      
                                    ELSE ISNULL(MAT.[OutlayBal], 0) END)              AS [OutlayBal],      
       MAT.[OutlayBud]                                                                AS [OutlayBud],      
       CONVERT(DECIMAL(19, 2), CASE WHEN @ClientCurrent <> 0      
                                         THEN @ClientCurrent + @ClientDeposit      
                                    WHEN @ClientDeposit <> 0      
                                         THEN @ClientCurrent + @ClientDeposit      
                                    ELSE ISNULL(MAT.[ClientBal], 0) END)              AS [ClientBal],      
       CONVERT(DECIMAL(19, 2), CASE WHEN @ClientCurrent <> 0      
                                         THEN @ClientCurrent      
                                    ELSE ISNULL(MAT.[ClientCurBal], 0) END)           AS [ClientCurBal],      
       CONVERT(DECIMAL(19, 2), CASE WHEN @ClientDeposit <> 0      
                                         THEN @ClientDeposit      
                                    ELSE ISNULL(MAT.[ClientDepBal], 0) END)           AS [ClientDepBal],      
       MAT.[StatuteLimits]                                                            AS [StatuteLimits],      
       RTRIM(ISNULL(MAT.[User1], ''))                                                 AS [User1],      
       RTRIM(ISNULL(MAT.[User2], ''))                                                 AS [User2],      
       RTRIM(ISNULL(MAT.[User3], ''))                                                 AS [User3],      
       MAT.[Value]                                                                    AS [Value],      
       @TimeBal                                                                       AS [TimeBal],  
		 CASE
			WHEN
				LEN(@TimeBal / 60) < 2
			THEN
				'0' +  CAST(@TimeBal / 60 AS VARCHAR)
			ELSE
				CAST(@TimeBal / 60 AS VARCHAR)
		 END
       + ':'      
       + SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(INT, @TimeBal) % 60), 2, 2)      AS [TimeBalHours],      
       @ChargeBal                                                                     AS [ChargeBal],      
		 CASE
			WHEN
				LEN(@TotalTime / 60) < 2
			THEN
				'0' +  CAST(@TotalTime / 60 AS VARCHAR)
			ELSE
				CAST(@TotalTime / 60 AS VARCHAR)
		 END
       + ':'      
       + SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(INT, @TotalTime) % 60), 2, 2)    AS [TotalHours],      
       @TotalCharge                                                                   AS [TotalCharge],      
       MAT.[FileColour]                                                               AS [FileColour],      
       RTRIM(ISNULL(MAT.[OldRef], ''))                                                AS [OldRef],      
       RTRIM(ISNULL(MAT.[Status], ''))           AS [Status],      
       MAT.[StatuteLimits]                                                            AS [StatuteLims],      
       RTRIM(ISNULL(MAT.[Comment], ''))                                               AS [Comment],      
       @DraftBillValue                                                                AS [DraftBillTotal],      
       @TIEDATE                                                                       AS [LastBillDate],      
       @LDIADATE                                                                      AS [LastActionDate],      
       RTRIM(ISNULL(@LDIAActionType, ''))                                             AS [LastActionType],      
       RTRIM(ISNULL(@LDIATEXT1, ''))                                                  AS [LastActionText],      
       RTRIM(ISNULL(@LDIAFNCODE, ''))                                                 AS [LastActionFE],      
       @MDIADATE                                                                      AS [LastMilestoneDate],      
       RTRIM(ISNULL(@MDIAActionType, ''))                                             AS [LastMilestoneType],      
       RTRIM(ISNULL(@MDIATEXT1, ''))                                                  AS [LastMilestoneText],      
       RTRIM(ISNULL(@MDIAFNCODE, ''))                                                 AS [LastMilestoneFE],      
       @NDIADATE                                                                      AS [NextActionDate],      
       RTRIM(ISNULL(@NDIAActionType, ''))                                             AS [NextActionType],      
       RTRIM(ISNULL(@NDIATEXT1, ''))                                                  AS [NextActionText],      
       RTRIM(ISNULL(@NDIAFNCODE, ''))                                                 AS [NextActionFE],      
       @LastTimeEntryDate                                                             AS [LastTimeEntryDate],      
       @LastTimeEntryTime                                                             AS [LastTimeEntryTime],      
       @LastTimeEntryRate                                                             AS [LastTimeEntryRate],      
       @LastTimeEntryCharge                                                           AS [LastTimeEntryCharge],      
       @LastTimeEntryTask                                                             AS [LastTimeEntrytask],      
       @LastTimeEntryComment                                                          AS [LastTimeEntryComment],      
       @LastTimeEntryFE                                                               AS [LastTimeEntryFE],      
       @TimeEntryTotalCharge                                                          AS [TimeEntryTotalCharge],      
       @TimeEntryTotalTime                                                            AS [TotalTime],      
       STC.[DESCRIPTION]                                                              AS [StatusCodeDescription],      
       CSM.[CSWKTCODE]                                                                AS [CSWKTCode],      
       TMP.[WKDESC]                                                                   AS [WKDesc],      
       CASE WHEN MAT.[ShowCommentInAlarm] = 'Y'      
                 THEN 'True'      
            ELSE 'False' END                                                          AS [ShowCommentInAlarm],      
       RTRIM(ISNULL(FCL.[COLOURDESC], ''))                                            AS [FileColourDescription],      
       ISNULL(FCL.[RGBColour], -1)                                                   AS [FileColourRGB],      
       @Section68                                                                     AS [Section68],      
       @IsApproved                                                                    AS [IsApproved]      
  FROM dbo.[matters] MAT      
       LEFT JOIN dbo.[WorkTypes] WKT      
               ON WKT.[CODE] = MAT.[WType]      
       LEFT OUTER JOIN dbo.[Departments] DPT      
              ON DPT.[CODE] = MAT.[Dept]      
       LEFT OUTER JOIN dbo.[Handlers] HAN      
                    ON HAN.[CODE] = MAT.[FECode]      
       LEFT OUTER JOIN dbo.[client] CLT      
                    ON CLT.[CLCODE] = MAT.[ClientCode]      
       LEFT OUTER JOIN dbo.[StatusCodes] STC      
                    ON STC.[CODE] = MAT.[Status]      
       LEFT OUTER JOIN dbo.[CaseMaster] CSM      
                       LEFT OUTER JOIN dbo.[Templates] TMP      
                                    ON TMP.[WKCODE] = CSM.[CSWKTCODE]      
                    ON CSM.[CSCODE] = MAT.[Code]      
       LEFT OUTER JOIN [dbo].[FileColours] FCL      
                    ON FCL.[COLOURCODE] = MAT.[FileColour]      
 WHERE MAT.[Code] = @MatterCode  
  
--Result Set 6      
--Total Time  [Activity]      
SELECT
         CASE
			WHEN
				LEN(TIES.[TOTALTIME] / 60) < 2
			THEN
				'0' +  CAST(TIES.[TOTALTIME] / 60 AS VARCHAR)
			ELSE
				CAST(TIES.[TOTALTIME] / 60 AS VARCHAR)
	     END
       + ':'      
       + SUBSTRING(CONVERT(VARCHAR(3), 100 + (TIES.[TOTALTIME] % 60)), 2, 2)                   AS [ActivityTotalTime],      
       TIES.[Value]                                                                            AS [ActivityTotalValue]      
  FROM (  SELECT ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)                   AS [TOTALTIME],      
                 SUM(CONVERT(DECIMAL(18, 2), ISNULL(TIE.[Charge], 0)))   AS [Value]      
            FROM [dbo].[matters] MAT      
                 INNER JOIN [dbo].[TimeEntry] TIE      
                         ON TIE.[MATTER] = MAT.[Code]      
           WHERE TIE.[MATTER] = @MatterCode      
             AND (   (TIE.[TimeOrCharge] = 'T')      
                  OR (TIE.[TimeOrCharge] = 'C'))      
             AND TIE.[TASK] <> 'WRI') TIES      
  
--Result Set 7      
--Write off time      
SELECT TIES.[WriteOffValue] As [WriteOffValue]      
  FROM (  SELECT SUM(CONVERT(DECIMAL(18, 2), ISNULL(TIE.[Charge], 0))) AS [WriteOffValue]      
            FROM [dbo].[matters] MAT      
                 INNER JOIN [dbo].[TimeEntry] TIE      
                         ON TIE.[MATTER] = MAT.[Code]      
           WHERE TIE.[MATTER] = @MatterCode      
             AND (   (TIE.[TimeOrCharge] = 'T')      
                  OR (TIE.[TimeOrCharge] = 'C'))      
             AND TIE.[Task] = 'WRI') TIES   
  
-- PLEASE NOTE THAT THE CALCULATION BELOW IS ALSO USED IN ky_NETTLFetchTimeEntry, so      
-- please modify both procedures if this needs to be changed.      
-- Result Set 10      
-- The fees issued to date      
    IF @IsSAM4 = 0      
      BEGIN      
        SET @NCOMMAND = N'      
SELECT ISNULL(SUM((CASE WHEN HED.[INVCR] = ''I''      
                             THEN TRN.[VALUE]      
                        ELSE TRN.[VALUE] * - 1 END)), 0) AS [FeesIssued]      
  FROM [dbo].[BatchH] HED      
       INNER JOIN [dbo].[BatchDetails] TRN      
               ON TRN.[BATCHNO] = HED.[BATCHNO]      
 WHERE HED.[MATTER] = @MatterCode      
   AND HED.[POSTED] = ''Y''      
   AND TRN.[TYPE] = ''I''      
   AND TRN.[OUTLAY] = ''F'''      
      END      
    ELSE      
      BEGIN      
        SET @NCOMMAND = N'      
DECLARE @TotalFeesBilled DECIMAL(22, 2)      
      
SELECT @TotalFeesBilled = ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)      
  FROM [dbo].[TransactionsHeaders] HED      
       INNER JOIN [dbo].[Transactions] TRN      
               ON TRN.[BatchNo] = HED.[BatchNo]      
              AND TRN.[RecType] = ''D''      
   AND TRN.[LineType] = ''F''      
              AND TRN.[XnType] = ''I''      
              AND TRN.[Posted] = ''Y''      
              AND (   TRN.[CorrectionInd] = ''L''      
                   OR TRN.[CorrectionInd] = ''X'')      
 WHERE HED.[MatterCode] = @MatterCode      
      
--values imported from Axxia      
SELECT @TotalFeesBilled = @TotalFeesBilled + ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)      
  FROM [dbo].[Transactions] TRN      
       LEFT OUTER JOIN [dbo].[TransactionsHeaders] HED      
                    ON HED.[BatchNo] = TRN.[BatchNo]      
 WHERE TRN.[MatterCode] = @MatterCode      
   AND TRN.[RecType] = ''D''      
   AND TRN.[LineType] = ''F''      
   AND TRN.[XnType] = ''I''      
   AND TRN.[Posted] = ''Y''      
   AND (   TRN.[CorrectionInd] = ''L''      
        OR TRN.[CorrectionInd] = ''X'')      
   AND HED.[BatchNo] IS NULL      
      
SELECT @TotalFeesBilled AS [FeesIssued]'      
      END      
      
EXECUTE sp_executesql @NCOMMAND, N'@MatterCode VARCHAR(20)', @MatterCode = @MatterCode      
      
-- Result Set 11      
-- Current outstanding fees      
IF @IsSAM4 = 0      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(DTL.[OSFees], 0)), 0)) AS [OSFees]      
  FROM [dbo].[DebtorsLedger] DTL      
 WHERE DTL.[matter] = @MatterCode'      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[FeesOS], 0)), 0)) AS [OSFees]      
  FROM [dbo].[Transactions] TRN      
 WHERE TRN.[MatterCode] = @MatterCode      
   AND TRN.[Posted] = ''Y''      
   AND TRN.[RecType] <> ''V''      
   AND TRN.[CorrectionInd] = ''L'''      
  END      
      
EXECUTE sp_executesql @NCOMMAND, N'@MatterCode VARCHAR(20)', @MatterCode = @MatterCode  
  
SELECT @IsSAM4 AS [IsSAM4]
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_GetActionId'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetActionId]
  END
GO

CREATE PROCEDURE [KAAS_CP_GetActionId]
(
    @CASECODE                 VARCHAR(20),
    @FNCODE                   VARCHAR(10),
    @TEAMCODE                 VARCHAR(10),
    @Result                      INT    OUTPUT
)

/*******************************************************************************************************
* This sp used to insert blank action.																   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_GetActionId]											       *
* Copied from			: [dbo].[ky_NETInsertTasksAction]											   *
* Copied from			: [dbo].[KAAS_InsertTasksAction]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
* 2022-02-10	Vinodhkumar.M   Created for Client Portal - upload doument                             *
* 2022-02-10	Vinodhkumar.M   KAAS_CP_GetNextActionId is created instead of KAAS_GetNextActionID
							    KAAS_CP_ConvertTime is created Instead of ky_ConvertTimeToClarion      *
						        for client Portal                                                      *
* 2022-02-15   Vinodhkumar.M   In Inserting diary passing values for due date priority value,
							   Action type and Publish fields										  *
*******************************************************************************************************/ 

AS
BEGIN
SET NOCOUNT ON
--Diary
    DECLARE @TIMECONVERT INT
    SET @TIMECONVERT = dbo.KAAS_CP_ConvertTime(GETDATE())
    DECLARE @ACTIONID    INT

    --Pino 2015-09-30 Start
   -- EXEC @ACTIONID = [dbo].[KAAS_GetNextActionID] 
    --SET @ACTIONID = (SELECT ISNULL(MAX(ACTIONID + 1), 1) FROM [dbo].[diary])
    --Pino 2015-09-30 End

	 -- This SP created for Client Portal Upload
	 EXEC @ACTIONID = [dbo].[KAAS_CP_GetNextActionId] 

    INSERT
      INTO [dbo].[diary]
          ([CASECODE],
           [DATE],
           [STATUS],
           [ACTIONCODE],
           [ACTIONSTATUS],
           [ACTIONTYPE],
           [PROCESSTYPE],
           [FNCODE],
           [TEAMCODE],
           [TEXT1],
           [TEXT2],
           [DELEGATEDFNR],
           [DELEGATEDDATE],
           [DELEGATEDBACKDATE],
           [DEFERRED],
           [DUEDATE],
           [PUBLISH],
           [DYSTARTTIME],
           [DYENDTIME],
           [DURATION],
           [ACTIONID],
           [ORGINALACTIONID],
           [PRIORITY],
           [HIGHLIGHTED],
           [MILESTEONETYPE],
           [ATTACHMENTS],
           [PROCESSSTATUS],
           [WORKPROCESS],
           [BILLABLE],
           [BILLDESCRIPTION],
           [EMAILADDRESS],
           [ADDRESSTO],
           [CCTo],
           [BCCTo],
           [EMAIL],
           [SUBJECT],
           [DELEGATIONSTATUS],
           [DRAFTBILLNO],
           [CHEQUEREQNO],
           [TxmSent],
           [Location],
           [HearingType],
           [ForCopy],
           [TxmDate],
           [TxmSeqNo],
           [DisplayText],
           [Flag])
    VALUES(@CASECODE,
           GETDATE(),
           0,
           null,
           null,
           'A',
           null,
           @FNCODE,
           @TEAMCODE,
           null,
           null,
           null,
           null,
           null,
           null,
           GETDATE(),
           'P',
           @TIMECONVERT,
           @TIMECONVERT,
           0,
           @ACTIONID,
           0,
           'N',
           null,
           null,
           null,
           0,
           0,
           0,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           0,
           0,
           0,
           0,
           null,
           'Not Applicable',
           null,
           null,
           0,
          null,
           0)
    INSERT
              INTO [dbo].[DiaryDelegations]
                  ([ACTIONID],
                   [HANDLER],
                   [TEAM],
                   [DATE],
                   [TIME],
                   [DATER],
                   [TIMER],
                   [DUEDATE],
                   [DUETIME],
                   [REVIEW],
                   [STATUS],
                   [OWNER],
                   [DELEGATE],
                   [DELEGATESTATUS],
                   [ActionType],
                   [FromHandler],
                   [ReturnedBy],
                   [DelType])
            VALUES(@ACTIONID,
                   @FNCODE,
                   @TEAMCODE,
                   GETDATE(),
                   @TIMECONVERT,
                   null,
                   @TIMECONVERT,
                   GETDATE(),
                   @TIMECONVERT,
                   null,
                   0,
                   'Y',
                   @FNCODE,
                   0,
                   null,
                   @FNCODE,
                   null,
                   'Created')
    SET @Result = @ACTIONID
SET NOCOUNT OFF
END

GO
IF OBJECT_ID(N'KAAS_CP_GetAllUserLoginDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetAllUserLoginDetails]
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_CP_GetAllUserLoginDetails]

AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetAllUserLoginDetails]   									   *
* Description: To get login details for all users in system											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-06    Aakif				 Created                                                           *
* 2022-07-27    Vinodhkumar.M        fetch only non deleted user condition is added                    *
 *******************************************************************************************************/

BEGIN
	SELECT
		  [ClientLoginId]							AS	 [ClientLoginId],
		  [Email]									AS	 [Email],
		  [PhoneNumber]								AS	 [PhoneNumber],
		  [Name]									AS	 [Name],
		  [ClientDefaulTimeZone]					AS	 [ClientDefaulTimeZone],
		  [AccessCode]								AS	 [AccessCode],
		  [AccessCodeStatus]						AS	 [AccessCodeStatus],
		  [PasswordHash]							AS	 [PasswordHash],
		  ISNULL([NoOfAttempt],0)					AS   [NoOfAttempt],
		  dbo.KAAS_CP_GetLastLoginDateTime(
		  ClientLoginId)							AS   [ClientLastAccessDateTime],
		  dbo.KAAS_CP_FNCheckUserIsLocked(
		  ClientLoginId)							AS   [IsLocked],
		  [LastAccessedDateTime]					AS	 [LastAccessedDateTime],
		  [LockedOutEndDate]						AS	 [LockedOutEndDate],
		  [SecurityStamp]							AS	 [SecurityStamp],
		  ISNULL([IsTwoFactorEnabled],0)			AS   [IsTwoFactorEnabled],
		  [IsActiveLogin]							AS   [IsActiveLogin],
		  [IsFirstlogin]							AS   [IsFirstlogin],
		  [IsDeleted]								AS	 [IsDeleted],
		  [IsAdmin]									AS	 [IsAdmin],
		  [IsEmailConfirmed]						AS	 [IsEmailConfirmed],
		  [IsPhoneNumberConfirmed]					AS	 [IsPhoneNumberConfirmed],
		  [EmailActivationToken]					AS	 [EmailActivationToken],
		  [ConcurrencyStamp]						AS   [ConcurrencyStamp],
		  [PasswordResetOTP]						AS   [PasswordResetOTP],
		  [PasswordResetOTPCreationTime]			AS   [PasswordResetOTPCreationTime],  
		  [PasswordResetOTPExpirationTime]			AS   [PasswordResetOTPExpirationTime],
		  [OTPAccessToken]							AS	 [OTPAccessToken],
		  [OTPAccessTokenCreationTime]				AS	 [OTPAccessTokenCreationTime],
		  [OTPAccessTokenExpirationTime]			AS   [OTPAccessTokenExpirationTime],
		  [PasswordResetOTPAttemptCount]			AS	 [PasswordResetOTPAttemptCount],
		  [PasswordResetLockOutEndDate]				AS	 [PasswordResetLockOutEndDate],
		  [IsPasswordResetOTPVerified]				AS	 [IsPasswordResetOTPVerified],
		  [IsUserVerifiedEmail]						AS	 [IsUserVerifiedEmail],
		  [VerifiedByAdminUserId]					AS	 [VerifiedByAdminUserId],
		  [EmailActivationTokenCreatedTime]			AS   [EmailActivationTokenCreatedTime],
		  [EmailActivationTokenExpirationTime]		AS   [EmailActivationTokenExpirationTime],
		  [IsAdminVerifiedUserLogin]				AS   [IsAdminVerifiedUserLogin],
		  [SecretQuestion]							AS   [SecretQuestion],
		  [Answer]									AS	 [Answer]
	FROM
		  [dbo].[ClientLogin]
	WHERE
		  [IsDeleted] = 0

END

GO

IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_GetCaseFoldersAttachment'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetCaseFoldersAttachment]
  END
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_GetCaseFoldersAttachment]
      (@matter                   VARCHAR(20),
       @documentnamingmethod     VARCHAR(1))
AS
BEGIN

/*******************************************************************************************************
* Returns the default location for any documents stored against a case/matter						   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_GetCaseFoldersAttachment]								       *
* Copied from			: [dbo].[ky_NETGetCaseFolders]												   *
* Copied from			: [dbo].[KAAS_GetCaseFolders]										           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
* 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                          *
 *******************************************************************************************************/

DECLARE @continue                 INT
DECLARE @strDefaultFolder         VARCHAR(255)
DECLARE @error                    VARCHAR(1000)
DECLARE @strFileName              VARCHAR(255)
DECLARE @strClientCode            VARCHAR(20)
DECLARE @strMatterNumber          VARCHAR(20)
DECLARE @storagemethod            VARCHAR(1)
DECLARE @docFolder                VARCHAR(255)

SET @continue = 0

SELECT @storagemethod = SCF.[StorageMethod]
  FROM [dbo].[SystemConfig] SCF

SET @storagemethod = ISNULL(@storagemethod, 'C')

SELECT @strClientCode = MAT.[ClientCode],
       @strMatterNumber = MAT.[Matter]
  FROM [dbo].[matters] MAT
 WHERE MAT.[Code] = @matter

    IF (@continue = 0)
      BEGIN
        BEGIN TRY
          SELECT @strDefaultFolder = (SELECT RTRIM(ISNULL(SC.[SCWPFOLDER], ''))
                                        FROM [dbo].[SystemConfig] SC)
          SET @strDefaultFolder = ISNULL(@strDefaultFolder, '')

          IF (@strDefaultFolder = '')
            BEGIN
              SET @continue = 4
              SET @error = 'SCWPFOLDER not SET in System Config'
            END
        END TRY
        BEGIN CATCH
          SET @continue = 5
          SET @error = 'Error retrieving SCWPFOLDER: ' + Error_Message()
        END CATCH
      END

    IF (@continue = 0)
      BEGIN
        BEGIN TRY
          SELECT @strFileName = RTRIM(ISNULL(CLT.[DCOUMENTFOLDER], ''))
            FROM [dbo].[client] CLT
           WHERE CLT.[CLCODE] = @strClientCode

          SET @strFileName = RTRIM(ISNULL(@strFileName, ''))

          IF (@strFileName = '')
            BEGIN
              SET @strFileName = @strDefaultFolder + '\' + @strClientCode

              UPDATE CLT
                 SET CLT.[DCOUMENTFOLDER] = @strFileName
                FROM [dbo].[client] CLT
               WHERE CLT.[CLCODE] = @strClientCode
            END
        END TRY
        BEGIN CATCH
          SET @continue = 1
          SET @error = 'Failed to establish Client Document Folder'
        END CATCH
    END

IF (@storagemethod = 'D')
BEGIN
  SET @docFolder = @strDefaultFolder + '\' +
                   SUBSTRING(CONVERT(VARCHAR(5), 10000 + YEAR(GETDATE())), 2, 4) +
                   SUBSTRING(CONVERT(VARCHAR(3), 100 + MONTH(GETDATE())), 2, 4)
END
IF (@storagemethod = 'C')
BEGIN
  SET @docFolder = @strFileName + '\' + @strMatterNumber
END

SET @docFolder = ISNULL(@docFolder, '')

SELECT RSL.[Continue],
       RSL.[Error],
       @strDefaultFolder AS [SCWPFolder],
       CASE WHEN UNCS.[Drive] IS NULL
                 THEN @strDefaultFolder
            ELSE UNCS.[UNC] + SUBSTRING(@strDefaultFolder, 3, LEN(@strDefaultFolder) - 2) END AS [UNCSCWPFolder],
       RSL.[ClientFolder],
       CASE WHEN UNC.[Drive] IS NULL
                 THEN RSL.[ClientFolder]
            ELSE UNC.[UNC] + SUBSTRING(RSL.[ClientFolder], 3, LEN(RSL.[ClientFolder]) - 2) END AS [UNCClientFolder],
       @docFolder As [DocumentFolder],
       CASE WHEN UNCD.[Drive] IS NULL
                 THEN @docFolder
            ELSE UNCD.[UNC] + SUBSTRING(@docFolder, 3, LEN(@docFolder) - 2) END AS [UNCDocumentFolder],
       @storagemethod AS [StorageMethod],
       @documentnamingmethod AS [DocumentNamingMethod]
  FROM (SELECT @continue AS [Continue],
               RTRIM(ISNULL(@strFileName, '')) AS [ClientFolder],
               RTRIM(ISNULL(@error, '')) AS [Error]) RSL
       LEFT OUTER JOIN [dbo].[UNCAlias] UNC
                    ON UNC.[Drive] = CASE WHEN SUBSTRING(RSL.[ClientFolder], 2, 1) = ':'
                                               THEN LEFT(RSL.[ClientFolder], 1)
                                          ELSE '' END
       LEFT OUTER JOIN [dbo].[UNCAlias] UNCS
                    ON UNCS.[Drive] = CASE WHEN SUBSTRING(@strDefaultFolder, 2, 1) = ':'
                                                THEN LEFT(@strDefaultFolder, 1)
                                           ELSE '' END
       LEFT OUTER JOIN [dbo].[UNCAlias] UNCD
                    ON UNCD.[Drive] = CASE WHEN SUBSTRING(@docFolder, 2, 1) = ':'
                                                THEN LEFT(@docFolder, 1)
                                           ELSE '' END
END

GO
IF OBJECT_ID(N'KAAS_CP_GetCurrentTenantFirmName',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetCurrentTenantFirmName]
GO
CREATE PROCEDURE [dbo].[KAAS_CP_GetCurrentTenantFirmName]
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetCurrentTenantFirmName]	      							   *
* Description: To get tenant firm name for client portal											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-04    Aakif        Created																   *
 *******************************************************************************************************/

BEGIN

	--SET DEFAULT HEADER IF FIRM NAME IS NOT AVAILABLE
	SELECT
		[NAME] AS [FirmName]
	FROM
		[dbo].[control]
END

GO






IF OBJECT_ID(N'KAAS_CP_GetDashboardWidgetDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetDashboardWidgetDetails]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_GetDashboardWidgetDetails]
    (@LoginId VARCHAR(100))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetDashboardWidgetDetails]									   *
* Description: To get widget details for Home page Dashboard									       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-06    Vinodhkumar        Created
* 2021-07-09    Vinodhkumar        Instead of using select statement,using scalar variables to store   *
								   and using the variable to dispaly the data						   *
* 2021-08-09    Aakif			   Included default value decimal precision for cost variables		   *
* 2022-06-13    Aakif			   Fixed issue to show only active cases in dashboard				   *
* 2022-06-14    Aakif			   Used join instead of subquery to improve performance				   *
 *******************************************************************************************************/

BEGIN

	DECLARE 
	@ActiveCases			INT,
	@OutstandingAction		INT,
	@RecentAction			INT,
	@OutstandingInvoice 	DECIMAL(10,2),
	@UnbilledOutlay			DECIMAL(10,2),
	@UnbilledTime			DECIMAL(10,2)


	DECLARE  @PublishedCasesList TABLE
	(
			[MatterCode]   VARCHAR(15) 
	)

	--Getting the published matter list and stored in table variable
	INSERT INTO 
		   @PublishedCasesList
    SELECT
		   [MatterCode] 
	FROM
		   [dbo].[KAAS_CP_TFGetMatterCodeForClient] (@LoginId)

	--To get active cases
	SELECT
		  @ActiveCases = COUNT(1)
	FROM
		  @PublishedCasesList PA
	JOIN 
		[dbo].[matters] MAT
	  ON PA.MatterCode = MAT.[Code]
	 AND ISNULL(MAT.Closed, '') = 'N'
	
	--To get outstanding action for all active cases			    
	SELECT
		  @OutstandingAction = COUNT(1)
	 FROM
		  [dbo].[diary] [DIA]
	 JOIN
		@PublishedCasesList [PC]
	   ON 
	     [DIA].[CaseCode] = [PC].[MatterCode]
	 WHERE
		  ISNULL([Publish], '') = 'P' AND
		  [Status] = 0	
	
	--To get the recent action for all active cases				
	SELECT
		  @RecentAction		 = COUNT(1)
	FROM
		  [dbo].[Diary] [DIA]
	 JOIN
		@PublishedCasesList [PC]
	   ON 
	     [DIA].[CaseCode] = [PC].[MatterCode]
	WHERE
		  ISNULL([Publish], '') = 'P' AND
		  [Date] >= DATEADD(DAY,-7,GETUTCDATE()) 

	--To get the Outstanding invoice for active cases
	SELECT
		  @OutstandingInvoice = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL([DebtBal], 0)), 0)) 
	FROM
		  [dbo].[Matters] [MAT]
	 JOIN
		@PublishedCasesList [PC]
	   ON 
	     [MAT].[Code] = [PC].[MatterCode]
	WHERE
		  ISNULL([Publish], '') = 'P' 

	
	--To get the Unbilled outlay amount
	SELECT
		  @UnbilledOutlay = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL([OutlayBal], 0)), 0))
	FROM
		  [dbo].[Matters] [MAT]
	 JOIN
		@PublishedCasesList [PC]
	   ON 
	     [MAT].[Code] = [PC].[MatterCode]
	WHERE
		  ISNULL([Publish], '') = 'P' 

		 	
	--To get the unbilled time for all active cases
	SELECT
		  @UnbilledTime = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL([ChargeBal], 0)), 0))
	FROM
		  [dbo].[Matters] [MAT]
	 JOIN
		@PublishedCasesList [PC]
	   ON 
	     [MAT].[Code] = [PC].[MatterCode]
	WHERE
		  ISNULL([Publish], '') = 'P' 

					 		  
	SELECT 
		@ActiveCases			AS   [ActiveCases],
		@OutstandingAction		AS	 [OutstandingAction],
		@RecentAction			AS	 [RecentAction],
		@OutstandingInvoice 	AS	 [OutstandingInvoice],
		@UnbilledOutlay			AS	 [UnbilledOutlay],
		@UnbilledTime			AS	 [UnbilledTime]

END

GO

IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_GetDiaryAttachments'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetDiaryAttachments]
  END
GO

CREATE PROCEDURE 
       [dbo].[KAAS_CP_GetDiaryAttachments]
      (@DIARYID Integer,
	  @Handler VARCHAR(10))
/*******************************************************************************************************
* This procedure is used load the data for TaskAddAction page Attachment Grid.						   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_FetchDiaryAttachments]										   *
* Copied from			: [dbo].[ky_NETCCFetchDiaryAttachments]										   *
* Copied from			: [dbo].KAAS_CP_GetDiaryAttachments]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
* 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                          *
*******************************************************************************************************/ 
AS
BEGIN
SET NOCOUNT ON


INSERT
  INTO [dbo].[DiaryAttachmentAccess]
      ([TrackReference],
       [Handler],
       [Comment])
SELECT [DAT].[TrackReference],
       @Handler,
       'Listed for Action'
  FROM [dbo].[DiaryAttachments] [DAT]
 WHERE [DAT].[DiaryID] = @DIARYID

  SELECT [DAT].[DIARYID]                                                                   AS [DIARYID],
         [DAT].[TRACKREFERENCE]                                                            AS [TRACKREFERENCE],
         RTRIM(ISNULL([DAT].[CASECODE], ''))                                               AS [CASECODE],
         RTRIM(ISNULL([DAT].[NAME], ''))                                                   AS [NAME],
         RTRIM(ISNULL([DAT].[DOCUMENT], ''))                                               AS [DOCUMENT],
         CASE WHEN [UNC].[UNC] IS NULL
                   THEN RTRIM(ISNULL([DAT].[FILEPATH], ''))
              ELSE   [UNC].[UNC]
                   + SUBSTRING(RTRIM(ISNULL([DAT].[FILEPATH],
                                            '')),
                               3,
                                 LEN(RTRIM(ISNULL([DAT].[FILEPATH],
                                                  '')))
                               - 2) END                                                    AS [FILEPATH],
         CASE WHEN [UNC].[UNC] IS NULL
                   THEN RTRIM(ISNULL([DAT].[FILEPATH], ''))
              ELSE   [UNC].[UNC]
                   + SUBSTRING(RTRIM(ISNULL([DAT].[FILEPATH],
                                            '')),
                               3,
                                 LEN(RTRIM(ISNULL([DAT].[FILEPATH],
                                                  '')))
                               - 2) END                                                    AS [LFILEPATH],
         RTRIM(ISNULL([DAT].[TYPE], ''))                                                   AS [TYPE],
         RTRIM(ISNULL([DCL].[CLASSCODE], ''))                                              AS [DOCCLASS],
         RTRIM(ISNULL([DCL].[CLASSDESCRIPTION], ''))                                       AS [DOCCLASSDESC],
         CONVERT(VARCHAR, [DAT].[DATEENTERED], 20)                                         AS [DATEENTERED],
         RTRIM(ISNULL([DAT].[SYSTEM], 'N'))                                                AS [SYSTEM],
         RTRIM(ISNULL([DAT].[DOCCLASS], ''))                                               AS [DOCCLASS],
         RTRIM(ISNULL([DAT].[ENTEREDBY], ''))                                              AS [ENTEREDBY],
         CONVERT(VARCHAR, [DAT].[LASTACCESSDATE], 20)                                      AS [LASTACCESSDATE],
         RTRIM(ISNULL([DAT].[LASTACCESSBY], ''))                                           AS [LASTACCESSBY],
         RTRIM(ISNULL([DAT].[DICTATIONFILE], ''))                                          AS [DICTATIONFILE],
         RTRIM(ISNULL([DAT].[SOURCE], ''))                                                 AS [Source],
         RTRIM(ISNULL([DAT].[Fees], ''))                                                   AS [Fees],
         RTRIM(ISNULL([DAT].[Outlay], ''))                                                 AS [Outlay],
         [DV].[CurrentVersion]                                                             AS [CurrentVersion],
         RTRIM(ISNULL([DX].[IMDocID], ''))                                                 AS [IMDocID],
         [MAT].[uniqueid]                                                                  AS [UniqueId]
    FROM [dbo].[DiaryAttachments] [DAT]
         INNER JOIN [dbo].[diary] [DIA]
                    INNER JOIN [dbo].[matters] [MAT]
                            ON [MAT].[Code] = [DIA].[CASECODE]
                 ON [DIA].[ActionID] = [DAT].[DiaryID]
         CROSS APPLY (SELECT ISNULL(MAX([DAV].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV]
                       WHERE [DAV].[TrackReference] = [DAT].[TRACKREFERENCE]) DV
         LEFT OUTER JOIN [dbo].[DocumentClasses] [DCL]
                      ON [DCL].[CLASSCODE] = [DAT].[DOCCLASS]
         LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                      ON SUBSTRING([DAT].[FilePath], 2, 1) = ':'
                     AND [UNC].[Drive] = SUBSTRING([DAT].[FilePath], 1, 1)
         LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                      ON [DX].[TrackReference] = [DAT].[TRACKREFERENCE]
   WHERE [DAT].[DIARYID] = @DIARYID
ORDER BY [DAT].[TRACKREFERENCE] DESC

SET NOCOUNT OFF
END

GO
IF OBJECT_ID(N'KAAS_CP_GetDocumentsIM',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetDocumentsIM]
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_GetDocumentsIM]
      (@matter              VARCHAR(20),
       @ActionID            INT,
       @DocFolderID         INT,
       @IMDocs              VARCHAR(MAX),
	   @PageNo              INT             = NULL,
       @PageSize            INT             = NULL,
	   @SearchText          VARCHAR(4000)   = '',
       @FileType            VARCHAR(4000)   = '',
       @SortColumn          VARCHAR(50)     = '',
       @SortDirection       VARCHAR(10)     = '',
	   @LoginId				BIGINT			= 0,
	   @ColumnNames         VARCHAR(50)		= '',
	   @FilterValues        VARCHAR(4000)	= '',
	   @DocumentIsNear		BIT				= 0,
	   @DocumentStartDate	DATE			='',
	   @DocumentEndDate		DATE			=''
	   )
AS
/************************************************************************************************************************
 *                                                                                                                      *
 * Copied From: [dbo].[KAAS_GetDocumentsIM]                                                                             *
 *                                                                                                                      *
 * Get list of Documents for the Document Manager                                                                       *
 *                                                                                                                      *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software              *
 *                                    remains fully functional                                                          *
 *   *****************************************************************************************************              *
 *   *                                                                                                   *              *
 *   * Supersedes:                              -                                                        *              *
 *   * Original:                                [ky_NETSPGetDocumentsIM]                                 *              *
 *   * First compatible version:                5.7.2.1                                                  *              *
 *   * Last compatible software version:        -                                                        *              *
 *   * Superseded by:                           -                                                        *              *
 *   *                                                                                                   *              *
 *   *****************************************************************************************************              *
 *                                                                                                                      *
 * Modification History                                                                                                 *
 * 2019-04-23   Vinodhan K        Created                                                                               *
 * 2019-05-24   Pino Carafa       Performance improvements                                                              *
 * 2019-05-24   Vinodhan		  Search field have changed as document instead of filepath                             *
 * 2019-05-24   Arun			  Performance improvements,									                            *
 * 2019-09-09   Vinodhan K		  Search now can be done on Document class description field				            *
 * 2019-09-18   Vinodhan K		  Total no. of records now will be displayed based on searched text (KEYSAAS - 1035)    *
 * 2020-02-13   Prabhu.V      	  Modified the SP to Implement filter works with dynamic values                         *
 * 2020-04-23   Prabhu.V          Performance Improved                           										*
 * 2020-04-29   Prabhu.V          Fixed FileType Filter Not working after Improved the SP                				*
 * 2020-05-04   Arun V            Document classes datatype size incresed.   KEYHM-582                                  *
 * 2020-05-04   Prabhu V          Document total reocrd issue fixed                                                     *
 * 2020-05-20   Prabhu V          Custom Filter Condition missed on performance improvement and added it now            *
 * 2021-06-02   Sadiq			  Handled seaching for Document near this Funcionlaity in Document manager(11989)		*
 * 2021-06-07   Sadiq             Filter option need to be added when "DOcument Near this" is selected(11988)			*
 * 2021-06-11   Sadiq             Added document name search  also now . (12398)
 * 2021-06-16   Aakf              Created																				*
 * 2021-07-29	Aakif			  Replaced table function to get document counts for published items					*
 ************************************************************************************************************************/
BEGIN
DECLARE @res TABLE
       ([id]                       INT identity(1, 1),
        [ActionId]                 INT,
        [TrackReference]           INT,
        [IMDocID]                  VARCHAR(500),
        [IMClass]                  VARCHAR(20),
        [DocClass]                 VARCHAR(10),
        [Document]                 VARCHAR(2000),
        [DiaryDate]                DATETIME,
        [DocumentDate]             DATETIME,
        [TYPE]                     VARCHAR(20),
        [Attachments]              CHAR(1),
        [EMAIL]                    VARCHAR(1),
        [EMAILFROM]                VARCHAR(200),
        [EMAILSENT]                DATETIME,
        [EMAILTO]                  VARCHAR(1000),
        [CurrentVersion]           INT,
        [IsInDocFolder]            BIT,
        [IsShared]                 BIT,
		[DocumentClassDescription] VARCHAR(40),
        [UniqueId]					INT,
		[FilePath]					VARCHAR(500),
		[Subject]					VARCHAR(2000),
		[ShortText]					VARCHAR(120),
		[NAME]						VARCHAR(500),
		[ProcessType]               VARCHAR(50),
		[ACTIONTYPE]				VARCHAR(50),
		[ActionTypeDescription]		VARCHAR(500),
		[DOCUMENTSOURCE]			VARCHAR(500)
		,[TotalRecord] INT
		)
DECLARE @TOTALRECORDS INT =0;
DECLARE @classes TABLE
       ([KeyhouseClass]     INT,
        [IMClass]           INT,
        [ClassCode]         VARCHAR(20),
        [ClassDescription]  VARCHAR(100))

DECLARE @IMDocTable TABLE
       ([IMDocID]           VARCHAR(500)        PRIMARY KEY,
        [Description]       VARCHAR(2000),
        [IMClass]           VARCHAR(20),
        [IMType]            VARCHAR(20),
        [EmailFrom]         VARCHAR(200),
        [EmailTo]           VARCHAR(1000),
        [EmailSent]         DATETIME,
        [DocumentDate]      DATETIME)

DECLARE @IMDocExpanded TABLE
       ([id]                INT              IDENTITY(1, 1)  PRIMARY KEY,
        [ActionID]          INT,
        [TrackReference]    INT,
        [IMDocID]           VARCHAR(500),
        [IMClass]           VARCHAR(20),
        [DocClass]          VARCHAR(10),
        [Document]          VARCHAR(2000),
        [DiaryDate]         DATETIME,
        [DocumentDate]      DATETIME,
        [EmailSent]         DATETIME,
        [TYPE]              VARCHAR(20),
        [Attachments]       CHAR(1),
        [EMAIL]             CHAR(1),
        [EmailFrom]         VARCHAR(200),
        [EmailTo]           VARCHAR(1000),
        [CurrentVersion]    INT)

		DECLARE @FileTypeList TABLE
		([FileType]			VARCHAR(20)						PRIMARY KEY)

		INSERT INTO @FileTypeList
		SELECT 
			RTRIM(LTRIM([Item])) 
		FROM 
			KAAS_FN_SplitString(@FileType, ',')

DECLARE @idoc INT
/*
DECLARE @StartRow INT = NULL;
DECLARE @EndRow   INT = NULL;
IF(((ISNULL(@PageNo, 0)) != 0 AND (ISNULL(@PageSize, 0)) != 0) AND (@PageNo > -1))
BEGIN
    SET @PageNo = ISNULL(@PageNo, 0) - 1; -- 0 BASED INDEX

	SET @StartRow = ((@PageNo) * @PageSize) + 1;
	SET @EndRow = (@StartRow + @PageSize) - 1;
END
*/
IF(@SortColumn = '' OR @SortColumn = NULL)
BEGIN
	SET @SortColumn = 'RowNumber'
END

IF(@SortDirection = '' OR @SortDirection = NULL)
BEGIN
	SET @SortDirection = 'ASC'
END

DECLARE @uniqueid AS INT=0;
SELECT @uniqueid = [uniqueid] 
FROM dbo.[matters] 
WHERE [Code] = @matter


DECLARE @CustomFilter TABLE
       ([DOCCLASS]     VARCHAR(2000),
        [TYPE]           VARCHAR(2000))

DECLARE @DOCCLASSFilterCount INT = 0;
DECLARE @TypeFilterCount INT = 0;
IF @ColumnNames <> ''
BEGIN
	-- Dynamic Filter By Custome Filter Settings Start

	SELECT columnName,rownumber INTO #columntbl FROM 
		(SELECT 
	LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS columnName, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
	FROM
	(
	SELECT CAST('<XMLRoot><RowData>' + REPLACE(@ColumnNames,',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
	)t
	CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) ColumnTbl  -- count(*) over(),

	SELECT FilterValue,rownumber INTO #FILTERVALUETBL FROM 
		(SELECT 
	LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue, ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
	FROM
	(
	SELECT CAST('<XMLRoot><RowData>' + REPLACE(@FilterValues,'|','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
	)t
	CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBL 

	DECLARE @count int
	DECLARE @lptcnt int=1
	
	DECLARE @ColumnName varchar(50)
	DECLARE @FilterValue varchar(2000)

	SELECT @count = count(1)  FROM #columntbl;

	WHILE @lptcnt <= @count
	BEGIN

	   SET @FilterValue =''
	   SELECT @ColumnName = columnName FROM #columntbl WHERE rownumber = @lptcnt
	   SELECT @FilterValue = FilterValue FROM #FILTERVALUETBL WHERE rownumber = @lptcnt
	   IF(@ColumnName = 'DOCCLASS')
		insert into @CustomFilter (DOCCLASS,TYPE) values (@FilterValue,null)
	   ELSE
	    insert into @CustomFilter (DOCCLASS,TYPE) values (null,@FilterValue)
	   
	   SET @lptcnt = @lptcnt + 1;   

	END
	
	SET @DOCCLASSFilterCount = (SELECT COUNT(1) FROM @CustomFilter WHERE DOCCLASS IS NOT NULL AND DOCCLASS <>'')
	SET @TypeFilterCount = (SELECT  COUNT(1) FROM @CustomFilter WHERE TYPE IS NOT NULL AND TYPE <>'')
	
END

IF (ISNULL(@DocFolderID, 0) = 0) AND (ISNULL(@ActionID, 0) = 0)
BEGIN
SET @IMDocs = ISNULL(@IMDocs, '<?xml version="1.0" encoding="windows-1252" ?>' + CHAR(13) + CHAR(10) + '<IMDocs/>')

IF (ISNULL(PATINDEX('%<?xml %', @IMDocs), 0) < 1)
  BEGIN
    SET @IMDocs = '<?xml version="1.0" encoding="windows-1252" ?>' + CHAR(13) + CHAR(10) + @IMDocs
  END

BEGIN TRY
EXEC sp_xml_preparedocument @idoc OUTPUT, @IMDocs
END TRY
BEGIN CATCH
EXEC sp_xml_preparedocument @idoc OUTPUT, '<IMDocs/>'
END CATCH

  INSERT
    INTO @IMDocTable
        ([IMDocID],
         [Description],
         [IMClass],
         [IMType],
         [EmailFrom],
         [EmailTo],
         [EmailSent],
         [DocumentDate])
  SELECT [DAL].[IMDocID],
         [DAL].[Description],
         [DAL].[IMClass],
         [DAL].[IMType],
         [DAL].[EmailFrom],
         [DAL].[EmailTo],
         [DAL].[EmailSent],
         [DAL].[DocumentDate]
    FROM OPENXML(@idoc, 'IMDocs/Doc', 2)
            WITH([IMDocID]        VARCHAR(500)    '@DocId',
                 [Description]    VARCHAR(2000)   '@Description',
                 [IMClass]        VARCHAR(20)     '@ClassId',
                 [IMType]         VARCHAR(20)     '@TypeId',
                 [EmailFrom]      VARCHAR(200)    '@EmailFrom',
                 [EmailTo]        VARCHAR(1000)   '@EmailTo',
                 [EmailSent]      DATETIME        '@EmailSent',
                 [DocumentDate]   DATETIME        '@DocumentDate') [DAL]

EXEC sp_xml_removedocument @idoc

INSERT
  INTO @res
      ([ActionId],
       [TrackReference],
       [IMDocID],
       [IMClass],
       [DocClass],
       [Document],
       [DiaryDate],
       [DocumentDate],
       [EmailSent],
       [TYPE],
       [Attachments],
       [EMAIL],
       [EmailFrom],
       [EmailTo],
       [CurrentVersion],
       [IsInDocFolder],
       [IsShared])
SELECT convert(INT, NULL)                                                     AS [ActionID],
       convert(INT, NULL)                                                     AS [TrackReference],
       [DAL].[IMDocID]                                                        AS [IMDocID],
       [DAL].[IMClass]                                                        AS [IMClass],
       convert(VARCHAR(10), NULL)                                             AS [DocClass],
       [DAL].[Description]                                                    AS [Document],
       convert(DATETIME,
               ISNULL([DAL].[DocumentDate],
                      [DAL].[EmailSent]))                                     AS [DiaryDate],
       convert(DATETIME,
               ISNULL([DAL].[DocumentDate],
                      [DAL].[EmailSent]))                                     AS [DocumentDate],
       convert(DATETIME,
               [DAL].[EmailSent])                                             AS [EMAILSENT],
       CASE convert(VARCHAR(20),
                    [DAL].[IMTYPE])
            WHEN 'WORD'      THEN 'DOC'
            WHEN 'WORDX'     THEN 'DOC'
            WHEN 'WPF'       THEN 'DOC'
            WHEN 'ANSI'      THEN 'DOC'
            WHEN 'ACROBAT'   THEN 'PDF'
            WHEN 'EXCEL'     THEN 'XLS'
            WHEN 'EXCELX'    THEN 'XLS'
            WHEN 'MIME'      THEN CASE WHEN [DAL].[IMClass] = 'E-Mail'
                                            THEN 'MSG'
                                       ELSE 'MIME' END
            ELSE [DAL].[IMTYPE] END                                           AS [TYPE],
       CONVERT(CHAR(1),
               'N')                                                           AS [Attachments],
       CONVERT(CHAR(1), CASE WHEN ISNULL([DAL].[IMClass], '') = 'E-Mail'
                                  THEN 'Y'
                             ELSE 'N' END)                                    As [EMAIL],
       CASE WHEN ISNULL([DAL].[IMClass], '') = 'E-Mail'
                 THEN [DAL].[EMAILFROM]
            ELSE CONVERT(VARCHAR(200), NULL) END                              AS [EmailFrom],
       CASE WHEN ISNULL([DAL].[IMClass], '') = 'E-Mail'
                 THEN [DAL].[EMAILTO]
            ELSE CONVERT(VARCHAR(1000), NULL) END                             AS [EmailTo],
       CONVERT(INT, 1)                                                        AS [CurrentVersion],
       0                                                                      AS [IsInDocFolder],
       0                                                                      AS [IsShared]
  FROM @IMDocTable [DAL]
       LEFT OUTER JOIN [dbo].[DAIMXref] [DX]
                    ON [DX].[IMDocID] = [DAL].[IMDocID]
 WHERE [DX].[TrackReference] IS NULL
 AND (
			@SearchText = ''
			OR
			([DAL].[Description] LIKE '%' + @SearchText + '%')
			OR
			(CONVERT(DATETIME, ISNULL([DAL].[DocumentDate], [DAL].[EmailSent])) LIKE '%' + @SearchText + '%')
		)
		AND
		(
			ISNULL(@FileType, '') = ''
			OR (CASE CONVERT(VARCHAR(20),[DAL].[IMTYPE])
				WHEN 'WORD'      THEN 'DOC'
				WHEN 'WORDX'     THEN 'DOC'
				WHEN 'WPF'       THEN 'DOC'
				WHEN 'ANSI'      THEN 'DOC'
				WHEN 'ACROBAT'   THEN 'PDF'
				WHEN 'EXCEL'     THEN 'XLS'
				WHEN 'EXCELX'    THEN 'XLS'
				WHEN 'MIME'      THEN CASE WHEN [DAL].[IMClass] = 'E-Mail'
												THEN 'MSG'
											ELSE 'MIME' END
				ELSE [DAL].[IMTYPE] END IN (select FileType from @FileTypeList ))
		)


--Filterig the value using search
IF @DocumentIsNear=1
BEGIN
SELECT @TOTALRECORDS = Count(1)  FROM  dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID]
 AND [DA].[CASECODE] = [DIA].[CASECODE]
WHERE [DIA].[CaseCode] = @matter
		AND
		[DA].DATEENTERED>=@DocumentStartDate
		AND
		[DA].DATEENTERED<=@DocumentEndDate
		AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)

		

SELECT @TOTALRECORDS = Count(1)+ @TOTALRECORDS FROM @res
	SELECT  
[DIA].[CASECODE],[DIA].[ACTIONID],[DIA].[DATE],[DIA].[TxmDate], [DIA].[EMAIL],[DIA].[ATTACHMENTS],[DIA].[EMAILADDRESS],[DIA].[ADDRESSTO],[DIA].[SUBJECT],[DIA].[DisplayText],
		[DIA].[PROCESSTYPE],[DIA].[ACTIONTYPE],
		[DA].[DIARYID],[DA].[TrackReference],[DA].[DocClass],[DA].[DATEENTERED],[DA].[TYPE],
		[DA].[FILEPATH],[DA].[NAME],[DA].[SOURCE],
		convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
		convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) AS [IMClass],
		RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], '')))) AS [Document],
		CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],

			CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription]
					  --,Count(1) Over() as TotalRowsCount
		INTO #DiaryTablesDoc
 FROM  dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID] and [DIA].CASECODE = [DA].CASECODE
   LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DA].[TrackReference]
 LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DA].[DocClass], ''))
													 END
 WHERE [DIA].[CaseCode] = @matter
		AND
		[DA].DATEENTERED>=@DocumentStartDate
		AND
		[DA].DATEENTERED<=@DocumentEndDate
		AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)
		order by [DA].DATEENTERED
 OFFSET @PageSize * (@PageNo - 1) ROWS
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);
	INSERT
    INTO @res
        ([ActionId],
         [TrackReference],
         [IMDocID],
         [IMClass],
         [DocClass],
         [Document],
         [DiaryDate],
         [DocumentDate],
         [EmailSent],
         [TYPE],
         [Attachments],
         [EMAIL],
         [EmailFrom],
         [EmailTo],
         [CurrentVersion],
         [IsInDocFolder],
         [IsShared],
		 [DocumentClassDescription],
		 [UniqueId],
		 [FilePath],
		 [Subject],
		 [ShortText],
		 [NAME],
		 [ProcessType],
		 [ACTIONTYPE],
		 [ActionTypeDescription],
		 [DOCUMENTSOURCE]
		-- ,[TotalRecord]
		 )
  SELECT convert(INT, [DIA].[DIARYID]) AS [ActionID],
         convert(INT, [DIA].[TrackReference]) AS [TrackReference],
         [DIA].[IMDocID],
         [DIA].[IMClass],
         convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) AS [DocClass],
         [DIA].[Document],
         convert(DATETIME, [DIA].[DATE]) As [DiaryDate],
         convert(DATETIME, [DIA].[DATEENTERED]) AS [DocumentDate],
         convert(DATETIME, ISNULL([DIA].[TxmDate], [DIA].[Date])) As [EMAILSENT],
         convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))) AS [TYPE],
     --    CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END AS [Attachments],
		 (CASE WHEN     ISNULL( convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END), '') = 'Y' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END )
                                  WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END)
                                  ELSE 'N' END) AS [Attachments],
      --   convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) AS [EMAIL],
		 (CASE WHEN     convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            ELSE 'N' END) AS [EMAIL],
      
       --  convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))) AS [EMAILFROM],
		 RTRIM(ISNULL(CONVERT(VARCHAR(200), SUBSTRING(convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))), 1, 200)), '')) AS [EMAILFROM],
         --RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')) AS [EMAILTO],
		 RTRIM(ISNULL(CONVERT(VARCHAR(1000), SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')), 1, 1000)), '')) AS [EMAILTO],
         [DV].[CurrentVersion],
         [IND].[InDocFolder],
         [SHD].[IsShared],
		
		  [DIA].[DocumentClassDescription],
					@uniqueid AS  uniqueid,
					  CASE WHEN [UNC].[UNC] IS NULL THEN RTRIM(ISNULL([DIA].[FILEPATH], ''))
							ELSE [UNC].[UNC] + SUBSTRING(RTRIM(ISNULL([DIA].[FILEPATH], '')), 3, LEN(RTRIM(ISNULL([DIA].[FILEPATH], ''))) - 2) END AS [FILEPATH],
					--	[RES].[EMAILSENT],
						   RTRIM(ISNULL(CONVERT(VARCHAR(1000),
												SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(2000),
																			   [DIA].[SUBJECT]),'')),
														  1,
														  1000)),
										'')) AS [SUBJECT],
					   RTRIM(ISNULL(CONVERT(VARCHAR(120),
											SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(120),
																		   [DIA].[DisplayText]),'')),
													  1,
													  120)),
									'')) AS [ShortText],
						RTRIM(ISNULL([DIA].[NAME], '')) AS [NAME],
      
       RTRIM(ISNULL([DIA].[PROCESSTYPE], '')) AS [PROCESSTYPE],
       RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) AS [ACTIONTYPE],
       [DIA].[ActionTypeDescription],
       RTRIM(ISNULL([DIA].[SOURCE], CASE WHEN [DIA].[ACTIONID] IS NULL THEN 'IManage' ELSE '' END)) AS [DOCUMENTSOURCE]
	  --,TotalRowsCount


    FROM #DiaryTablesDoc [DIA]
		-- INNER JOIN dbo.[matters] [MAT]			ON [MAT].[CODE] = [DIA].[CASECODE]
                    CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                                  THEN CONVERT(BIT, 0)
                                             ELSE CONVERT(BIT, 1) END AS [InDocFolder]
                                   FROM [dbo].[DocFolderDocuments] [DFD]
                                  WHERE [DFD].[TrackReference] = [DIA].[TrackReference]) [IND]
                    CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                                  THEN CONVERT(BIT, 0)
                                             ELSE CONVERT(BIT, 1) END AS [IsShared]
                                   FROM [dbo].[FileSharingDocuments] [FSD]
                                        INNER JOIN [dbo].[FileSharingMapping] [FSM]
                                                   INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                                                           ON [FSDF].[DocFolderID] = [FSM].[FileSharingDocFoldersID]
                                                          AND [FSDF].[Shared] = 1
                                                ON [FSM].[id] = [FSD].[FileSharingMappingID]
                                  WHERE [FSD].[TrackReference] = [DIA].[TrackReference]) [SHD]
                 
         CROSS APPLY (SELECT ISNULL(MAX([DAV].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV]
                       WHERE TRACKREFERENCE = [DIA].[TRACKREFERENCE]) [DV]
         
		LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                                    ON SUBSTRING([DIA].[FilePath], 2, 1) = ':'
                                   AND [UNC].[Drive] = SUBSTRING([DIA].[FilePath], 1, 1)
		OUTER APPLY (  SELECT TOP 1
                             [MST].[TrackReference] AS [TrackReference],
                             [MST].[Type] AS [Type]
                        FROM #DiaryTablesDoc [MST]
                       WHERE [MST].[diaryid] = [DIA].[ActionID] 
                    ORDER BY CASE WHEN [MST].Type = 'MSG'
                                       THEN 0
                                  ELSE 1 END,
                             [MST].[TrackReference]) [OMS]
   
   
END

ELSE
BEGIN
SELECT @TOTALRECORDS = Count(1)  FROM  dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID]
 AND [DA].[CASECODE] = [DIA].[CASECODE]
WHERE [DIA].[CaseCode] = @matter
AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN 
			([DA].FILEPATH LIKE '%' + @SearchText + '%')
			OR
			(RTRIM(convert(VARCHAR(2000), ISNULL([DA].[Document], ''))) LIKE '%' + @SearchText + '%')
			OR
			([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
			OR
			([DA].[TYPE] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DocClass] LIKE '%' + @SearchText + '%')
			THEN 1
			ELSE 0
			END = 1
		)
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)

SELECT @TOTALRECORDS = Count(1)+ @TOTALRECORDS FROM @res
	SELECT  
[DIA].[CASECODE],[DIA].[ACTIONID],[DIA].[DATE],[DIA].[TxmDate], [DIA].[EMAIL],[DIA].[ATTACHMENTS],[DIA].[EMAILADDRESS],[DIA].[ADDRESSTO],[DIA].[SUBJECT],[DIA].[DisplayText],
		[DIA].[PROCESSTYPE],[DIA].[ACTIONTYPE],
		[DA].[DIARYID],[DA].[TrackReference],[DA].[DocClass],[DA].[DATEENTERED],[DA].[TYPE],
		[DA].[FILEPATH],[DA].[NAME],[DA].[SOURCE],
		convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
		convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) AS [IMClass],
		RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], '')))) AS [Document],
		CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],

			CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription]
					  --,Count(1) Over() as TotalRowsCount
		INTO #DiaryTables
 FROM  dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID] and [DIA].CASECODE = [DA].CASECODE
   LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DA].[TrackReference]
 LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DA].[DocClass], ''))
													 END
 WHERE [DIA].[CaseCode] = @matter
 AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN 
			([DA].FILEPATH LIKE '%' + @SearchText + '%')
			OR
			([Document] LIKE '%' + @SearchText + '%')
			
			OR
			([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
			OR
			([DA].[TYPE] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DocClass] LIKE '%' + @SearchText + '%')
			THEN 1
			ELSE 0
			END = 1
		)
		
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)
 ORDER BY 
 
	     CASE WHEN @SortDirection = 'ASC' AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'Type'   THEN convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DA].[TYPE], ''))))
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber'  THEN
	     		CASE @SortColumn
	     			WHEN 'Type'   THEN convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DA].[TYPE], ''))))
	     	END
	     END DESC,
	     CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber' THEN
	     	CASE @SortColumn
	     			WHEN 'Document'   THEN RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], ''))))
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber' THEN
	     		CASE @SortColumn
	     			WHEN 'Document'   THEN RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], ''))))
	     	END
	     END DESC,
	     CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'DocumentClassDescription'   THEN CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber'  THEN
	     		CASE @SortColumn
	     			WHEN 'DocumentClassDescription'   THEN CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END
	     	END
	     END DESC,
		 CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'DocumentDate'   THEN convert(DATETIME, [DA].[DATEENTERED])
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber' THEN
	     		CASE @SortColumn
	     			WHEN 'DocumentDate'   THEN convert(DATETIME, [DA].[DATEENTERED])
	     	END
	     END DESC, [DA].[TrackReference] DESC
 OFFSET @PageSize * (@PageNo - 1) ROWS
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);
	INSERT
    INTO @res
        ([ActionId],
         [TrackReference],
         [IMDocID],
         [IMClass],
         [DocClass],
         [Document],
         [DiaryDate],
         [DocumentDate],
         [EmailSent],
         [TYPE],
         [Attachments],
         [EMAIL],
         [EmailFrom],
         [EmailTo],
         [CurrentVersion],
         [IsInDocFolder],
         [IsShared],
		 [DocumentClassDescription],
		 [UniqueId],
		 [FilePath],
		 [Subject],
		 [ShortText],
		 [NAME],
		 [ProcessType],
		 [ACTIONTYPE],
		 [ActionTypeDescription],
		 [DOCUMENTSOURCE]
		-- ,[TotalRecord]
		 )
  SELECT convert(INT, [DIA].[DIARYID]) AS [ActionID],
         convert(INT, [DIA].[TrackReference]) AS [TrackReference],
         [DIA].[IMDocID],
         [DIA].[IMClass],
         convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) AS [DocClass],
         [DIA].[Document],
         convert(DATETIME, [DIA].[DATE]) As [DiaryDate],
         convert(DATETIME, [DIA].[DATEENTERED]) AS [DocumentDate],
         convert(DATETIME, ISNULL([DIA].[TxmDate], [DIA].[Date])) As [EMAILSENT],
         convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))) AS [TYPE],
     --    CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END AS [Attachments],
		 (CASE WHEN     ISNULL( convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END), '') = 'Y' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END )
                                  WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END)
                                  ELSE 'N' END) AS [Attachments],
      --   convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) AS [EMAIL],
		 (CASE WHEN     convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            ELSE 'N' END) AS [EMAIL],
      
       --  convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))) AS [EMAILFROM],
		 RTRIM(ISNULL(CONVERT(VARCHAR(200), SUBSTRING(convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))), 1, 200)), '')) AS [EMAILFROM],
         --RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')) AS [EMAILTO],
		 RTRIM(ISNULL(CONVERT(VARCHAR(1000), SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')), 1, 1000)), '')) AS [EMAILTO],
         [DV].[CurrentVersion],
         [IND].[InDocFolder],
         [SHD].[IsShared],
		
		  [DIA].[DocumentClassDescription],
					@uniqueid AS  uniqueid,
					  CASE WHEN [UNC].[UNC] IS NULL THEN RTRIM(ISNULL([DIA].[FILEPATH], ''))
							ELSE [UNC].[UNC] + SUBSTRING(RTRIM(ISNULL([DIA].[FILEPATH], '')), 3, LEN(RTRIM(ISNULL([DIA].[FILEPATH], ''))) - 2) END AS [FILEPATH],
					--	[RES].[EMAILSENT],
						   RTRIM(ISNULL(CONVERT(VARCHAR(1000),
												SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(2000),
																			   [DIA].[SUBJECT]),'')),
														  1,
														  1000)),
										'')) AS [SUBJECT],
					   RTRIM(ISNULL(CONVERT(VARCHAR(120),
											SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(120),
																		   [DIA].[DisplayText]),'')),
													  1,
													  120)),
									'')) AS [ShortText],
						RTRIM(ISNULL([DIA].[NAME], '')) AS [NAME],
      
       RTRIM(ISNULL([DIA].[PROCESSTYPE], '')) AS [PROCESSTYPE],
       RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) AS [ACTIONTYPE],
       [DIA].[ActionTypeDescription],
       RTRIM(ISNULL([DIA].[SOURCE], CASE WHEN [DIA].[ACTIONID] IS NULL THEN 'IManage' ELSE '' END)) AS [DOCUMENTSOURCE]
	  --,TotalRowsCount


    FROM #DiaryTables [DIA]
		-- INNER JOIN dbo.[matters] [MAT]			ON [MAT].[CODE] = [DIA].[CASECODE]
                    CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                                  THEN CONVERT(BIT, 0)
                                             ELSE CONVERT(BIT, 1) END AS [InDocFolder]
                                   FROM [dbo].[DocFolderDocuments] [DFD]
                                  WHERE [DFD].[TrackReference] = [DIA].[TrackReference]) [IND]
                    CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                                  THEN CONVERT(BIT, 0)
                                             ELSE CONVERT(BIT, 1) END AS [IsShared]
                                   FROM [dbo].[FileSharingDocuments] [FSD]
                                        INNER JOIN [dbo].[FileSharingMapping] [FSM]
                                                   INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                                                           ON [FSDF].[DocFolderID] = [FSM].[FileSharingDocFoldersID]
                                                          AND [FSDF].[Shared] = 1
                                                ON [FSM].[id] = [FSD].[FileSharingMappingID]
                                  WHERE [FSD].[TrackReference] = [DIA].[TrackReference]) [SHD]
                 
         CROSS APPLY (SELECT ISNULL(MAX([DAV].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV]
                       WHERE TRACKREFERENCE = [DIA].[TRACKREFERENCE]) [DV]
         
		LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                                    ON SUBSTRING([DIA].[FilePath], 2, 1) = ':'
                                   AND [UNC].[Drive] = SUBSTRING([DIA].[FilePath], 1, 1)
		OUTER APPLY (  SELECT TOP 1
                             [MST].[TrackReference] AS [TrackReference],
                             [MST].[Type] AS [Type]
                        FROM #DiaryTables [MST]
                       WHERE [MST].[diaryid] = [DIA].[ActionID] 
                    ORDER BY CASE WHEN [MST].Type = 'MSG'
                                       THEN 0
                                  ELSE 1 END,
                             [MST].[TrackReference]) [OMS]
   
   
END

--SELECT * from #DiaryTables
  

 --  OFFSET @PageSize * (@PageNo - 1) ROWS
 --  FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);
END
ELSE IF ISNULL(@DocFolderID, 0) <> 0
BEGIN

IF @DocumentIsNear=1

BEGIN
	SELECT @TOTALRECORDS = Count(1)
FROM [dbo].[DocFolderDocuments] [DDC]
 INNER JOIN dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID]
 AND [DA].[CASECODE] = [DIA].[CASECODE]
 ON [DA].[TrackReference] = [DDC].[TrackReference]
  WHERE  [DDC].[DocFolderID] = @DocFolderID 
		AND
		[DA].DATEENTERED>=@DocumentStartDate
		AND
		[DA].DATEENTERED<=@DocumentEndDate
		AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)
		
	SELECT  
[DIA].[CASECODE],[DIA].[ACTIONID],[DIA].[DATE],[DIA].[TxmDate], [DIA].[EMAIL],[DIA].[ATTACHMENTS],[DIA].[EMAILADDRESS],[DIA].[ADDRESSTO],[DIA].[SUBJECT],[DIA].[DisplayText],
		[DIA].[PROCESSTYPE],[DIA].[ACTIONTYPE],
		[DA].[DIARYID],[DA].[TrackReference],[DA].[DocClass],[DA].[DATEENTERED],[DA].[TYPE],
		[DA].[FILEPATH],[DA].[NAME],[DA].[SOURCE],
		convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
		convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) AS [IMClass],
		RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], '')))) AS [Document],
		CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],

			CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription]
					 -- , Count(1) Over() as TotalRowsCount
		INTO #DiaryTableListDOc
 FROM [dbo].[DocFolderDocuments] [DDC]
 INNER JOIN dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID] 
 AND [DIA].CASECODE = [DA].CASECODE
 ON [DA].[TrackReference] = [DDC].[TrackReference]
   LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DA].[TrackReference]
 LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DA].[DocClass], ''))
													 END
 WHERE [DDC].[DocFolderID] = @DocFolderID 
		AND
		[DA].DATEENTERED>=@DocumentStartDate
		AND
		[DA].DATEENTERED<=@DocumentEndDate
		AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)

	order by [DA].DATEENTERED
		
	OFFSET @PageSize * (@PageNo - 1) ROWS
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);

	--SELECT * from #DiaryTableList
  INSERT
    INTO @res
        ([ActionId],
         [TrackReference],
         [IMDocID],
         [IMClass],
         [DocClass],
         [Document],
         [DiaryDate],
         [DocumentDate],
         [EmailSent],
         [TYPE],
         [Attachments],
         [EMAIL],
         [EmailFrom],
         [EmailTo],
         [CurrentVersion],
         [IsInDocfolder],
         [IsShared],
		 [DocumentClassDescription],
		 [UniqueId],
		 [FilePath],
		 [Subject],
		 [ShortText],
		 [NAME],
		 [ProcessType],
		 [ACTIONTYPE],
		 [ActionTypeDescription],
		 [DOCUMENTSOURCE]
		, [TotalRecord]
		 )
  SELECT convert(INT, [DIA].[DIARYID]) AS [ActionID],
         convert(INT, [DIA].[TrackReference]) AS [TrackReference],
         convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
         convert(VARCHAR(20), ISNULL([DIA].[IMClass], '')) AS [IMClass],
         convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) AS [DocClass],
         RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DIA].[Document], '')))) AS [Document],
         convert(DATETIME, [DIA].[DATE]) As [DiaryDate],
         convert(DATETIME, [DIA].[DATEENTERED]) AS [DocumentDate],
         convert(DATETIME, ISNULL([DIA].[TxmDate], [DIA].[Date])) As [EMAILSENT],
         convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))) AS [TYPE],
         --CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END AS [Attachments],
		 (CASE WHEN     ISNULL( convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END), '') = 'Y' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END )
                                  WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END)
                                  ELSE 'N' END) AS [Attachments],
       --  convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) AS [EMAIL],
	   (CASE WHEN     convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            ELSE 'N' END) AS [EMAIL],
         --convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))) AS [EMAILFROM],
		 RTRIM(ISNULL(CONVERT(VARCHAR(200), SUBSTRING(convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))), 1, 200)), '')) AS [EMAILFROM],
         -- RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')) AS [EMAILTO],
		 RTRIM(ISNULL(CONVERT(VARCHAR(1000), SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')), 1, 1000)), '')) AS [EMAILTO],
         [DV].[CurrentVersion],
         CONVERT(BIT, 1),
         [SHD].[IsShared],
		
		  CASE WHEN convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription],
					  @uniqueid AS uniqueid,
					  CASE WHEN [UNC].[UNC] IS NULL THEN RTRIM(ISNULL([DIA].[FILEPATH], ''))
							ELSE [UNC].[UNC] + SUBSTRING(RTRIM(ISNULL([DIA].[FILEPATH], '')), 3, LEN(RTRIM(ISNULL([DIA].[FILEPATH], ''))) - 2) END AS [FILEPATH],
					--	[RES].[EMAILSENT],
						   RTRIM(ISNULL(CONVERT(VARCHAR(1000),
												SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(2000),
																			   [DIA].[SUBJECT]),'')),
														  1,
														  1000)),
										'')) AS [SUBJECT],
					   RTRIM(ISNULL(CONVERT(VARCHAR(120),
											SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(120),
																		   [DIA].[DisplayText]),'')),
													  1,
													  120)),
									'')) AS [ShortText],
						RTRIM(ISNULL([DIA].[NAME], '')) AS [NAME],
      
       RTRIM(ISNULL([DIA].[PROCESSTYPE], '')) AS [PROCESSTYPE],
       RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) AS [ACTIONTYPE],
       CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],
       RTRIM(ISNULL([DIA].[SOURCE], CASE WHEN [DIA].[ACTIONID] IS NULL THEN 'IManage' ELSE '' END)) AS [DOCUMENTSOURCE]
	   ,Count(1) over() [TotalRecord]
    FROM  #DiaryTableListDOc [DIA]
                 --ON [DIA].[TrackReference] = [DDC].[TrackReference]
         CROSS APPLY (SELECT ISNULL(MAX([DAV].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV]
                       WHERE TRACKREFERENCE = [DIA].[TRACKREFERENCE]) [DV]
         CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                       THEN CONVERT(BIT, 0)
                                  ELSE CONVERT(BIT, 1) END AS [IsShared]
                        FROM [dbo].[FileSharingDocuments] [FSD]
                             INNER JOIN [dbo].[FileSharingMapping] [FSM]
                                        INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                                                ON [FSDF].[DocFolderID] = [FSM].[FileSharingDocFoldersID]
                                               AND [FSDF].[Shared] = 1
                                     ON [FSM].[id] = [FSD].[FileSharingMappingID]
                                    AND [FSM].[FileSharingDocFoldersID] = @DocFolderID
                       WHERE [FSD].[TrackReference] = [DIA].[TrackReference]) [SHD]
         LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DIA].[TrackReference]
		LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DIA].[DocClass], ''))
													 END
		LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                                    ON SUBSTRING([DIA].[FilePath], 2, 1) = ':'
                                   AND [UNC].[Drive] = SUBSTRING([DIA].[FilePath], 1, 1)
		OUTER APPLY (  SELECT TOP 1
                             [MST].[TrackReference] AS [TrackReference],
                             [MST].[Type] AS [Type]
                        FROM #DiaryTableListDOc [MST]
                       WHERE [MST].[diaryid] = [DIA].[ActionID] --AND [MST].[TrackReference] =  [DA].[TrackReference]
                    ORDER BY CASE WHEN [MST].Type = 'MSG'
                                       THEN 0
                                  ELSE 1 END,
                             [MST].[TrackReference]) [OMS]
   
END

ELSE
BEGIN
	SELECT @TOTALRECORDS = Count(1)
FROM [dbo].[DocFolderDocuments] [DDC]
 INNER JOIN dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID]
 AND [DA].[CASECODE] = [DIA].[CASECODE]
 ON [DA].[TrackReference] = [DDC].[TrackReference]
  WHERE  [DDC].[DocFolderID] = @DocFolderID 
  AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN
				([DA].FILEPATH LIKE '%' + @SearchText + '%')
				OR
				(RTRIM(convert(VARCHAR(2000), ISNULL([DA].[Document], ''))) LIKE '%' + @SearchText + '%')
				OR
				([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
				OR
				([DA].[TYPE] LIKE '%' + @SearchText + '%')
				OR
				([DA].[DocClass] LIKE '%' + @SearchText + '%')
				THEN 1
				ELSE 0
				END =1
		)
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)
	SELECT  
[DIA].[CASECODE],[DIA].[ACTIONID],[DIA].[DATE],[DIA].[TxmDate], [DIA].[EMAIL],[DIA].[ATTACHMENTS],[DIA].[EMAILADDRESS],[DIA].[ADDRESSTO],[DIA].[SUBJECT],[DIA].[DisplayText],
		[DIA].[PROCESSTYPE],[DIA].[ACTIONTYPE],
		[DA].[DIARYID],[DA].[TrackReference],[DA].[DocClass],[DA].[DATEENTERED],[DA].[TYPE],
		[DA].[FILEPATH],[DA].[NAME],[DA].[SOURCE],
		convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
		convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) AS [IMClass],
		RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], '')))) AS [Document],
		CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],

			CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription]
					 -- , Count(1) Over() as TotalRowsCount
		INTO #DiaryTableList
 FROM [dbo].[DocFolderDocuments] [DDC]
 INNER JOIN dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID] 
 AND [DIA].CASECODE = [DA].CASECODE
 ON [DA].[TrackReference] = [DDC].[TrackReference]
   LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DA].[TrackReference]
 LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DA].[DocClass], ''))
													 END
 WHERE [DDC].[DocFolderID] = @DocFolderID 
 AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN
				([DA].FILEPATH LIKE '%' + @SearchText + '%')
				OR
				([Document] LIKE '%' + @SearchText + '%')
				OR
				([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
				OR
				([DA].[TYPE] LIKE '%' + @SearchText + '%')
				OR
				([DA].[DocClass] LIKE '%' + @SearchText + '%')
				THEN 1
				ELSE 0
				END =1
		)
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)
 ORDER BY 
 
	     CASE WHEN @SortDirection = 'ASC' AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'Type'   THEN convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DA].[TYPE], ''))))
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber'  THEN
	     		CASE @SortColumn
	     			WHEN 'Type'   THEN convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DA].[TYPE], ''))))
	     	END
	     END DESC,
	     CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber' THEN
	     	CASE @SortColumn
	     			WHEN 'Document'   THEN RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], ''))))
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber' THEN
	     		CASE @SortColumn
	     			WHEN 'Document'   THEN RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], ''))))
	     	END
	     END DESC,
	     CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'DocumentClassDescription'   THEN CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber'  THEN
	     		CASE @SortColumn
	     			WHEN 'DocumentClassDescription'   THEN CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END
	     	END
	     END DESC,
		 CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'DocumentDate'   THEN convert(DATETIME, [DA].[DATEENTERED])
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber' THEN
	     		CASE @SortColumn
	     			WHEN 'DocumentDate'   THEN convert(DATETIME, [DA].[DATEENTERED])
	     	END
	     END DESC, [DA].[TrackReference] DESC
	OFFSET @PageSize * (@PageNo - 1) ROWS
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);

	--SELECT * from #DiaryTableList
  INSERT
    INTO @res
        ([ActionId],
         [TrackReference],
         [IMDocID],
         [IMClass],
         [DocClass],
         [Document],
         [DiaryDate],
         [DocumentDate],
         [EmailSent],
         [TYPE],
         [Attachments],
         [EMAIL],
         [EmailFrom],
         [EmailTo],
         [CurrentVersion],
         [IsInDocfolder],
         [IsShared],
		 [DocumentClassDescription],
		 [UniqueId],
		 [FilePath],
		 [Subject],
		 [ShortText],
		 [NAME],
		 [ProcessType],
		 [ACTIONTYPE],
		 [ActionTypeDescription],
		 [DOCUMENTSOURCE]
		, [TotalRecord]
		 )
  SELECT convert(INT, [DIA].[DIARYID]) AS [ActionID],
         convert(INT, [DIA].[TrackReference]) AS [TrackReference],
         convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
         convert(VARCHAR(20), ISNULL([DIA].[IMClass], '')) AS [IMClass],
         convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) AS [DocClass],
         RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DIA].[Document], '')))) AS [Document],
         convert(DATETIME, [DIA].[DATE]) As [DiaryDate],
         convert(DATETIME, [DIA].[DATEENTERED]) AS [DocumentDate],
         convert(DATETIME, ISNULL([DIA].[TxmDate], [DIA].[Date])) As [EMAILSENT],
         convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))) AS [TYPE],
         --CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END AS [Attachments],
		 (CASE WHEN     ISNULL( convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END), '') = 'Y' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END )
                                  WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END)
                                  ELSE 'N' END) AS [Attachments],
       --  convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) AS [EMAIL],
	   (CASE WHEN     convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            ELSE 'N' END) AS [EMAIL],
         --convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))) AS [EMAILFROM],
		 RTRIM(ISNULL(CONVERT(VARCHAR(200), SUBSTRING(convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))), 1, 200)), '')) AS [EMAILFROM],
         -- RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')) AS [EMAILTO],
		 RTRIM(ISNULL(CONVERT(VARCHAR(1000), SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')), 1, 1000)), '')) AS [EMAILTO],
         [DV].[CurrentVersion],
         CONVERT(BIT, 1),
         [SHD].[IsShared],
		
		  CASE WHEN convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription],
					  @uniqueid AS uniqueid,
					  CASE WHEN [UNC].[UNC] IS NULL THEN RTRIM(ISNULL([DIA].[FILEPATH], ''))
							ELSE [UNC].[UNC] + SUBSTRING(RTRIM(ISNULL([DIA].[FILEPATH], '')), 3, LEN(RTRIM(ISNULL([DIA].[FILEPATH], ''))) - 2) END AS [FILEPATH],
					--	[RES].[EMAILSENT],
						   RTRIM(ISNULL(CONVERT(VARCHAR(1000),
												SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(2000),
																			   [DIA].[SUBJECT]),'')),
														  1,
														  1000)),
										'')) AS [SUBJECT],
					   RTRIM(ISNULL(CONVERT(VARCHAR(120),
											SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(120),
																		   [DIA].[DisplayText]),'')),
													  1,
													  120)),
									'')) AS [ShortText],
						RTRIM(ISNULL([DIA].[NAME], '')) AS [NAME],
      
       RTRIM(ISNULL([DIA].[PROCESSTYPE], '')) AS [PROCESSTYPE],
       RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) AS [ACTIONTYPE],
       CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],
       RTRIM(ISNULL([DIA].[SOURCE], CASE WHEN [DIA].[ACTIONID] IS NULL THEN 'IManage' ELSE '' END)) AS [DOCUMENTSOURCE]
	   ,Count(1) over() [TotalRecord]
    FROM  #DiaryTableList [DIA]
                 --ON [DIA].[TrackReference] = [DDC].[TrackReference]
         CROSS APPLY (SELECT ISNULL(MAX([DAV].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV]
                       WHERE TRACKREFERENCE = [DIA].[TRACKREFERENCE]) [DV]
         CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                       THEN CONVERT(BIT, 0)
                                  ELSE CONVERT(BIT, 1) END AS [IsShared]
                        FROM [dbo].[FileSharingDocuments] [FSD]
                             INNER JOIN [dbo].[FileSharingMapping] [FSM]
                                        INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                                                ON [FSDF].[DocFolderID] = [FSM].[FileSharingDocFoldersID]
                                               AND [FSDF].[Shared] = 1
                                     ON [FSM].[id] = [FSD].[FileSharingMappingID]
                                    AND [FSM].[FileSharingDocFoldersID] = @DocFolderID
                       WHERE [FSD].[TrackReference] = [DIA].[TrackReference]) [SHD]
         LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DIA].[TrackReference]
		LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DIA].[DocClass], ''))
													 END
		LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                                    ON SUBSTRING([DIA].[FilePath], 2, 1) = ':'
                                   AND [UNC].[Drive] = SUBSTRING([DIA].[FilePath], 1, 1)
		OUTER APPLY (  SELECT TOP 1
                             [MST].[TrackReference] AS [TrackReference],
                             [MST].[Type] AS [Type]
                        FROM #DiaryTableList [MST]
                       WHERE [MST].[diaryid] = [DIA].[ActionID] --AND [MST].[TrackReference] =  [DA].[TrackReference]
                    ORDER BY CASE WHEN [MST].Type = 'MSG'
                                       THEN 0
                                  ELSE 1 END,
                             [MST].[TrackReference]) [OMS]
   
END



END
ELSE
BEGIN

SELECT @TOTALRECORDS = COUNT(1)
FROM  dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID]
 AND [DA].[CASECODE] = [DIA].[CASECODE]
 WHERE [DIA].[ACTIONID] = @ActionID 
 AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
		CASE WHEN @SearchText = '' THEN 1 
			 WHEN			
			([DA].FILEPATH LIKE '%' + @SearchText + '%')
			OR
				(RTRIM(convert(VARCHAR(2000), ISNULL([DA].[Document], ''))) LIKE '%' + @SearchText + '%')
			OR
			([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
			OR
			([DA].[TYPE] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DocClass] LIKE '%' + @SearchText + '%')
			THEN 1
			ELSE 0
			END  = 1
		)
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)

  SELECT  
[DIA].[CASECODE],[DIA].[ACTIONID],[DIA].[DATE],[DIA].[TxmDate], [DIA].[EMAIL],[DIA].[ATTACHMENTS],[DIA].[EMAILADDRESS],[DIA].[ADDRESSTO],[DIA].[SUBJECT],[DIA].[DisplayText],
		[DIA].[PROCESSTYPE],[DIA].[ACTIONTYPE],
		[DA].[DIARYID],[DA].[TrackReference],[DA].[DocClass],[DA].[DATEENTERED],[DA].[TYPE],
		[DA].[FILEPATH],[DA].[NAME],[DA].[SOURCE],
		convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
		convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) AS [IMClass],
		RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], '')))) AS [Document],
		CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],

			CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription]
					  --,Count(1) Over() as TotalRowsCount
		INTO #DiaryTable
 FROM  dbo.[diary]  [DIA]
 INNER JOIN dbo.[DiaryAttachments] [DA] ON  [DA].[DiaryID] = [DIA].[ACTIONID]
 AND [DIA].CASECODE = [DA].CASECODE 
   LEFT OUTER JOIN [dbo].[DAIMXRef] [DX] ON [DX].[TrackReference] = [DA].[TrackReference]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                    ON [DL].[IMDocID] = [DX].[IMDocID]
                      
 LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DA].[DocClass], ''))
													 END
 WHERE [DIA].[ACTIONID] = @ActionID
 AND
		ISNULL([DIA].PUBLISH, '') = 'P'
		AND
		(
		CASE WHEN @SearchText = '' THEN 1 
			 WHEN			
			([DA].FILEPATH LIKE '%' + @SearchText + '%')			
			OR
			([Document] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
			OR
			([DA].[TYPE] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DocClass] LIKE '%' + @SearchText + '%')
			THEN 1
			ELSE 0
			END  = 1
		)
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
		AND
		(
	 (CASE WHEN @DOCCLASSFilterCount = 0 THEN 0
		   WHEN [DA].[DocClass] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [DOCCLASS] from @CustomFilter WHERE [DOCCLASS] IS NOT NULL and [DOCCLASS] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
		   ELSE 1 END) = 0
	 AND 
	 (CASE WHEN @TypeFilterCount = 0  THEN 0
		   WHEN  [DA].[TYPE] in (select FilterValue from 
															(SELECT LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST('<XMLRoot><RowData>' + REPLACE((SELECT DISTINCT [TYPE] from @CustomFilter WHERE [TYPE] IS NOT NULL and [TYPE] <>''),',','</RowData><RowData>') + '</RowData></XMLRoot>' AS XML) AS x
																)t
																CROSS APPLY x.nodes('/XMLRoot/RowData')m(n)) FILTERVALUETBLFnl) THEN 0
			ELSE 1 END) =0
	)
 ORDER BY 
 
	     CASE WHEN @SortDirection = 'ASC' AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'Type'   THEN convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DA].[TYPE], ''))))
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber'  THEN
	     		CASE @SortColumn
	     			WHEN 'Type'   THEN convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DA].[TYPE], ''))))
	     	END
	     END DESC,
	     CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber' THEN
	     	CASE @SortColumn
	     			WHEN 'Document'   THEN RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], ''))))
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber' THEN
	     		CASE @SortColumn
	     			WHEN 'Document'   THEN RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DA].[Document], ''))))
	     	END
	     END DESC,
	     CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'DocumentClassDescription'   THEN CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber'  THEN
	     		CASE @SortColumn
	     			WHEN 'DocumentClassDescription'   THEN CASE WHEN convert(VARCHAR(10), ISNULL([DA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END
	     	END
	     END DESC,
		 CASE WHEN @SortDirection = 'ASC'  AND @SortColumn!='RowNumber'  THEN
	     	CASE @SortColumn
	     			WHEN 'DocumentDate'   THEN convert(DATETIME, [DA].[DATEENTERED])
	     		END
	     	END,
	     	CASE WHEN @SortDirection = 'DESC'  AND @SortColumn!='RowNumber' THEN
	     		CASE @SortColumn
	     			WHEN 'DocumentDate'   THEN convert(DATETIME, [DA].[DATEENTERED])
	     	END
	     END DESC, [DA].[TrackReference] DESC
	OFFSET @PageSize * (@PageNo - 1) ROWS
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);
--SELECT * from #DiaryTable
--select * from @IMDocTable
  INSERT
    INTO @res
        ([ActionId],
         [TrackReference],
         [IMDocID],
         [IMClass],
         [DocClass],
         [Document],
         [DiaryDate],
         [DocumentDate],
         [EmailSent],
         [TYPE],
         [Attachments],
         [EMAIL],
         [EmailFrom],
         [EmailTo],
         [CurrentVersion],
         [IsInDocFolder],
         [IsShared],
		 [DocumentClassDescription],
		 [UniqueId],
		 [FilePath],
		 [Subject],
		 [ShortText],
		 [NAME],
		 [ProcessType],
		 [ACTIONTYPE],
		 [ActionTypeDescription],
		 [DOCUMENTSOURCE]
		 ,[TotalRecord]
		 )
  SELECT convert(INT, [DIA].[DIARYID]) AS [ActionID],
         convert(INT, [DIA].[TrackReference]) AS [TrackReference],
         convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) AS [IMDocID],
         convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) AS [IMClass],
         convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) AS [DocClass],
         RTRIM(convert(VARCHAR(2000), ISNULL([DL].[Description], ISNULL([DIA].[Document], '')))) AS [Document],
         convert(DATETIME, [DIA].[DATE]) As [DiaryDate],
         convert(DATETIME, [DIA].[DATEENTERED]) AS [DocumentDate],
         convert(DATETIME, ISNULL([DIA].[TxmDate], [DIA].[Date])) As [EMAILSENT],
         convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))) AS [TYPE],
        -- CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END AS [Attachments],
		  (CASE WHEN     ISNULL( convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END), '') = 'Y' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END )
                                  WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                        AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                       THEN (CASE WHEN [DIA].[ATTACHMENTS] = 'Y' THEN 'Y' ELSE 'N' END)
                                  ELSE 'N' END) AS [Attachments],
         --convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) AS [EMAIL],
		 (CASE WHEN     convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            WHEN     ISNULL(convert(VARCHAR(20), UPPER(RTRIM(ISNULL([DIA].[TYPE], '')))), '') = 'MSG' 
                                  AND convert(INT, [DIA].[TrackReference]) = [OMS].[TrackReference]
                                 THEN 'Y'
                            ELSE 'N' END) AS [EMAIL],
       --  convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))) AS [EMAILFROM],
	   RTRIM(ISNULL(CONVERT(VARCHAR(200), SUBSTRING(convert(VARCHAR(200), RTRIM(ISNULL([DIA].[EMAILADDRESS], ''))), 1, 200)), '')) AS [EMAILFROM],
         --RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')) AS [EMAILTO],
		 RTRIM(ISNULL(CONVERT(VARCHAR(1000), SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(1000), [DIA].[ADDRESSTO]), '')), 1, 1000)), '')) AS [EMAILTO],
         [DV].[CurrentVersion],
         [IND].[InDocFolder],
         [SHD].[IsShared],
		
		  CASE WHEN convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) <> ''
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [DCL].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [DCL].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [DCL].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [DCL].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [DCL].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [DCL].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [DCL].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [DCL].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [DCL].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [DCL].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [DCL].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [DCL].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [DCL].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [DCL].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [DCL].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [DCL].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([DCL].[CLASSCODE], '') END END AS [DocumentClassDescription],
					  @uniqueid As uniqueid,
					  CASE WHEN [UNC].[UNC] IS NULL THEN RTRIM(ISNULL([DIA].[FILEPATH], ''))
							ELSE [UNC].[UNC] + SUBSTRING(RTRIM(ISNULL([DIA].[FILEPATH], '')), 3, LEN(RTRIM(ISNULL([DIA].[FILEPATH], ''))) - 2) END AS [FILEPATH],
					--	[RES].[EMAILSENT],
						   RTRIM(ISNULL(CONVERT(VARCHAR(1000),
												SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(2000),
																			   [DIA].[SUBJECT]),'')),
														  1,
														  1000)),
										'')) AS [SUBJECT],
					   RTRIM(ISNULL(CONVERT(VARCHAR(120),
											SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(120),
																		   [DIA].[DisplayText]),'')),
													  1,
													  120)),
									'')) AS [ShortText],
						RTRIM(ISNULL([DIA].[NAME], '')) AS [NAME],
      
       RTRIM(ISNULL([DIA].[PROCESSTYPE], '')) AS [PROCESSTYPE],
       RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) AS [ACTIONTYPE],
       CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN convert(VARCHAR(1), CASE WHEN RTRIM(ISNULL([DIA].[EMAIL], 'N')) = 'Y' THEN 'Y' ELSE 'N' END) = 'Y'
                                THEN 'Email'
                           WHEN convert(VARCHAR(500), ISNULL([DX].[IMDocID], '')) <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],
       RTRIM(ISNULL([DIA].[SOURCE], CASE WHEN [DIA].[ACTIONID] IS NULL THEN 'IManage' ELSE '' END)) AS [DOCUMENTSOURCE]
	   ,Count(1) over() [TotalRecord]
    FROM #DiaryTable [DIA]
                    CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                                  THEN CONVERT(BIT, 0)
                                             ELSE CONVERT(BIT, 1) END AS [InDocFolder]
                                   FROM [dbo].[DocFolderDocuments] [DFD]
                                  WHERE [DFD].[TrackReference] = [DIA].[TrackReference]) [IND]
                    CROSS APPLY (SELECT CASE WHEN COUNT(1) = 0
                                                  THEN CONVERT(BIT, 0)
                                             ELSE CONVERT(BIT, 1) END AS [IsShared]
                                   FROM [dbo].[FileSharingDocuments] [FSD]
                                        INNER JOIN [dbo].[FileSharingMapping] [FSM]
                                                   INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                                                           ON [FSDF].[DocFolderID] = [FSM].[FileSharingDocFoldersID]
                                                          AND [FSDF].[Shared] = 1
                                                ON [FSM].[id] = [FSD].[FileSharingMappingID]
                                  WHERE [FSD].[TrackReference] = [DIA].[TrackReference]) [SHD]
                 
         CROSS APPLY (SELECT ISNULL(MAX([DAV].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV]
                       WHERE TRACKREFERENCE = [DIA].[TRACKREFERENCE]) [DV]
         LEFT OUTER JOIN [dbo].[DAIMXRef] [DX]
                         LEFT OUTER JOIN @IMDocTable [DL]
                                      ON [DL].[IMDocID] = [DX].[IMDocID]
                      ON [DX].[TrackReference] = [DIA].[TrackReference]
		LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
						ON convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) <> ''
						AND DCL.[CLASSCODE] = CASE WHEN convert(VARCHAR(10), ISNULL([DIA].[DocClass], '')) = '' THEN convert(VARCHAR(20), ISNULL([DL].[IMClass], '')) 
													 ELSE convert(VARCHAR(10), ISNULL([DIA].[DocClass], ''))
													 END
		LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                                    ON SUBSTRING([DIA].[FilePath], 2, 1) = ':'
                                   AND [UNC].[Drive] = SUBSTRING([DIA].[FilePath], 1, 1)
		OUTER APPLY (  SELECT TOP 1
                             [MST].[TrackReference] AS [TrackReference],
                             [MST].[Type] AS [Type]
                        FROM #DiaryTable [MST]
                       WHERE [MST].[diaryid] = [DIA].[ActionID] --AND [MST].[TrackReference] =  [DA].[TrackReference]
                    ORDER BY CASE WHEN [MST].Type = 'MSG'
                                       THEN 0
                                  ELSE 1 END,
                             [MST].[TrackReference]) [OMS]
   
END
/*
INSERT
  INTO @classes
      ([KeyhouseClass],
       [IMClass],
       [ClassCode],
       [ClassDescription])
SELECT [CLS].[KeyhouseClass],
       [CLS].[IMClass],
       [CLS].[ClassCode],
       CASE WHEN [CLS].[KeyhouseClass] = 1
                 THEN RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], ''))
            ELSE CASE WHEN [CLS].[ClassCode] = 'ATTNOTES'
                           THEN 'Attendance Notes'
                      WHEN [CLS].[ClassCode] = 'BILL'
                           THEN 'Bill'
                      WHEN [CLS].[ClassCode] = 'FAX'
                           THEN 'Fax'
                      WHEN [CLS].[ClassCode] = 'LEGAL'
                           THEN 'Legal'
                      WHEN [CLS].[ClassCode] = 'SCAN'
                           THEN 'Scan'
                      WHEN [CLS].[ClassCode] = 'COMPARE'
                           THEN 'Compare Document'
                      WHEN [CLS].[ClassCode] = 'DISCUSSION'
                           THEN 'Discussion'
                      WHEN [CLS].[ClassCode] = 'DOC'
                           THEN 'Document'
                      WHEN [CLS].[ClassCode] = 'E-MAIL'
                           THEN 'E-Mail'
                      WHEN [CLS].[ClassCode] = 'EVENT'
                           THEN 'Event'
                      WHEN [CLS].[ClassCode] = 'LETTER'
                           THEN 'Letter'
                      WHEN [CLS].[ClassCode] = 'MEMO'
                           THEN 'Memo'
                      WHEN [CLS].[ClassCode] = 'PAGE_ICON'
                           THEN 'Page Icon'
                      WHEN [CLS].[ClassCode] = 'TASK'
                           THEN 'Task'
                      WHEN [CLS].[ClassCode] = 'TEXT'
                           THEN 'Text File'
                      WHEN [CLS].[ClassCode] = 'WEBDOC'
                           THEN 'InfoLink Web Page'
                      ELSE ISNULL([CLS].[CLASSCODE], '') END END AS [ClassDescription]
  FROM (SELECT DISTINCT
               1 AS [KeyhouseClass],
               0 AS [IMClass],
               CONVERT(VARCHAR(20), [RES].[DocClass]) AS [ClassCode]
          FROM @res [RES]
         WHERE ISNULL([RES].[DocClass], '') <> ''
        UNION
        SELECT DISTINCT
               0 AS [KeyhouseClass],
               1 AS [IMClass],
               CONVERT(VARCHAR(20), [RES].[IMClass]) AS [ClassCode]
          FROM @res [RES]
         WHERE ISNULL([RES].[IMClass], '') <> '') [CLS]
       LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
                    ON [CLS].[KeyhouseClass] = 1
                   AND DCL.[CLASSCODE] = [CLS].[ClassCode]
*/
/*
UPDATE [RES]
   SET [RES].[EMAIL] = CASE WHEN (    ISNULL([RES].[EMAIL], '') = 'Y'
                                  AND [RES].[TrackReference] = [OMS].[TrackReference])
                                 THEN 'Y'
                            WHEN (    ISNULL([RES].[TYPE], '') = 'MSG'
                                  AND [RES].[TrackReference] = [OMS].[TrackReference])
                                 THEN 'Y'
                            ELSE 'N' END,
       [RES].[Attachments] = CASE WHEN (    ISNULL([RES].[EMAIL], '') = 'Y'
                                        AND [RES].[TrackReference] = [OMS].[TrackReference])
                                       THEN [RES].[Attachments]
                                  WHEN (    ISNULL([RES].[TYPE], '') = 'MSG'
                                        AND [RES].[TrackReference] = [OMS].[TrackReference])
                                       THEN [RES].[Attachments]
                                  ELSE 'N' END
  FROM @res [RES]
       OUTER APPLY (  SELECT TOP 1
                             [MST].[TrackReference] AS [TrackReference],
                             [MST].[Type] AS [Type]
                        FROM [dbo].[diaryattachments] [MST]
                       WHERE [MST].[diaryid] = [RES].[ActionID]
                    ORDER BY CASE WHEN [MST].Type = 'MSG'
                                       THEN 0
                                  ELSE 1 END,
                             [MST].[TrackReference]) [OMS]
 WHERE [RES].[ACTIONID] IS NOT NULL
 */
/*
SELECT [RES].[id],
       CONVERT(VARCHAR(15),dbo.KAAS_FNConvertUTCDateToTargetTimeZone([RES].[DiaryDate], @LoggedInHandler), 23) AS [DATE],
       ISNULL([RES].[ActionID], 0) AS [ACTIONID],
       CONVERT(VARCHAR(15), dbo.KAAS_FNConvertUTCDateToTargetTimeZone([RES].[DocumentDate], @LoggedInHandler), 23)  AS [DocumentDate],
       [RES].[IMDocID],
       [RES].[IMClass],
       [RES].[DocumentClassDescription],
       [RES].[DocClass],
       [RES].[Document],
       ISNULL([RES].[TrackReference], 0) AS [TRACKREFERENCE],
       [RES].[TYPE] AS [TYPE],
       [RES].[Attachments] AS [Attachments],
       [RES].[EMAIL],
       RTRIM(ISNULL(CONVERT(VARCHAR(200), SUBSTRING(ISNULL([DIA].[EMAILADDRESS], [RES].[EMAILFROM]), 1, 200)), '')) AS [EMAILADDRESS],
       RTRIM(ISNULL(CONVERT(VARCHAR(1000), SUBSTRING(ISNULL([DIA].[ADDRESSTO], [RES].[EMAILTO]), 1, 1000)), '')) AS [ADDRESSTO],
       [RES].[EMAILSENT],
       RTRIM(ISNULL(CONVERT(VARCHAR(1000),
                            SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(2000),
                                                           [DIA].[SUBJECT]),'')),
                                      1,
                                      1000)),
                    '')) AS [SUBJECT],
       RTRIM(ISNULL(CONVERT(VARCHAR(120),
                            SUBSTRING(RTRIM(ISNULL(CONVERT(VARCHAR(120),
                                                           [DIA].[DisplayText]),'')),
                                      1,
                                      120)),
                    '')) AS [ShortText],
       RTRIM(ISNULL([DAT].[NAME], '')) AS [NAME],
       CASE WHEN [UNC].[UNC] IS NULL THEN RTRIM(ISNULL([DAT].[FILEPATH], ''))
                 ELSE [UNC].[UNC] + SUBSTRING(RTRIM(ISNULL([DAT].[FILEPATH], '')), 3, LEN(RTRIM(ISNULL([DAT].[FILEPATH], ''))) - 2) END AS [FILEPATH],
       RTRIM(ISNULL([DIA].[PROCESSTYPE], '')) AS [PROCESSTYPE],
       RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) AS [ACTIONTYPE],
       CASE WHEN [DIA].[ACTIONTYPE] = 'A'
                 THEN 'Action'
            WHEN [DIA].[ACTIONTYPE] = 'N'
                 THEN 'Note'
            WHEN [DIA].[ACTIONTYPE] = 'P'
                 THEN 'Appointment'
            WHEN [DIA].[ACTIONTYPE] = 'R'
                 THEN 'Reminder'
            WHEN [DIA].[ACTIONTYPE] = 'E'
                 THEN 'Email'
            WHEN [DIA].[ACTIONTYPE] = 'T'
                 THEN 'Phone Message'
            WHEN [DIA].[ACTIONTYPE] = 'D'
                 THEN 'Dictation'
            WHEN [DIA].[ACTIONTYPE] = 'U'
                 THEN 'Undertaking'
            WHEN [DIA].[ACTIONTYPE] = 'S'
                 THEN 'Statute Date'
            WHEN [DIA].[ACTIONTYPE] = 'C'
                 THEN 'Critical Date'
            WHEN [DIA].[ACTIONTYPE] = 'O'
                 THEN 'Court Date'
            WHEN [DIA].[ACTIONTYPE] = 'M'
                 THEN 'Scanned Post/Mail'
            WHEN RTRIM(ISNULL([DIA].[ACTIONTYPE], '')) = ''
                 THEN CASE WHEN [RES].[EMAIL] = 'Y'
                                THEN 'Email'
                           WHEN [RES].[IMDocID] <> ''
                                THEN 'IManage document'
                           ELSE 'Unknown' END

            ELSE 'Action Type: ' + [DIA].[ACTIONTYPE] END AS [ActionTypeDescription],
       RTRIM(ISNULL([DAT].[SOURCE], CASE WHEN [DIA].[ACTIONID] IS NULL THEN 'IManage' ELSE '' END)) AS [DOCUMENTSOURCE],
       [RES].[CurrentVersion],
       [RES].[IsInDocFolder],
       [RES].[IsShared],
	   [RES].UniqueId
  FROM @res [RES]
       LEFT OUTER JOIN [dbo].[DiaryAttachments] [DAT]
                       INNER JOIN [dbo].[diary] [DIA]
                               ON [DIA].[ACTIONID] = [DAT].[DIARYID]
                       LEFT OUTER JOIN [dbo].[UNCAlias] [UNC]
                                    ON SUBSTRING([DAT].[FilePath], 2, 1) = ':'
                                   AND [UNC].[Drive] = SUBSTRING([DAT].[FilePath], 1, 1)
                    ON [DAT].[TRACKREFERENCE] = [RES].[TrackReference]
	
       --2018-02-26 START
       --LEFT OUTER JOIN @classes [CLS]
       --             ON [CLS].[KeyhouseClass] = CASE WHEN ISNULL([RES].[IMClass], '') = '' THEN 1 ELSE 0 END
       --            AND [CLS].[IMClass] = CASE WHEN ISNULL([RES].[IMClass], '') = '' THEN 0 ELSE 1 END
       --            AND [CLS].[ClassCode] = CASE WHEN ISNULL([RES].[IMClass], '') = '' THEN [RES].[DocClass] ELSE [RES].[IMClass] END
       LEFT OUTER JOIN @classes [CLS]
                    ON [CLS].[KeyhouseClass] = CASE WHEN ISNULL([RES].[DocClass], '') = '' THEN 0 ELSE 1 END
                   AND [CLS].[IMClass] = CASE WHEN ISNULL([RES].[DocClass], '') = '' THEN 1 ELSE 0 END
                   AND [CLS].[ClassCode] = CASE WHEN ISNULL([RES].[DocClass], '') = '' THEN [RES].[IMClass] ELSE [RES].[DocClass] END
       --2018-02-26 END
	--WHERE [RES].id between  (@PageNo * @PageSize) + 1 and ((@PageNo * @PageSize) + 1 + @PageSize) - 1
	ORDER BY ID
	*/
	SELECT 
		[id] AS [Id],
       CONVERT(VARCHAR(15),dbo.KAAS_CP_FNConvertUTCDateToTargetTimeZone([DiaryDate], @LoginId), 23)  AS [DATE],
       [ACTIONID],
       CONVERT(VARCHAR(15), dbo.KAAS_CP_FNConvertUTCDateToTargetTimeZone([DocumentDate], @LoginId), 23) AS [DocumentDate],
       [IMDocID],
       [IMClass],
       [DocumentClassDescription],
       [DocClass],
       [Document],
       [TRACKREFERENCE] AS [DocTrackReference],
       [TYPE] AS [DocType],
       [Attachments],
       [EMAIL],
       [EMAILFROM] AS [EMAILADDRESS],
       [EMAILTO] AS [ADDRESSTO],
       [EMAILSENT],
       [SUBJECT],
       [ShortText],
       [NAME],
       [FILEPATH] AS [FilePath],
       [PROCESSTYPE],
       [ACTIONTYPE],
       [ActionTypeDescription],
       [DOCUMENTSOURCE],
       [CurrentVersion],
       [IsInDocFolder],
       [IsShared],
	   UniqueId

	from @res
	ORDER BY TrackReference DESC
--	WHERE ID between  (@PageNo * @PageSize) + 1 and ((@PageNo * @PageSize) + 1 + @PageSize) - 1
--	ORDER BY ID
	--OFFSET @PageSize * (@PageNo - 1) ROWS
   -- FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);
--OPTION (KEEPFIXED PLAN)
/*	IF Exists(SELECT TOP 1 TotalRecord FROM @res)
		BEGIN
		SELECT TOP 1 ISNULL(TotalRecord,0) FROM @res
		END
	ELSE
		BEGIN
		SELECT 0 as TotalRecord
		END
*/
		SELECT @TOTALRECORDS AS TotalRecord
/*	
	SELECT top 1 count(1) Over()	AS [TotalRecord]
			
	FROM [dbo].[diary] [DIA]
		INNER JOIN [dbo].[DiaryAttachments] [DAT]
				ON [DAT].[DiaryID] = [DIA].[ActionID]
	WHERE [DIA].[CASECODE] = @matter
*/	
	IF ISNULL(@DocFolderID, 0) <> 0
    BEGIN
	    SELECT
			[seq]						AS [seq],
			[id]						AS [FolderId],
			[parent]					AS [parent],
			[foldername]				AS [foldername],
			[foldericon]				AS [foldericon],
			[folderimage]				AS [folderimage],
			[foldershared]				AS [foldershared],
			[folderisours]				AS [folderisours],
			[foldername]				AS [Document],
			[documentcount]				AS [DocumentCount],
			999 + TRY_CAST(seq AS INT)  AS [Id]
		FROM
			[dbo].[KAAS_CP_FNGetDocFolders](@matter, @DocFolderID, 1, 1)
		WHERE
			parent <> -1
    END
  ELSE
    BEGIN
      SELECT TOP 0
             CONVERT(INT, 0)				AS [seq],
             CONVERT(INT, 0)				AS [FolderId],
             CONVERT(INT, 0)				AS [parent],
             CONVERT(VARCHAR(500), '')		AS [foldername],
             CONVERT(INT, 0)				AS [foldericon],
             CONVERT(VARBINARY(MAX), NULL)  AS [folderimage],
             CONVERT(BIT, 0)				AS [foldershared],
             CONVERT(BIT, 0)				AS [folderisours],
             CONVERT(INT, 0)				AS [DocumentCount]
    END

END
GO

IF OBJECT_ID(N'KAAS_CP_GetFEandTeamCode',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetFEandTeamCode]
GO

CREATE PROCEDURE
	[dbo].[KAAS_CP_GetFEandTeamCode]
	 (@CASECODE    VARCHAR(15) = NULL)

AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetFEandTeamCode]									           *
* Description: To get current team code and FE code													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-02-14	Vinodhkumar.M  Ceated														           *
 *******************************************************************************************************/

BEGIN

		DECLARE @FeeEarner AS  VARCHAR(10);
		DECLARE @Partner   AS  VARCHAR(10);
		DECLARE @Secretary AS  VARCHAR(10);


		SELECT  
			  @FeeEarner = [MAT].[FECode],
			  @Partner   = [MAT].[Partner],
			  @Secretary = [MAT].[Secretary]
		 FROM
			  [matters] [MAT]
		WHERE [MAT].[Code] = @CASECODE 

		IF EXISTS (SELECT TOP 1 1 FROM [Handlers] WHERE [CODE] = @FeeEarner)
		  BEGIN
				SELECT 
					ISNULL([Code],'')						AS FECode,
					ISNULL([HAN].[TEAM],'')					AS TeamCode
				 FROM
				     [Handlers] [HAN]
				WHERE
				     [HAN].[CODE] = @FeeEarner
		  END
		 ELSE IF EXISTS (SELECT TOP 1 1  FROM [Handlers] WHERE [CODE] = @Partner)
		  BEGIN
				SELECT 
					ISNULL([Code],'')						AS FECode,
					ISNULL([HAN].[TEAM],'')					AS TeamCode
				 FROM
				     [Handlers] [HAN]
				WHERE
				     [HAN].[CODE] = @Partner
		  END
		 ELSE IF EXISTS (SELECT TOP 1 1 FROM [Handlers] WHERE [CODE] = @Secretary)
		  BEGIN
				SELECT 
					ISNULL([Code],'')						AS FECode,
					ISNULL([HAN].[TEAM],'')					AS TeamCode
				 FROM
				     [Handlers] [HAN]
				WHERE
				     [HAN].[CODE] = @Secretary
		  END

END

GO






IF OBJECT_ID(N'KAAS_CP_GetMatterDetailsForClient',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetMatterDetailsForClient]
GO

CREATE    PROCEDURE  
       [dbo].[KAAS_CP_GetMatterDetailsForClient]  
      (@LoginId             BIGINT,  
       @CaseCode            VARCHAR(20) = NULL,  
       @IsShowCloseMatter   BIT = 0)  
AS  
/*******************************************************************************************************  
*                                                                                                      *  
* Stored Procedure Name : [dbo].[KAAS_CP_GetMatterDetailsForClient]                                    *  
* Description: To get matter details for client portal                                                 *  
*                                                                                                      *  
* Modification History:                                                                                *  
* 2021-06-09    Aakif          Created                                                                 *  
* 2021-06-11    Aakif          Included option to serach with case code. User TimeZone conversion      *  
*                              and label names for User1, User2, User3 and Your Ref                    *  
* 2021-06-22    Aakif          Included column for matter comment and fixed null data issue for status *  
* 2022-02-10    vinodhkumar.M  Included -  FE code, Team code column                                   *  
* 2022-02-10    vinodhkumar.M  Removed  -  new SP created to fetch FE code, Team code column, so       *  
                                           removing columns here                                       *  
* 2022-04-20    vinodhkumar.M  Included -  client Code                                                 *  
* 2022-04-26    vinodhkumar.M  Included -  Fe Code,Telephone number,DisallowNewMatter and              *  
                               handled Inactive    condition                                           *  
* 2022-04-29    vinodhkumar.M  Updated - Replaced Contact inactive condition with Matter table         *  
                                         closed in where clause also put left join for matter table    *  
                                         with [FeeEarnerCodes] table                                   *  
* 2022-06-06    Aakif          Updated SP to include option to list closed matter as well              *  
* 2022-06-08    Aakif          Included column to show matter close status                             *  
* 2022-06-14    Aakif          Included column to show Outstanding balance                             *  
* 2022-07-07    Aakif          Included option to show recently accessed matter first                  *  
* 2022-08-11    Aakif          Performance Tuning                                                      *  
* 2023-10-12    Pino Carafa    Rewrite using [dbo].[PublishedMatters] View                             *  
*                                                                                                      *  
********************************************************************************************************/  
BEGIN  
  
SET NOCOUNT ON  
  
SET @CaseCode = RTRIM(ISNULL(@CaseCode, ''))  
  
DECLARE @MATS TABLE  
       ([Code]               VARCHAR(20)      PRIMARY KEY,  
        [LastAccess]         DATETIME,  
        UNIQUE NONCLUSTERED ([LastAccess] DESC, [Code]))  
  
DECLARE @COUNT INT  
  
IF @CaseCode <> ''  
  BEGIN  
    SELECT @COUNT = COUNT(1)  
      FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
           INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, NOLOCK)  
                   ON [MAT].[Code] = [CLA].[MatterCode]  
     WHERE [CLA].[ClientLoginId] = @LoginId  
       AND [CLA].[MatterCode] = @CaseCode  
  END  
ELSE IF @IsShowCloseMatter = 1  
  BEGIN  
    SELECT @COUNT = COUNT(1)  
      FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
           INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, NOLOCK)  
                   ON [MAT].[Code] = [CLA].[MatterCode]  
     WHERE [CLA].[ClientLoginId] = @LoginId  
     AND [CLA].[MatterCode] IS NOT NULL  
  END  
ELSE  
  BEGIN  
    SELECT @COUNT = COUNT(1)  
      FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
           INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_Closed]), NOLOCK)  
                   ON [MAT].[Closed] = 0  
                  AND [MAT].[Code] = [CLA].[MatterCode]  
     WHERE [CLA].[ClientLoginId] = @LoginId  
       AND [CLA].[MatterCode] IS NOT NULL  
  END  
  
IF @COUNT > 0  
BEGIN  
  IF @CaseCode <> ''  
    BEGIN  
      INSERT  
        INTO @MATS  
            ([Code],  
             [LastAccess])  
      SELECT TOP (@COUNT)  
             [MAT].[Code],  
             [MAT].[Started]  
        FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
             INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, NOLOCK)  
                     ON [MAT].[Code] = [CLA].[MatterCode]  
       WHERE [CLA].[ClientLoginId] = @LoginId  
         AND [CLA].[MatterCode] = @CaseCode  
    END  
  ELSE IF @IsShowCloseMatter = 1  
    BEGIN  
      INSERT  
        INTO @MATS  
            ([Code],  
             [LastAccess])  
      SELECT TOP (@COUNT)  
             [MAT].[Code],  
             [MAT].[Started]  
        FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
             INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, NOLOCK)  
                     ON [MAT].[Code] = [CLA].[MatterCode]  
       WHERE [CLA].[ClientLoginId] = @LoginId  
         AND [CLA].[MatterCode] IS NOT NULL  
    END  
  ELSE  
    BEGIN  
      INSERT  
        INTO @MATS  
            ([Code],  
             [LastAccess])  
      SELECT TOP (@COUNT)  
             [MAT].[Code],  
             [MAT].[Started]  
        FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
             INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_Closed]), NOLOCK)  
                     ON [MAT].[Closed] = 0  
                    AND [MAT].[Code] = [CLA].[MatterCode]  
       WHERE [CLA].[ClientLoginId] = @LoginId  
         AND [CLA].[MatterCode] IS NOT NULL  
    END  
END  
  
IF @CaseCode <> ''  
  BEGIN  
    SELECT @COUNT = COUNT(1)  
      FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
           INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_Client]), NOLOCK)  
                   ON [MAT].[ClientCode] = [CLA].[ContactCode]  
                  AND [MAT].[Code] = @CaseCode  
     WHERE [CLA].[ClientLoginId] = @LoginId  
       AND [CLA].[MatterCode] IS NULL  
  END  
ELSE IF @IsShowCloseMatter = 1  
  BEGIN  
    SELECT @COUNT = COUNT(1)  
      FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
           INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_Client]), NOLOCK)  
                   ON [MAT].[ClientCode] = [CLA].[ContactCode]  
     WHERE [CLA].[ClientLoginId] = @LoginId  
       AND [CLA].[MatterCode] IS NULL  
  END  
ELSE  
  BEGIN  
    SELECT @COUNT = COUNT(1)  
      FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
           INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_ClosedClient]), NOLOCK)  
                   ON [MAT].[Closed] = 0  
                  AND [MAT].[ClientCode] = [CLA].[ContactCode]  
     WHERE [CLA].[ClientLoginId] = @LoginId  
       AND [CLA].[MatterCode] IS NULL  
  END  
  
IF @COUNT > 0  
BEGIN  
  IF @CaseCode <> ''  
    BEGIN  
      INSERT  
        INTO @MATS  
            ([Code],  
             [LastAccess])  
      SELECT TOP (@COUNT)  
             [MAT].[Code],  
             [MAT].[Started]  
        FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
             INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_Client]), NOLOCK)  
                        LEFT OUTER JOIN @MATS [MTX]  
                                     ON [MTX].[Code] = [MAT].[Code]  
                     ON [MAT].[ClientCode] = [CLA].[ContactCode]  
                    AND [MAT].[Code] = @CaseCode  
       WHERE [CLA].[ClientLoginId] = @LoginId  
         AND [CLA].[MatterCode] IS NULL  
         AND [MTX].[Code] IS NULL  
   END  
  ELSE IF @IsShowCloseMatter = 1  
    BEGIN  
      INSERT  
        INTO @MATS  
            ([Code],  
             [LastAccess])  
      SELECT TOP (@COUNT)  
             [MAT].[Code],  
             [MAT].[Started]  
        FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
             INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_Client]), NOLOCK)  
                        LEFT OUTER JOIN @MATS [MTX]  
                                     ON [MTX].[Code] = [MAT].[Code]  
                     ON [MAT].[ClientCode] = [CLA].[ContactCode]  
       WHERE [CLA].[ClientLoginId] = @LoginId  
         AND [CLA].[MatterCode] IS NULL  
         AND [MTX].[Code] IS NULL  
    END  
  ELSE  
    BEGIN  
      INSERT  
        INTO @MATS  
            ([Code],  
             [LastAccess])  
      SELECT TOP (@COUNT)  
             [MAT].[Code],  
             [MAT].[Started]  
        FROM [dbo].[ClientLoginAccess] [CLA] WITH (NOLOCK)  
             INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, INDEX([IDX_ClosedClient]), NOLOCK)  
                        LEFT OUTER JOIN @MATS [MTX]  
                                     ON [MTX].[Code] = [MAT].[Code]  
                     ON [MAT].[Closed] = 0  
                    AND [MAT].[ClientCode] = [CLA].[ContactCode]  
       WHERE [CLA].[ClientLoginId] = @LoginId  
         AND [CLA].[MatterCode] IS NULL  
         AND [MTX].[Code] IS NULL  
    END  
END  
  
UPDATE [MAT]  
   SET [MAT].[LastAccess] = [CPRM].[LastAccessDate]  
  FROM [dbo].[ClientPortalRecentMatter] [CPRM] WITH (NOLOCK)  
       INNER JOIN @MATS [MAT]  
               ON [MAT].[Code] = [CPRM].[MatterCode]  
 WHERE [CPRM].[ClientLoginId] = @LoginId  
  
  SELECT [MAT].[Code]                    AS [Code],  
         [LA].[DATE]                     AS [LastActionDate],  
         [MS].[DATE]                     AS [LastMilestoneDate],  
         [NA].[DATE]                     AS [NextActionDate],  
         [LA].[DisplayText]              AS [LastActionText],  
         [MS].[DisplayText]              AS [LastMilestoneText],  
         [NA].[DisplayText]              AS [NextActionText],  
         [MAT].[Name]                    AS [ClientName],  
         [MAT].[ClientCode]              AS [ClientCode],  
         [MAT].[FECode]                  AS [FECode],  
         [MAT].[Telephone]               AS [Telephone],  
         [MAT].[ClientAddress]           AS [ClientAddress],  
         [MAT].[Code]                    AS [MatterCode],  
         [MAT].[MatterDescription]       AS [MatterDescription],  
         [MAT].[CaseHandler]             AS [CaseHandler],  
         [MAT].[User1Label]              AS [User1Label],  
         [MAT].[User1]                   AS [User1],  
         [MAT].[User2Label]              AS [User2Label],  
         [MAT].[User2]                   AS [User2],  
         [MAT].[User3Label]              AS [User3Label],  
         [MAT].[User3]                   AS [User3],  
         [MAT].[YourRefLabel]            AS [YourRefLabel],  
         [MAT].[YourRef]                 AS [YourRef],  
         [MAT].[MatterStartDate]         AS [MatterStartDate],  
         [MAT].[MatterCloseDate]         AS [MatterCloseDate],  
         [MAT].[MatterStatusCode]        AS [MatterStatusCode],  
         [MAT].[MatterStatus]            AS [MatterStatus],  
         [MAT].[MatterOriginalDebt]      AS [MatterOriginalDebt],  
         [MAT].[MatterComments]          AS [MatterComments],  
         [MAT].[DisallowNewMatter]       AS [DisallowNewMatter],  
         [MAT].[IsMatterClosed]          AS [IsMatterClosed],  
         [MAT].[OutstandingAmount]       AS [OutstandingAmount],  
         [MT1].[LastAccess]              AS [LastAccessDate]  
    FROM @MATS [MT1]  
         INNER JOIN [dbo].[PublishedMatters] [MAT] WITH (NOEXPAND, NOLOCK, INDEX([PK_PublishedMatters]))  
                 ON [MAT].[Code] = [MT1].[Code]  
         OUTER APPLY (  SELECT TOP 1  
                               [PUB].[ACTIONID],  
                               [PUB].[DATE],  
                               [PUB].[DisplayText]  
                          FROM [dbo].[PublishedActions] [PUB]  
                               WITH (NOEXPAND, INDEX ([IDX_NextActions]), NOLOCK)  
                         WHERE [PUB].[CASECODE] = [MAT].[Code]  
                           AND [PUB].[STATUS]   = 0  
                      ORDER BY [PUB].[CASECODE],  
                               [PUB].[STATUS],  
                               [PUB].[DATE]) [NA]  
         OUTER APPLY (  SELECT TOP 1  
                               [PUB].[ACTIONID],  
                               [PUB].[DATE],  
                               [PUB].[DisplayText]  
                          FROM [dbo].[PublishedActions] [PUB]  
                               WITH (NOEXPAND, INDEX ([IDX_LastActions]), NOLOCK)  
                         WHERE [PUB].[CASECODE] = [MAT].[Code]  
                           AND [PUB].[STATUS]   = 1  
                      ORDER BY [PUB].[CASECODE],  
                               [PUB].[STATUS] DESC,  
                               [PUB].[DATE]   DESC) [LA]  
         OUTER APPLY (  SELECT TOP 1  
                               [PUB].[ACTIONID],  
                               [PUB].[DATE],  
                               [PUB].[DisplayText]  
                          FROM [dbo].[PublishedActions] [PUB]  
                               WITH (NOEXPAND, INDEX ([IDX_Highlighted]), NOLOCK)  
                         WHERE [PUB].[CASECODE] = [MAT].[Code]  
                           AND [PUB].[HIGHLIGHTED] = 1  
                           AND [PUB].[STATUS]   = 1  
                      ORDER BY [PUB].[CASECODE],  
                               [PUB].[HIGHLIGHTED] DESC,  
                               [PUB].[DATE]        DESC) [MS]  
ORDER BY [MT1].[LastAccess] DESC,  
         [MAT].[Code] ASC  
  
SET NOCOUNT OFF  
  
END  
GO

IF OBJECT_ID(N'KAAS_CP_GetMatterDocFolderTree', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetMatterDocFolderTree]
END
GO

CREATE PROCEDURE [dbo].[KAAS_CP_GetMatterDocFolderTree]      
(  
 @matter      VARCHAR(20)  
)  
AS      
/********************************************************************************************************
* Gets the folder structure for a Matter. Creates it if it doesn't exist, use the CasePlan folder       * 
* structure as a template. Create it too, if it doesn't exist.		   								    *
*                                                                                                       *
* Stored Procedure Name : [dbo].[KAAS_GetMatterDocFolderTree]										    *
* Copied from			: [dbo].[ky_NETSPGetMatterDocFolderTree]									    *
*                                                                                                       *
* Modification History:                                                                                 *
* 2019-04-23    Vinodhan K        Created                                                               *
* 2019-06-19    Vinodhan K        Removed the condition to check whether UseDocFolders is set as True   *
*                                 or False. For now it wil return the data even when it is set as False *
* 2021-06-17    Aakif	          Created                                                               *
* 2021-07-29	Aakif			  Replaced table function to get document counts for published items	*
 *******************************************************************************************************/    
BEGIN    
  DECLARE @WKCODE CHAR(4)      
  DECLARE @MatterCode VARCHAR(20)      
  DECLARE @folderid INT    
      
  SELECT TOP 1      
         @MatterCode = [SM].[CODE],      
         @WKCODE = [TMP].[WKCODE]      
    FROM [dbo].[SearchMatters] SM      
         INNER JOIN [dbo].[CaseMaster] CSM      
                 ON [CSM].[CSCODE] = SM.[Code]      
         LEFT OUTER JOIN [dbo].[Templates] [TMP]      
                      ON [TMP].[WKCODE] = [CSM].[CSWKTCODE]      
   WHERE [CSM].[CSCODE] = @matter      
      
  IF @MatterCode IS NULL      
    BEGIN      
      -- Dummy statement      
      SELECT TOP 0      
             CONVERT(INT, 0) AS [id],      
             CONVERT(INT, 0) AS [parent],      
             CONVERT(VARCHAR(500), '') AS [foldername],      
             CONVERT(INT, 0) AS [foldericon]      
      
      RETURN      
    END      
      
  SELECT TOP 1      
         @folderid = MDF.[DocFolderID]      
    FROM [dbo].[MatterDocFolders] MDF      
   WHERE [MDF].[MatterCode] = @MatterCode      
      
  IF @folderid IS NULL      
    BEGIN      
      DECLARE @DefaultRootFolderName VARCHAR(500)      
      
      SELECT @DefaultRootFolderName = CONVERT(VARCHAR(500), [SET].[KeyValue])      
        FROM [dbo].[Settings] [SET]      
       WHERE [SET].[KeyName] = 'DocFolderDefaultRootName'      
      
      SET @DefaultRootFolderName = RTRIM(ISNULL(@DefaultRootFolderName, 'Documents'))      
      
      IF @WKCODE IS NULL      
        BEGIN      
          EXEC @folderid = [dbo].[KAAS_SaveDocFolderTree] '<folders><folder id="1" newfolder="True" deletefolder="False" foldername="Documents" parent="0" foldericon="1"/></folders>'      
      
          UPDATE [DF]      
             SET [DF].[foldername] = @DefaultRootFolderName      
            FROM [dbo].[DocFolders] [DF]       
           WHERE [DF].[id] = @folderid      
        END      
      ELSE      
        BEGIN      
          SELECT TOP 1      
                 @folderid = CDF.[DocFolderID]      
            FROM [dbo].[CasePlanDocFolders] CDF      
           WHERE [CDF].[WKCode] = @WKCODE      
      
          IF @folderid IS NULL      
            BEGIN      
              EXEC @folderid = [dbo].[KAAS_SaveDocFolderTree] '<folders><folder id="1" newfolder="True" deletefolder="False" foldername="Documents" parent="0" foldericon="1"/></folders>'      
      
UPDATE [DF]      
                 SET [DF].[foldername] = @DefaultRootFolderName      
                FROM [dbo].[DocFolders] [DF]       
               WHERE [DF].[id] = @folderid      
      
              INSERT      
                INTO [dbo].[CasePlanDocFolders]      
                    ([WKCode],      
                     [DocFolderID])      
              SELECT @WKCODE,      
                     @folderid      
            END      
      
          DECLARE @DUP TABLE      
                 ([id] INT)      
      
          INSERT INTO @DUP      
          EXEC @folderid = [dbo].[KAAS_DuplicateDocFolderTree] @folderid      
        END      
      
      INSERT      
        INTO [dbo].[MatterDocFolders]      
            ([MatterCode],      
             [DocFolderID])      
      SELECT @MatterCode,      
             @folderid      
    END    
      
 SELECT  
		[seq]						AS [seq],
		[id]						AS [FolderId],
		[parent]					AS [parent],
		[foldername]				AS [foldername],
		[foldericon]				AS [foldericon],
		[folderimage]				AS [folderimage],
		[foldershared]				AS [foldershared],
		[folderisours]				AS [folderisours],
		[foldername]				AS [Document],
		[documentcount]				AS [DocumentCount],
		999 + TRY_CAST(seq AS INT)  AS [Id]
 FROM
	[dbo].[KAAS_CP_FNGetDocFolders](@matter, @folderid, 1, 1)     
END
GO

IF OBJECT_ID(N'KAAS_CP_GetNewMatterCode',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_GetNewMatterCode]
GO

CREATE PROCEDURE [dbo].[KAAS_CP_GetNewMatterCode]
       (@ClientCode            VARCHAR(10),
        @MatterNumber          VARCHAR(10),
        @MatterLen             VARCHAR(10),
		@MatterCode			   VARCHAR(20) OUTPUT)
AS
/************************************************************************************************************

  Stored Procedure Name: [ky_NETCheckMatterCode]
  Description:           This procedure is used to Check new matter is already exists or not.
  Created :              03 Nov 2014

 Modification History	:                                                                              
 20 Nov 2014		Pino				Use [dbo].[Settings]                                                           
 2022-04-20			Vinodhkumar.M		Created  for client portal                                                          
************************************************************************************************************/
BEGIN

  SET NOCOUNT ON

  DECLARE @MaxLen       INT
  DECLARE @NewMatterNum VARCHAR(10)
  DECLARE @NewMatter BIGINT

  -- Get the maximum Matter Number length from the Settings table
  SELECT @MaxLen = CONVERT(INT, [SET].[KeyValue])
    FROM [dbo].[Settings] [SET]
    WHERE [SET].[KeyName] = 'MaxMatNum'

  -- Default to 4 for SAM3 and 8 for SAM4 if value isn't in the Settings Table
  IF (@MaxLen IS NULL)
    BEGIN
      IF [dbo].[ISSAM4]() = 0
        BEGIN
          SET @MaxLen = 4
        END
      ELSE
        BEGIN
          SET @MaxLen = 8
        END
    END

  -- If procedure is called to discover the maximum matter length, return it.
  IF(@MatterLen = 'True')
    BEGIN
      SELECT @MaxLen AS [max_length]
    END

  -- Procedure is called to automatically calculate the next matter number
  IF(@MatterLen <> 'True') AND (RTRIM(ISNULL(@MatterNumber, '')) = '')
    BEGIN
      -- Calculate the next matter number
      SELECT @NewMatter = 1000000001 + ISNULL(MAX(CASE WHEN ISNUMERIC(MAT.[Matter]) = 0
                                                            THEN 0
                                                       ELSE CONVERT(INT, MAT.[Matter]) END), 0)
        FROM [dbo].[matters] MAT
       WHERE MAT.[ClientCode] = @ClientCode

      SELECT @NewMatterNum = REVERSE(SUBSTRING(REVERSE(CONVERT(VARCHAR(10), @NewMatter)), 1, @MaxLen))

      SET @MatterCode = @NewMatterNum 
    END

  -- Procedure is called to check whether a previously generated number is still valid
  IF(@MatterLen <> 'True') AND (RTRIM(ISNULL(@MatterNumber, '')) <> '')
    BEGIN
      IF NOT EXISTS
        (SELECT TOP 1 1 
           FROM [dbo].[matters] MAT
          WHERE MAT.[Code] = @ClientCode + '/' + @MatterNumber)
        BEGIN
          SET @MatterCode = @MatterNumber
        END
      ELSE
        BEGIN
          SELECT 'This matter code already exists.'
        END
    END
	
  SET NOCOUNT OFF

END 

GO


IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = 'KAAS_CP_GetNextActionId'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetNextActionId]
  END
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_GetNextActionId]
AS

/*******************************************************************************************************
* Dummy Procedure in preparation for the use of the DiarySeed table									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_GetNextActionId]											   *
* Copied from			: [dbo].[ky_NETGetNextActionID]											       *
* Copied from			: [dbo].[KAAS_GetNextActionID]											       *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
* 2022-02-11	Vinodhkumar.M   Created - to upload Document in client portal                          *
 *******************************************************************************************************/

BEGIN
    --Old code START
    --DECLARE @nextVAL INT
    --DECLARE @delVAL INT

    --SELECT @nextVAL = ISNULL(MAX(DIA.[ActionID]), 0) + 1
    --  FROM [dbo].[diary] DIA

    --SELECT @delVAL = ISNULL(MAX(DIA.[ActionID]), 0) + 1
    --  FROM [dbo].[DiaryDeletionLog] DIA

    --IF (@delVAL > @nextVAL)
    --  BEGIN
    --    SET @nextVAL = @delVAL
    --  END

    --RETURN @nextVAL
    --Old code END
    DECLARE @MaxActionID INT

    DECLARE @bsuccess BIT

    SET @bsuccess = 0

    WHILE (@bsuccess = 0)
      BEGIN
        BEGIN TRY
          INSERT
            INTO [dbo].[diaryids] DEFAULT VALUES

            SET @MaxActionID = SCOPE_IDENTITY()

          SET @bsuccess = 1
        END TRY
        BEGIN CATCH
          SET @bsuccess = 0
        END CATCH
      END

    -- This while loop handles the possibility that a piece of legacy code uses the OLD mechanism
    WHILE EXISTS
          (SELECT TOP 1 1
            FROM [dbo].[diary] [DIA]
            WHERE [DIA].[ACTIONID] = @MaxActionID)
      BEGIN
        SET @bsuccess = 0

        WHILE (@bsuccess = 0)
          BEGIN
            BEGIN TRY
              INSERT
                INTO [dbo].[diaryids] DEFAULT VALUES

                SET @MaxActionID = SCOPE_IDENTITY()

              SET @bsuccess = 1
            END TRY
            BEGIN CATCH
              SET @bsuccess = 0
            END CATCH
          END
      END

    DELETE [dbo].[diaryids]

    RETURN @MaxActionID
END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_GetNextTrackReference'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetNextTrackReference]
  END
GO

CREATE PROCEDURE 
       [dbo].[KAAS_CP_GetNextTrackReference]
	   (@Result     INT   OUTPUT)
AS
/*******************************************************************************************************
* Gets next available track referene number                                                            *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_GetNextTrackReference]                                        *
* Copied from			: [dbo].[spGetNextTrackReferenceInDiaryAttachments]                            *
* Copied from			: [dbo].[KAAS_GetNextTrackReferenceInDiaryAttachments]                         *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-10	Vinodhan K		Created                                                                *
* 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                          *
* 2022-02-11	Vinodhkumar.M   return the value using output parameter                                *
 *******************************************************************************************************/
BEGIN
	DECLARE @TrackReference INT

	EXEC @TrackReference = [dbo].[KAAS_CP_GetNextTrackRefValue]

	SET @Result = @TrackReference

	--SELECT
	--	ISNULL(MAX(TRACKREFERENCE), 0)+1    AS    TRACKREFERENCE
	--FROM
	--	dbo.DiaryAttachments  --ORDER BY TRACKREFERENCE DESC
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_GetNextTrackRefValue'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetNextTrackRefValue]
  END
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_GetNextTrackRefValue]
AS
/**********************************************************************************
 * SP Name : KAAS_CP_GetNextTrackRefValue
 *Copied from [dbo].[ky_NETGetNextTrackReference]
 *
 * Dummy Procedure in preparation for the use of the DiaryAttachmentsSeed table
 *
 * Until this is in place, just calculate the next available TrackReference
 *
 * Modification History
 * 2015-10-01 Pino Carafa            Created
 * 2015-11-12 Pino Carafa            Include the Diary Att Deletion Log Trackrefs
 *                                   that way, if an attachment is created and
 *                                   then immediately deleted, its trackref is
 *                                   not reused.
 * 2017-03-09 Pino Carafa            Implement trackreferences table solution
 *
 * 2022-02-11 Vinodhkumar.M          Created
 **********************************************************************************/
BEGIN
    --old code START
    --DECLARE @nextVAL INT
    --DECLARE @delVAL INT

    --SELECT @nextVAL = ISNULL(MAX(DAT.[TrackReference]), 0) + 1
    --  FROM [dbo].[DiaryAttachments] DAT

    --SELECT @delVAL = ISNULL(MAX(DAT.[TrackReference]), 0) + 1
    --  FROM [dbo].[DiaryAttachmentDeletionLog] DAT

    --IF (@delVAL > @nextVAL)
    --  BEGIN
    --    SET @nextVAL = @delVAL
    --  END

    --RETURN @nextVAL
    --old code END

    DECLARE @MaxTrackReference INT

    DECLARE @bsuccess BIT

    SET @bsuccess = 0

    WHILE (@bsuccess = 0)
      BEGIN
        BEGIN TRY
          INSERT
            INTO [dbo].[trackreferences] DEFAULT VALUES

          SET @MaxTrackReference = SCOPE_IDENTITY()

          SET @bsuccess = 1
        END TRY
        BEGIN CATCH
          SET @bsuccess = 0
        END CATCH
      END

    -- This while loop handles the possibility that a piece of legacy code uses the OLD mechanism
    WHILE EXISTS
          (SELECT TOP 1 1
             FROM [dbo].[DiaryAttachments] [DAT]
                  with (nolock)
            WHERE [DAT].[TrackReference] = @MaxTrackReference)
      BEGIN
        SET @bsuccess = 0

        WHILE (@bsuccess = 0)
          BEGIN
            BEGIN TRY
              INSERT
                INTO [dbo].[trackreferences] DEFAULT VALUES

              SET @MaxTrackReference = SCOPE_IDENTITY()

              SET @bsuccess = 1
            END TRY
            BEGIN CATCH
              SET @bsuccess = 0
            END CATCH
          END
      END

    --DELETE [dbo].[trackreferences]

    RETURN @MaxTrackReference
END
GO
IF OBJECT_ID(N'KAAS_CP_GetPortalTemplateForKey',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetPortalTemplateForKey]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_GetPortalTemplateForKey]
    (@TemplateKey VARCHAR(100))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetPortalTemplateForKey] 									   *
* Description: To get email or message template for provided key									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-02    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN
	
	SELECT 
		[PortalTemplateId]	AS [PortalTemplateId],
		[TemplateType]		AS [TemplateKey],
		[TemplateSubject]	AS [TemplateSubject],
		[TemplateBody]		AS [TemplateBody]
	FROM
		[dbo].[PortalNotificationTemplate]
	WHERE
		[TemplateType] = @TemplateKey

END

GO

IF OBJECT_ID(N'KAAS_CP_GetRatesFields',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetRatesFields]
GO
CREATE PROCEDURE [dbo].[KAAS_CP_GetRatesFields]
(@FormId INT = 0)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetRatesFields]	      									   *
* Description: To get fields for client portal														   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-04-13    Vinodhkumar.M        Created														   *
 *******************************************************************************************************/

BEGIN

														SELECT		  [RecordId],
																		[FormId],
									  LTRIM(RTRIM([FilePreFix])) AS [FilePreFix],
										LTRIM(RTRIM([FieldName])) AS [FieldName],
																	[FieldOrder],
									  LTRIM(RTRIM([FieldLabel])) AS [FieldLabel],
																	  [Required],
																	  [FieldTip],
																 [ControlTypeID],
																		 [Lines],
																	[WidthChars]
														FROM 
																[dbo].[WebFields]
														WHERE  
															  [FormId] = @FormId
														ORDER BY
															    [FieldOrder] ASC


													SELECT		[WebAssociateID],
																		[FormId],
						LTRIM(RTRIM([CaseAssociateType])) AS [CaseAssociateType],
							  LTRIM(RTRIM([AssociateLabel])) AS [AssociateLabel],
																[AssociateOrder],
																[PopupSelection],
																[AllowMultiples],
															  [DefaultMultiples]
												   FROM 
														   [dbo].[WebAssociates]

												   WHERE      
															  [FormId] = @FormId
												ORDER BY
															[AssociateOrder] ASC




											SELECT 	   [WAF].[WebAssociateFieldID],
															[WAF].[WebAssociateId],
								LTRIM(RTRIM([WAF].[FieldPrefix])) AS [FieldPrefix],
									LTRIM(RTRIM([WAF].[FieldName])) AS [FieldName],
																[WAF].[FieldOrder],
								  LTRIM(RTRIM([WAF].[FieldLabel])) AS [FieldLabel],
																  [WAF].[FieldTip],
																  [WAF].[Required],
															 [WAF].[ControlTypeID],
																	 [WAF].[Lines],
																[WAF].[WidthChars]

											FROM	
												 [dbo].[WebAssociatesFields] [WAF]
					  
											INNER JOIN	
											[dbo].[WebAssociates] [WA] ON [WA].[WebAssociateID] = [WAF].[WebAssociateId]

											WHERE		 
														   [WA].[FormId] = @FormId

											ORDER BY
															[WAF].[WebAssociateId],
															[WAF].[FieldOrder] ASC
											




			
END

GO






IF OBJECT_ID(N'KAAS_CP_GetRateTitle',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetRateTitle]
GO
CREATE PROCEDURE [dbo].[KAAS_CP_GetRateTitle]
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetRateTitle]	      										   *
* Description: To get form details for client portal													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-04-11    Vinodhkumar.M        Created														   *
 *******************************************************************************************************/

BEGIN

			SELECT  Title,
					FormId,
					FormName,
					CasePlanCode,
					Handler,
					Team,
					InitialActionCode,
					RequestAction,
					Department,
					WorkType,
					FeCode,
					TemplateCode
					 
			 FROM  [dbo].[WebForms]
END

GO






IF OBJECT_ID(N'KAAS_CP_GetSettings',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetSettings]
GO
CREATE PROCEDURE [dbo].[KAAS_CP_GetSettings]
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetSettings]	      										   *
* Description: To get settings for client portal													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-27    Aakif        Created																   *
* 2021-05-31    Aakif        Included column for two factor authentication							   *
 *******************************************************************************************************/

BEGIN
	SELECT
		[TenantLogo]						   AS [TenantLogo], 
		[TenantLogoType]					   AS [TenantLogoType],
		[UPEKey]							   AS [UPEKey],
		ISNULL([IsTwoFactorEnabled], 0)		   AS [IsTwoFactorEnabled],
		ISNULL([IsLockOut_Attempt], 0)		   AS [IsLockOutAttempt],
		ISNULL([LockoutDurationInMins], 10)    AS [LockoutLimitInMin],
		ISNULL([PasswordResetNotification], 0) AS [PasswordResetNotification]
	FROM
		[dbo].[ClientPortalSetting]
END

GO






IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_GetUploadAzureInfo'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_GetUploadAzureInfo]
  END
GO

Create Procedure
       [dbo].[KAAS_CP_GetUploadAzureInfo]
      (@TrackReference INT,
       @Version        INT)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[ky_NETSPGetAzureDATInfo]                                                                           *
 *                                                                                                           *
 * Gets the information Azure needs to retrieve a Diary Attachment                                           *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * First compatible version:                5.6.4.1                                                  *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History                                                                                      *
 * 2018-11-12   Pino Carafa       Created                                                                    *
 * 2019-11-19   Pino Carafa       Add Link to DiaryAttachmentOriginalMatterLinks                             *
 * 2020-02-06   Pino Carafa       Filepath loses colon for file paths that are really local, and that don't  *
 *                                have a drive letter covered by [dbo].[UNCAlias]                            *
 * 2020-05-26   Pino Carafa       Add Matter Code and Client Code                                            *
 * 2020-06-08   Arun Vasu         Copied from Ky_NETSPGetAzureDATInfo                                        *
 * 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                                *
 *************************************************************************************************************/
BEGIN
  DECLARE @FilePath       VARCHAR(500)
  DECLARE @Document       VARCHAR(100)
  DECLARE @DotPos         INT
  DECLARE @SlashPos       INT
  DECLARE @FileExtension  VARCHAR(10)
  DECLARE @MatterUniqueID INT
  DECLARE @IsCurrent      BIT
  DECLARE @Type           VARCHAR(10)
  DECLARE @MatterCode     VARCHAR(20)
  DECLARE @ClientCode     VARCHAR(10)

  SELECT @TrackReference = [DAT].[TrackReference],
         @Document = RTRIM(ISNULL([DAT].[DOCUMENT], '')),
         @FilePath = REVERSE(RTRIM(ISNULL([DAV].[Filepath], ISNULL([DAT].[FILEPATH], '')))),
         @MatterUniqueID = ISNULL([DAOML].[OriginalUniqueID], [MAT].[uniqueid]),
         @Version = CASE WHEN [DAV].[Version] IS NULL
                              THEN [CV].[CurrentVersion]
                         ELSE [DAV].[Version] END,
         @IsCurrent = CASE WHEN [DAV].[Version] IS NULL
                               THEN 1
                          ELSE 0 END,
         @Type = [DAT].[TYPE],
         @MatterCode = RTRIM(ISNULL([MAT].[Code], '')),
         @ClientCode = RTRIM(ISNULL([MAT].[ClientCode], ''))
    FROM [dbo].[DiaryAttachments] [DAT]
         LEFT OUTER JOIN [dbo].[DiaryAttachmentOriginalMatterLinks] [DAOML]
                      ON [DAOML].[TrackReference] = [DAT].[TrackReference]
         INNER JOIN [dbo].[diary] [DIA]
                    INNER JOIN [dbo].[matters] [MAT]
                            ON [MAT].[Code] = [DIA].[CASECODE]
                 ON [DIA].[ACTIONID] = [DAT].[DiaryID]
         LEFT OUTER JOIN [dbo].[DiaryAttachmentVersioning] [DAV]
                      ON [DAV].[TrackReference] = [DAT].[TrackReference]
                     AND [DAV].[Version] = @Version
         CROSS APPLY (SELECT ISNULL(MAX([DAV2].[Version]), 0) + 1 AS [CurrentVersion]
                        FROM [dbo].[DiaryAttachmentVersioning] [DAV2]
                       WHERE [DAV2].[TrackReference] = [DAT].[TrackReference]) [CV]
   WHERE [DAT].[TrackReference] = @TrackReference

  SET @DotPos = CHARINDEX('.', @FilePath)
  SET @SlashPos = CHARINDEX('\', @FilePath)

  IF @DotPos < 1
    BEGIN
      SET @FileExtension = ''
    END
  ELSE
    IF @DotPos < @SlashPos
      BEGIN
        SET @FileExtension = REVERSE(SUBSTRING(@FilePath, 1, @DotPos))
      END
    ELSE
      BEGIN
        SET @FileExtension = ''
      END

  IF @Document = ''
    BEGIN
      IF @SlashPos > 0
        BEGIN
          SET @Document = REVERSE(SUBSTRING(@FilePath, 1, @SlashPos - 1))
          SET @Document = SUBSTRING(@Document, 1, LEN(@Document) - LEN(@FileExtension))
          IF @Document LIKE '%_' + CONVERT(VARCHAR(10), @TrackReference)
            BEGIN
              SET @Document = SUBSTRING(@Document, 1, LEN(@Document) - LEN('_' + CONVERT(VARCHAR(10), @TrackReference)))
            END
        END
      ELSE
        BEGIN
          SET @Document = 'File'
        END
    END

  SET @FilePath = REVERSE(@FilePath)
  IF LEN(@FilePath) > 1
    BEGIN
      IF SUBSTRING(@FilePath, 2, 1) = ':'
        BEGIN
          IF (SELECT [UNC].[UNC] FROM [dbo].[UNCAlias] [UNC] WHERE [UNC].[Drive] = SUBSTRING(@FilePath, 1, 1)) IS NOT NULL
            BEGIN
              SELECT @FilePath = ISNULL((SELECT [UNC].[UNC] FROM [dbo].[UNCAlias] [UNC] WHERE [UNC].[Drive] = SUBSTRING(@FilePath, 1, 1)), SUBSTRING(@FilePath, 1, 1)) + SUBSTRING(@FilePath, 3, LEN(@FilePath) - 2)
            END
        END
    END

  SELECT @TrackReference AS [TrackReference],
         @Document       AS [Document],
         @FileExtension  AS [FileExtension],
         @MatterUniqueID AS [MatterUniqueID],
         @FilePath       AS [FilePath],
         @Version        AS [RetrievedVersion],
         @IsCurrent      AS [IsCurrent],
         @Type           AS [Type],
         @MatterCode     AS [MatterCode],
         @ClientCode     AS [ClientCode]
END

GO
IF OBJECT_ID(N'KAAS_CP_GetUserLoginDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetUserLoginDetails]
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_CP_GetUserLoginDetails]
	(@EmailId VARCHAR(200))
AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetUserLoginDetails]      									   *
* Description: To get login details for specified email												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-27    Aakif        Created                                                                   *
* 2021-05-31    Aakif        Included column for two factor authentication							   *
* 2022-07-28    vinodhkumar        restrict deletes user from listing							       *
 *******************************************************************************************************/

BEGIN
	SELECT
		  [ClientLoginId]							AS	 [ClientLoginId],
		  [Email]									AS	 [Email],
		  [PhoneNumber]								AS	 [PhoneNumber],
		  [Name]									AS	 [Name],
		  [ClientDefaulTimeZone]					AS	 [ClientDefaulTimeZone],
		  [AccessCode]								AS	 [AccessCode],
		  [AccessCodeStatus]						AS	 [AccessCodeStatus],
		  [PasswordHash]							AS	 [PasswordHash],
		  ISNULL([NoOfAttempt],0)					AS   [NoOfAttempt],
		  [LastAccessedDateTime]					AS	 [LastAccessedDateTime],
		  [LockedOutEndDate]						AS	 [LockedOutEndDate],
		  [SecurityStamp]							AS	 [SecurityStamp],
		  ISNULL([IsTwoFactorEnabled],0)			AS   [IsTwoFactorEnabled],
		  [IsActiveLogin]							AS   [IsActiveLogin],
		  [IsFirstlogin]							AS   [IsFirstLogin],
		  [IsDeleted]								AS	 [IsDeleted],
		  [IsAdmin]									AS	 [IsAdmin],
		  [IsEmailConfirmed]						AS	 [IsEmailConfirmed],
		  [IsPhoneNumberConfirmed]					AS	 [IsPhoneNumberConfirmed],
		  [EmailActivationToken]					AS	 [EmailActivationToken],
		  [ConcurrencyStamp]						AS   [ConcurrencyStamp],
		  [PasswordResetOTP]						AS   [PasswordResetOTP],
		  [PasswordResetOTPCreationTime]			AS   [PasswordResetOTPCreationTime],  
		  [PasswordResetOTPExpirationTime]			AS   [PasswordResetOTPExpirationTime],
		  [OTPAccessToken]							AS	 [OTPAccessToken],
		  [OTPAccessTokenCreationTime]				AS	 [OTPAccessTokenCreationTime],
		  [OTPAccessTokenExpirationTime]			AS   [OTPAccessTokenExpirationTime],
		  [PasswordResetOTPAttemptCount]			AS	 [PasswordResetOTPAttemptCount],
		  [PasswordResetLockOutEndDate]				AS	 [PasswordResetLockOutEndDate],
		  [IsPasswordResetOTPVerified]				AS	 [IsPasswordResetOTPVerified],
		  [IsUserVerifiedEmail]						AS	 [IsUserVerifiedEmail],
		  [VerifiedByAdminUserId]					AS	 [VerifiedByAdminUserId],
		  [EmailActivationTokenCreatedTime]			AS   [EmailActivationTokenCreatedTime],
		  [EmailActivationTokenExpirationTime]		AS   [EmailActivationTokenExpirationTime],
		  [IsAdminVerifiedUserLogin]				AS   [IsAdminVerifiedUserLogin],
		  [SecretQuestion]							AS   [SecretQuestion],
		  [Answer]									AS	 [Answer]
	FROM
		  [dbo].[ClientLogin]
	WHERE 
		  [Email] = @EmailId AND [IsDeleted] = 0
END

GO
IF OBJECT_ID(N'KAAS_CP_GetUserSetting',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_GetUserSetting]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_GetUserSetting]
    (@LoginId       BIGINT,
	 @SettingKey    VARCHAR(100))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_GetUserSetting]											   *
* Description: TO GET CLIENT PORTAL USER SETTING													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-07-06    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN
	SELECT	[US].[SettingId]	 AS [SettingId],
			[US].[ClientLoginId] AS [ClientLoginId],
			[US].[Key]			 AS [Key],
			[US].[Value]		 AS [Value]
	  FROM [dbo].[ClientPortalUserSetting] [US]
	 WHERE [US].[ClientLoginId] = @LoginId
	   AND [US].[Key] = @SettingKey

END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_CP_InsertDocumentIntoFolder'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_InsertDocumentIntoFolder]
  END
GO

 CREATE PROCEDURE
        [dbo].[KAAS_CP_InsertDocumentIntoFolder]
       (@copyxml         VARCHAR(MAX))
AS
/***********************************************************************************************************
* Flags the documents passed in through @copyxml as being "in" the document folder(s) in the XML document  *
* @copyxml       - an xml string outlining the nature of the changes                                       *
*                                                                                                          *
* Stored Procedure Name : KAAS_CP_InsertDocumentIntoFolder                                                 *
* Copied From           : [dbo].[ky_NETSPCopyDocsToDocFolder]                                              *
* Copied from			: [dbo].[KAAS_CopyDocsToDocFolder]                                                 *
*                                                                                                          *
* Modification History:                                                                                    *
* 2016-04-26    Pino Carafa      Created                                                                   *
* 2019-10-11    Vinodhan K       Created KAAS_CopyDocsToDocFolder                                          *
* 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                              *
************************************************************************************************************/
BEGIN
  SET NOCOuNT ON

  DECLARE @iSL INT
  DECLARE @MAX INT

  DECLARE @data TABLE
         ([seq]                       INT              IDENTITY(1, 1)    NOT NULL      PRIMARY KEY,
          [folderid]                  INT                                NOT NULL,
          [trackreference]            INT                                NOT NULL)
          
  BEGIN TRY
  EXEC SP_XML_PREPAREDOCUMENT @iSL OUTPUT, @copyxml
  END TRY
  BEGIN CATCH
  EXEC SP_XML_PREPAREDOCUMENT @iSL OUTPUT, N'<copydocstofolders/>'
  END CATCH

  INSERT
    INTO @data
        ([folderid],
         [trackreference])
  SELECT SRC.[folderid],
         SRC.[trackreference]
    FROM OPENXML(@iSL, N'copydocstofolders/copy')
    WITH ([folderid]                  INT            '@tofolder',
          [trackreference]            INT            '@trackreference') SRC

  EXEC sp_xml_removedocument @iSL

  INSERT
    INTO [dbo].[DocFolderDocuments]
        ([DocFolderID],
         [TrackReference])
  SELECT DT.[folderid],
         DT.[trackreference] 
    FROM @data DT
         LEFT OUTER JOIN [dbo].[DocFolderDocuments] DFD
                      ON DFD.[DocFolderID] = DT.[folderid]
                     AND DFD.[TrackReference] = DT.[trackreference]
   WHERE DFD.[TrackReference] IS NULL

   SET NOCOUNT OFF

END
GO

IF OBJECT_ID(N'KAAS_CP_InsertMatterAndAssociate',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_InsertMatterAndAssociate]
GO
CREATE PROCEDURE
       [dbo].[KAAS_CP_InsertMatterAndAssociate]      
       (@JsonData    NVARCHAR(MAX), 
	   @ClientCode   VARCHAR(20),
	   @FormId		 INT,
	   @LoginId		 BIGINT = 0,
       @Result		 INT OUTPUT)      
      
AS        
/*******************************************************************************************************
* This procedure is used to Generate Case Associate code.				  							   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_InsertMatterAndAssociate]									   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2022-04-20	Vinodhkumar.M		Created for client portal                                          *
* 2022-06-06	Aakif				Marked the case associate as published by default if present	   *
* 2022-06-16    Arun V              Added Default case code
* 2022-06-17    Arun V              Case Associate Type table insert added for assocaites.
* 2022-07-07	Aakif				Included option to show recently accessed matter first			   *
 *******************************************************************************************************/
BEGIN      
 SET NOCOUNT ON    
     BEGIN TRY
        BEGIN TRAN

			DECLARE @TempTable Table
			(
			[Key]	            NVARCHAR(50),
			[Value]	            NVARCHAR(500),
			[Type]	            NVARCHAR(10),
			[WebAsscoaiteId]	NVARCHAR(10),
			[ControlTypeId]		NVARCHAR(10)
			)
			--Matters
			DECLARE @MatterCode NVARCHAR(20) = '';
			DECLARE @FECode nvarchar(20) = '';
			DECLARE @CasePlanCode nvarchar(20) = '';
			DECLARE @WType nvarchar(20) = '';
			DECLARE @Dept nvarchar(20) = '';

			--For New Actions
			DECLARE @NewActionCode VARCHAR(15) = '';

			DECLARE @DynamicMATColums NVARCHAR(500) = '';
			DECLARE @DynamicMATValues NVARCHAR(500) = '';
	
			-- Case Associates Names
			DECLARE @CaseAssociateCodeOutput NVARCHAR(20) = '';
			DECLARE @DynamicCANColums NVARCHAR(500) = '';
			DECLARE @DynamicCANValues NVARCHAR(500) = '';

			DECLARE @WebAssociateTempTable Table
			(
			[RowNumber]			INT,
			[WebAssociateId]	INT,
			[CaseAssociateType] VARCHAR(30)
			)
			DECLARE @IncrementValue INT = 1;
			DECLARE @RowCount INT = 0;
			DECLARE @WebAssociateId INT = 0;
			DECLARE @CaseAssociateType VARCHAR(30) = '';

			--UDF 
			DECLARE @UDFTempTable Table
			(
			[RowNumber]			INT,
			[ControlTypeId]		INT,
			[KeyName]		    NVARCHAR(20),
			[KeyValue]			NVARCHAR(100)
			)
			DECLARE @UDFIncrementValue  INT = 1;
			DECLARE @UDFRowCount		INT = 0;
			DECLARE @UDFControlTypeId   INT = 0;
			DECLARE @UDFKeyName         VARCHAR(20)  = 0;
			DECLARE @UDFKeyValue        VARCHAR(100) = 0;



			INSERT INTO @TempTable
			SELECT *
			FROM OPENJSON(@JsonData)
			WITH (
			[Key] NVARCHAR(50) '$.Key',
			[Value] NVARCHAR(500) '$.Value',
			[Type] NVARCHAR(10) '$.Type',
			[WebAsscoaiteId] NVARCHAR(10) '$.WebAssociateId',
			[ControlTypeId] NVARCHAR(10) '$.ControlTypeId'
			);

			EXEC  [dbo].[KAAS_CP_GetNewMatterCode] @ClientCode,N'',N'False', @MatterCode OUT

			SELECT  @FECode = LTRIM(RTRIM(FeCode)),
					@WType = LTRIM(RTRIM(WorkType)),
					@Dept = LTRIM(RTRIM(Department)),
					@NewActionCode = LTRIM(RTRIM(ISNULL(InitialActionCode, ''))),
					@CasePlanCode =  LTRIM(RTRIM(ISNULL(CasePlanCode, '')))
			 FROM   [dbo].[WebForms]
			 WHERE  FormId = @FormId

			--INSERT MATTERS START
					SELECT  
						  @DynamicMATColums = @DynamicMATColums + [Key] + ', ', 
						  @DynamicMATValues = @DynamicMATValues + ''''+[Value] +''''+ ', '
					FROM  @TempTable WHERE [Type]='MAT:'

					SELECT @DynamicMATColums = SUBSTRING(@DynamicMATColums, 0, LEN(@DynamicMATColums)),
					@DynamicMATValues = SUBSTRING(@DynamicMATValues, 0, LEN(@DynamicMATValues))

					DECLARE @InsertMatterQuery NVARCHAR(MAX) = 
						'Insert into Matters (Code, ClientCode, Matter, FECode, WType, Dept,[Started],Publish, '+@DynamicMATColums+') values 
						 ( '''+@ClientCode+'/'+@MatterCode+''' , '''+@ClientCode+''','''+@MatterCode+''', '''+@FECode +''','''+@WType+''' ,'''+@Dept+''',GETDATE(),''P'','+@DynamicMATValues+' )' 

						 INSERT INTO CaseMaster(CSCODE,CSCLIENTCDE,CSFNR,CSDATEENTERED_DATE, CSWKTCODE)
						 VALUES(@ClientCode+'/'+@MatterCode,@ClientCode,@FECode,GETDATE(), @CasePlanCode)

					EXEC(@InsertMatterQuery) 

					-- UPDATE MATTER DESC TO 'CLIENT_NAME -V- MATTER_DESC'
					DECLARE @ClientName VARCHAR(256);
					DECLARE @ClientAndMatterCode VARCHAR(20) = @ClientCode+'/'+@MatterCode;

					SELECT @ClientName = [CON].[Name]
					  FROM [dbo].[Contacts] [CON]
					 WHERE [CON].[Code] = @ClientCode
					
					UPDATE [MAT]
					   SET [MAT].[Description] = ISNULL(@ClientName, '') + ' -V- ' + ISNULL([MAT].[Description], '')
					  FROM [dbo].[matters] [MAT]
					 WHERE [MAT].[Code] = @ClientCode+'/'+@MatterCode
					-- UPDATE MATTER DESC END
						
					-- UPDATE RECENT MATTER DATA
					EXEC KAAS_CP_AddEditRecentMatterList @LoginId, @ClientAndMatterCode

			-- INSERTING NEW TEMPLATE ACTIONS START
			IF(ISNULL(@NewActionCode, '') <> '')
			BEGIN
				DECLARE @FullMatterCode VARCHAR(20) = @ClientCode+'/'+@MatterCode;
				EXEC [dbo].[KAAS_CP_CreateActionForNewInstruction] @FullMatterCode, @FormId
			END

			-- INSERTING NEW TEMPLATE ACTIONS END

			--INSERT MATTERS END

			--INSERT CASE ASSOCIATES NAMES START
			INSERT INTO @WebAssociateTempTable(RowNumber,WebAssociateId,CaseAssociateType)
			SELECT ROW_NUMBER() OVER(ORDER BY FORMID ) AS RowNumber,WebAssociateID,CaseAssociateType FROM [dbo].[WebAssociates] WHERE [FormId] = @FormId
	
			SELECT @RowCount = COUNT(1) FROM @WebAssociateTempTable

			WHILE(@IncrementValue <= @RowCount)
				BEGIN
					EXEC [dbo].[KAAS_CP_GenerateCaseAssociateCode] '',@CaseAssociateCodeOutput OUT 
					SELECT @WebAssociateId = WebAssociateId, @CaseAssociateType = LTRIM(RTRIM(CaseAssociateType)) FROM @WebAssociateTempTable WHERE RowNumber = @IncrementValue
			
					SELECT  
						   @DynamicCANColums = @DynamicCANColums + [Key] + ', ', 
		 				   @DynamicCANValues = @DynamicCANValues + ''''+[Value] +''''+ ', '
					 FROM  @TempTable 
					WHERE  [Type]='CAN:' AND [WebAsscoaiteId]= ''+@WebAssociateId+''

					SELECT @DynamicCANColums = SUBSTRING(@DynamicCANColums, 0, LEN(@DynamicCANColums)),
					@DynamicCANValues = SUBSTRING(@DynamicCANValues, 0, LEN(@DynamicCANValues))

					DECLARE @InsertCaseAssociateQuery NVARCHAR(MAX) = 
					'Insert into CaseAssociatesNames (Code,Type,'+@DynamicCANColums+') values 
					( '''+@CaseAssociateCodeOutput+''', '''+@CaseAssociateType+''','+@DynamicCANValues+' )' 

					INSERT INTO CaseContacts(CASECODE,CONTYPE,CONNUM,NAMECODE, PUBLISH)
					VALUES(@ClientCode+'/'+@MatterCode,@CaseAssociateType,@IncrementValue,@CaseAssociateCodeOutput, 'Y')

					INSERT INTO CaseAssoicatesTypes(NAMECODE, TYPECODE, SEARCHCODE, Retired) VALUES
					(@CaseAssociateCodeOutput, @CaseAssociateType,'', 'N')

					SET @DynamicCANColums = '';
					SET @DynamicCANValues = '';
					SET @IncrementValue = @IncrementValue + 1;

					EXEC(@InsertCaseAssociateQuery) 

				END
			--INSERT CASE ASSOCIATES NAMES  END


			--INSERT UDF START
	
			INSERT INTO @UDFTempTable(RowNumber,ControlTypeId,KeyName,KeyValue)
			SELECT ROW_NUMBER() OVER(ORDER BY ControlTypeID ) AS RowNo,ControlTypeID,[Key],Value
			  FROM @TempTable
			 WHERE [Type]='UDF:'
	
			SELECT @UDFRowCount = COUNT(1) FROM @UDFTempTable

			WHILE(@UDFIncrementValue <= @UDFRowCount)
			  BEGIN
		
				SELECT  @UDFControlTypeId = ControlTypeId,
						@UDFKeyName       = KeyName,
						@UDFKeyValue      = KeyValue
				  FROM  @UDFTempTable 
				 WHERE  RowNumber= @UDFIncrementValue

				 --INSERT UDF
				 DECLARE @CASECODE VARCHAR(20) = ''+@ClientCode+'/'+@MatterCode+'';
				 DECLARE @UDF_INSERT INT = 0;
				 DECLARE @UDF_UPDATE INT = 0;

					EXEC  [dbo].[KAAS_CP_NETOtherCaseDetailsInsert] @CASECODE,@UDFKeyName,@UDF_INSERT OUT

				IF(@UDFControlTypeId = 1 OR @UDFControlTypeId = 2 OR @UDFControlTypeId = 5)
					BEGIN
					  EXEC  [dbo].[KAAS_CP_NETOtherCaseDetailsUpdate] @CASECODE,'UDF:',@UDFKeyName,@UDFKeyValue,0,NULL,@UDF_UPDATE OUT
					END

				ELSE IF(@UDFControlTypeId = 3)
					BEGIN
					  EXEC  [dbo].[KAAS_CP_NETOtherCaseDetailsUpdate] @CASECODE,'UDF:',@UDFKeyName,'',0,@UDFKeyValue,@UDF_UPDATE OUT
					END

				ELSE IF(@UDFControlTypeId = 4)
					BEGIN
					  EXEC  [dbo].[KAAS_CP_NETOtherCaseDetailsUpdate] @CASECODE,'UDF:',@UDFKeyName,'',@UDFKeyValue,NULL,@UDF_UPDATE OUT
					END

				SET @UDFIncrementValue = @UDFIncrementValue + 1;
			  END

			--INSERT UDF END

		  SET @Result = 1
		 SET NOCOUNT OFF   
 
   COMMIT TRAN
    END TRY
    BEGIN CATCH
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRAN
        END
    END CATCH   
END   
  

GO


IF OBJECT_ID(N'KAAS_CP_ListCaseContacts',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_ListCaseContacts]
GO
  
CREATE PROCEDURE  
       [dbo].[KAAS_CP_ListCaseContacts]  
      (@CaseCode	VARCHAR(20),  
       @ForEmail	BIT           = 1,  
       @Number		INT           = 0,  
       @Status		VARCHAR(1)	  = '',
	   @SearchText	VARCHAR(4000) = NULL
	   )  
AS  
/*************************************************************************************************************  
 * Stored Procedure Name: [KAAS_CP_ListCaseContacts]  
 * Copied From			: [ky_NETSPListCaseContacts]  
 *
 * List Case Contacts for Outlook Add-in  
 *  
 *   *******************  
 *   *                 *  
 *   * PLEASE NOTE:    * If you make any changes to this procedure's parameters, please inform Pino Carafa as  
 *   * ============    * this will impact the Outlook Add-in!  
 *   *                 *  
 *   *******************  
 *  
 * Modification History  
 * 2015-12-03    Pino              Make it usable for Framework, too  
 * 2016-07-21    Suriya M          KEYD-3783 - When you add a new strong room Deed file to a case, the Retired  
 *                                 Associates are showing in the "From Whom" & "To Whom" fields of "DEED" tab.  
 * 2016-07-22    Pino              Set default value for Status to ensure Outlook Add-in remains unaffected  
 * 2018-05-01    Pino Carafa       KEYD-4573 Add Secondary Email  
 * 2019-12-04    Pino Carafa       Return CC CONTYPE rather than CAN TYPE in first query  
 * 2019-12-16    Pino Carafa       Return Occupation  
 * 2020-06-03    John Ginnane      KEYD-6531 - Added mobile no to output  
 * 2020-07-14    John Ginnane      KEYD-6531 - Added SourceTable and SourceCode to output  
 * 2020-08-25    Pino Carafa       KEYD-6753 - Added Title to output  
 * 2020-09-24    Arun Vasu         KEYD-6648 - Added Work phone number to output  
 * 2021-03-11    Arun Vasu         Have get the FeeEarner, Partner label from setting table ref: 11634  
 * 2021-03-12    Arun Vasu         Changed the logic the get the handler label values and set for handlers label ref: 11634  
 * 2021-06-18    Aakif			   Created
 * 2021-06-22    Aakif			   Fixed issue to fetch published contact
 * 2022-06-06    Aakif			   Included address field for case contacts
 * 2022-06-22    Aakif			   Included legal address field for associates contact
 *************************************************************************************************************/  
BEGIN  
SET NOCOUNT ON  
  DECLARE @FromWhom       VARCHAR(10)  
  DECLARE @FeeEarnerLabel VARCHAR(20)  
  DECLARE @Partner        VARCHAR(20)  
  
  IF(@Status = 'T')  
    BEGIN  
      SET @FromWhom = RTRIM(ISNULL((SELECT [FMI].[TOWHOCODE]  
                                      FROM [dbo].[FileManagerItems] [FMI]  
                                     WHERE [FMI].[NUMBER] = @Number), ''))  
    END  
  ELSE  
    BEGIN  
      SET @FromWhom = RTRIM(ISNULL((SELECT [FMI].[FROMWHOCODE]  
                                      FROM [dbo].[FileManagerItems] [FMI]  
                                     WHERE [FMI].[NUMBER] = @Number), ''))  
    END  
  
  
--Getting the fee earner, and Partner label value from setting  
    SELECT @FeeEarnerLabel = [Keyvalue]   
      FROM [Settings]   
     WHERE [KeyName] = 'FeeEarnerLabel'  
      
    SELECT @Partner = [Keyvalue]   
      FROM [Settings]   
     WHERE [KeyName] = 'PartnerLabel'  
  
  
  SELECT [RES].[CODE]															 AS [Code],  
         CASE WHEN [RES].[NAME] = ''  
                   THEN [RES].[COMPANY]  
              ELSE [RES].[NAME] END                                              AS [Name],  
         [RES].[COMPANY]														 AS [Company],  
         [RES].[EMAIL]															 AS [Email],  
         [RES].[NAMECODE],  
         [RES].[CASECODE]														 AS [CaseCode],  
         [RES].[TYPE]															 AS [Type],  
         [RES].[Occupation]                                                      AS [Occupation],  
         CASE WHEN RTRIM(ISNULL([AST].[DESCRIPTION], '')) = ''  
                   THEN [RES].[TYPE]  
              ELSE RTRIM(ISNULL([AST].[DESCRIPTION], '')) END                    AS [TypeDesc],  
         LTRIM(  CASE WHEN [RES].[NAME] = ''  
                           THEN ''  
                      WHEN [RES].[NAME] = [RES].[COMPANY]  
                           THEN ''  
                      ELSE [RES].[NAME] END  
               + CASE WHEN [RES].[COMPANY] = ''  
                           THEN ''  
                      ELSE ' (' + [RES].[COMPANY] + ')' END)                     AS [NAMECOMP],  
         [RES].[MobileNo]														 AS [MobileNo],  
         [RES].[TITLE]															 AS [Title],  
         [RES].[SourceTable],  
         [RES].[SourceCode],  
         [RES].[Work],
		 [RES].[ContactAddresses],
		 [RES].[LegalAddress]
    FROM (SELECT CONVERT(VARCHAR(10), RTRIM(ISNULL([CAN].[CODE], '')))           AS [CODE],  
                 CONVERT(VARCHAR(300), RTRIM(ISNULL([CAN].[NAME], '')))          AS [NAME],  
                 CONVERT(VARCHAR(50), RTRIM(ISNULL([CAN].[COMPANY], '')))        AS [COMPANY],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CAN].[EMAIL], '')))         AS [Email],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CAN].[OCCUPATION], '')))    AS [Occupation],  
                 CONVERT(VARCHAR(10), RTRIM(ISNULL([CC].[NAMECODE], '')))        AS [NAMECODE],  
                 CONVERT(VARCHAR(20), RTRIM(ISNULL([CC].[CASECODE], '')))        AS [CASECODE],  
                 CONVERT(VARCHAR(20), RTRIM(ISNULL([CC].[CONTYPE], '')))         AS [TYPE], --PINO 2019-12-04, WAS [CAN].[TYPE]  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CAN].[TITLE], '')))         AS [Title],  
                 CONVERT(VARCHAR(50), ISNULL([CAN].[MOBILENO], ''))              AS [MobileNo],  
                 'CaseAssociatesNames'                                           AS [SourceTable],  
                 [CAN].[CODE]                                                    AS [SourceCode],  
                 CONVERT(VARCHAR(50), ISNULL([CAN].[PHONENO], ''))               AS [Work],
				 RTRIM(ISNULL([CAN].[ADDRESS], ''))								 AS [ContactAddresses],
				 RTRIM(ISNULL([CAN].[LEGALADDRESS], ''))						 AS [LegalAddress]
            FROM [dbo].[CaseContacts] [CC]  
                 INNER JOIN [dbo].[CaseAssociatesNames] [CAN]  
                         ON [CAN].[CODE] = [CC].[NameCODE]  
                        AND (   @ForEmail = 0  
                             OR RTRIM(ISNULL([CAN].[EMAIL], '')) <> '')  
           WHERE [CC].[CASECODE] = @CaseCode
		     AND ISNULL([CC].PUBLISH, '') = 'Y'
             AND (   ISNULL([CC].Retired,'N') <> 'Y'  
                  OR [CC].NAMECODE = CASE @Number  
                                        WHEN 0 THEN ''  
                                   ELSE @FromWhom END)  
          --UNION  
          --SELECT CONVERT(VARCHAR(10), RTRIM(ISNULL([CTC].[CLCODE], '')))         AS [Code],  
          --       CONVERT(VARCHAR(300),   RTRIM(ISNULL([CTC].[FIRSTNAME], ''))  
          --                             + ' '  
          --                             + RTRIM(ISNULL([CTC].[SURNAME], '')))     AS [Name],  
          --       CONVERT(VARCHAR(50), RTRIM(ISNULL([CTC].[CLNAMECON], '')))      AS [Company],  
          --       CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[EmailAddress], '')))  AS [Email],  
          --       CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[Occupation], '')))    AS [Occupation],  
          --       CONVERT(VARCHAR(10), '')                                        AS [NAMECODE],  
          --       CONVERT(VARCHAR(20), @CaseCode)                                 AS [CaseCode],  
          --       CONVERT(VARCHAR(20), 'Client Contact')                          AS [Type],  
          --       CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[CLTITLE], '')))       AS [TITLE],  
          --       CONVERT(VARCHAR(50), ISNULL([CTC].[Mobile], ''))                AS [MobileNo],  
          --       'ClientContacts'                                                AS [SourceTable],  
          --       CONVERT(VARCHAR(50), [CTC].[id])                                AS [SourceCode],  
          --       CONVERT(VARCHAR(50),ISNULL([CTC].[WorkPhone],''))               AS [Work]  
          --  FROM [dbo].[matters] [MAT]  
          --       INNER JOIN [dbo].[ClientContacts] [CTC]  
          --               ON [CTC].[CLCODE] = [MAT].[ClientCode]  
          --              AND (   @ForEmail = 0  
          --                   OR RTRIM(ISNULL([CTC].[EmailAddress], '')) <> '')  
          -- WHERE [MAT].[CODE] = @CaseCode  
          UNION  
          SELECT CONVERT(VARCHAR(10), RTRIM(ISNULL([CAN].[CODE], '')))           AS [Code],  
                 CONVERT(VARCHAR(300), RTRIM(ISNULL([CAC].[NAME], '')))          AS [Name],  
                 CONVERT(VARCHAR(50), RTRIM(ISNULL([CAN].[COMPANY], '')))        AS [Company],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CAC].[EMAIL], '')))         AS [Email],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CAN].[OCCUPATION], '')))    AS [Occupation],  
                 CONVERT(VARCHAR(10), RTRIM(ISNULL([CC].[NAMECODE], '')))        AS [NAMECODE],  
                 CONVERT(VARCHAR(20), RTRIM(ISNULL([CC].[CASECODE], '')))        AS [CaseCode],  
                 CONVERT(VARCHAR(20), RTRIM(ISNULL([CC].[CONTYPE], '')))         AS [Type],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CAC].[JOBTITLE], '')))      AS [Title],  
                 CONVERT(VARCHAR(50), ISNULL([CAC].[MOBILE], ''))                AS [MobileNo],  
                 'CaseAssociatesContacts'                                        AS [SourceTable],  
                 CONVERT(VARCHAR(50), [CAC].[KEYID])                             AS [SourceCode],  
                 CONVERT(VARCHAR(50), ISNULL([CAC].[PHONE],''))                  AS [Work],  
				 RTRIM(ISNULL([CAC].[ADDRESS], ''))								 AS [ContactAddresses],
				 ''																 AS [LegalAddress]
            FROM [dbo].[CaseContacts] [CC]  
                 INNER JOIN [dbo].[CaseAssociatesNames] [CAN]  
                            INNER JOIN [dbo].[CaseAssociatesContacts] [CAC]  
                                    ON [CAC].[NAMECODE] = [CAN].[CODE]  
                                   AND (   @ForEmail = 0  
                                        OR RTRIM(ISNULL([CAC].[EMAIL], '')) <> '')  
                         ON [CAN].[CODE] = [CC].[NameCODE]  
           WHERE [CC].[CASECODE] = @CaseCode 
		   AND ISNULL([CC].PUBLISH, '') = 'Y'
          --UNION  
          --SELECT CONVERT(VARCHAR(10), RTRIM(ISNULL([CTC].[CODE], '')))           AS [Code],  
          --       CONVERT(VARCHAR(300), RTRIM(ISNULL([CTC].[Name], '')))          AS [Name],  
          --       CONVERT(VARCHAR(50), '')                                        AS [Company],  
          --       CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[email], '')))         AS [Email],  
          --       CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[Occupation], '')))    AS [Occupation],  
          --       CONVERT(VARCHAR(10), '')                                        AS [NAMECODE],  
          --       CONVERT(VARCHAR(20), @CaseCode)                                 AS [CaseCode],  
          --       CONVERT(VARCHAR(20), 'Client')                                  AS [Type],  
          --       CONVERT(VARCHAR(100), '')                                       AS [Title], --Not sure there is a column representing this in Contacts or client  
          --       CONVERT(VARCHAR(50), ISNULL([CLI].[CLMOBNO], ''))               AS [MobileNo],  
          --       'client'                                                        AS [SourceTable],  
          --       [CTC].[CODE]                                                    AS [SourceCode],  
          --       CONVERT(VARCHAR(50), ISNULL([CTC].[Tel], ''))                   AS [Work]  
          --  FROM [dbo].[matters] [MAT]  
          --       INNER JOIN [dbo].[Contacts] [CTC]  
          --               ON [CTC].[CODE] = [MAT].[ClientCode]  
          --              AND (   @ForEmail = 0  
          --                   OR RTRIM(ISNULL([CTC].[email], '')) <> '')  
          --       LEFT OUTER JOIN [dbo].[client] AS [CLI]  
          --                    ON [CLI].[CLCODE] = [CTC].[CODE]  
          -- WHERE [MAT].[CODE] = @CaseCode  
          UNION  
          SELECT CONVERT(VARCHAR(10), RTRIM(ISNULL([HAN].[CODE], '')))           AS [Code],  
                 CONVERT(VARCHAR(300), RTRIM(ISNULL([HAN].[Name], '')))          AS [Name],  
                 CONVERT(VARCHAR(50), '')                                        AS [Company],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([HAN].[email], '')))         AS [Email],  
                 CONVERT(VARCHAR(100), '')                                       AS [Occupation],  
                 CONVERT(VARCHAR(10), '')                                        AS [NAMECODE],  
                 CONVERT(VARCHAR(20), @CaseCode)                                 AS [CaseCode],  
                 CONVERT(VARCHAR(20),  
                   (CASE WHEN ColumnName='FECode'   
                              THEN ISNULL(@FeeEarnerLabel, 'Fee Earner')   
                       WHEN ColumnName='Partner'  
                              THEN ISNULL(@Partner, 'Partner')  
                         ELSE ColumnName   
                    END))                                                        AS [Type],  
                 CONVERT(VARCHAR(100), '')                                       AS [Title],   
                 CONVERT(VARCHAR(50), ISNULL([HAN].[PhoneNumber], ''))           AS [MobileNo],  
                 'Handlers'                                                      AS [SourceTable],  
                 [HAN].[CODE]                                                    AS [SourceCode],  
                 CONVERT(VARCHAR(50), ISNULL([HAN].[Phoneno], ''))               AS [Work],  
				  ''															 AS [ContactAddresses],
				 ''																 AS [LegalAddress]
            FROM (SELECT [UNPVT].[Handlers]     AS [HandlerValue],   
                         [UNPVT].[Handlerslist] AS [ColumnName]  
                    FROM [dbo].[matters] [MAT]  
                         UNPIVOT (    [Handlers]  
                                  FOR [Handlerslist]   
                                   IN ([MAT].[FECode],  
                                       [MAT].[Partner],  
                                       [MAT].[Secretary])) [UNPVT]  
                   WHERE [UNPVT].[Code] = @CaseCode  
                     AND [UNPVT].[Handlers] <> '') [HANDLERLIST]  
                 INNER JOIN [Handlers] [HAN]  
                         ON [HAN].[CODE] = [HANDLERLIST].[HandlerValue]  
          UNION  
          SELECT CONVERT(VARCHAR(10), RTRIM(ISNULL([CTC].[CODE], '')))           AS [Code],  
                 CONVERT(VARCHAR(300), RTRIM(ISNULL([CTC].[Name], '')))          AS [Name],  
                 CONVERT(VARCHAR(50), '')                                        AS [Company],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[SecondaryEmail],  
                                                    '')))                        AS [Email],  
                 CONVERT(VARCHAR(100), RTRIM(ISNULL([CTC].[Occupation], '')))    AS [Occupation],  
                 CONVERT(VARCHAR(10), '')                                        AS [NAMECODE],  
                 CONVERT(VARCHAR(20), @CaseCode)                                 AS [CaseCode],  
                 CONVERT(VARCHAR(20), 'Client')                                  AS [Type],  
                 CONVERT(VARCHAR(100), '')                                       AS [Title], --Not sure there is a column representing this in Contacts or client  
                 CONVERT(VARCHAR(50), ISNULL([CLI].[CLMOBNO], ''))               AS [MobileNo],  
                 'client'                                                        AS [SourceTable],  
                 [CTC].[CODE]                                                    AS [SourceCode],  
                 CONVERT(VARCHAR(50), ISNULL([CTC].[Tel], ''))                   AS [Work],  
				 RTRIM(ISNULL([CTC].[ADDRESS], ''))								 AS [ContactAddresses],
				 ''																 AS [LegalAddress]
            FROM [dbo].[matters] [MAT]  
                 INNER JOIN [dbo].[Contacts] [CTC]  
                         ON [CTC].[CODE] = [MAT].[ClientCode]  
                        AND (   @ForEmail = 0  
                             OR RTRIM(ISNULL([CTC].[SecondaryEmail], '')) <> '')  
                 LEFT OUTER JOIN [dbo].[client] AS [CLI]  
                              ON [CLI].[CLCODE] = [CTC].[CODE]  
           WHERE [MAT].[CODE] = @CaseCode) [RES]  
         LEFT OUTER JOIN [dbo].[AssociateTypes] [AST]  
                      ON [AST].[CODE] = [RES].[TYPE]
		WHERE [RES].[TYPE] <> 'client'
		AND
			(
				(RTRIM(LTRIM(ISNULL(@SearchText, ''''))) = '''') OR (RTRIM(LTRIM(@SearchText)) = '''')
				OR
				(
					   [NAME] LIKE '%' + RTRIM(LTRIM(@SearchText)) + '%'
					OR [TYPE] LIKE '%' + RTRIM(LTRIM(@SearchText)) + '%'
					OR [Email] LIKE '%' + RTRIM(LTRIM(@SearchText)) + '%'
					OR [MobileNo] LIKE '%' + RTRIM(LTRIM(@SearchText)) + '%'
					OR [Work] LIKE '%' + RTRIM(LTRIM(@SearchText)) + '%'
				)
			)
ORDER BY CASE WHEN [RES].[NAME] = ''  
                   THEN [RES].[COMPANY]  
              ELSE [RES].[NAME] END,  
         [RES].[TYPE]  
SET NOCOUNT OFF  
END  

GO

IF OBJECT_ID(N'KAAS_CP_NETOtherCaseDetailsFetchListOnly',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_NETOtherCaseDetailsFetchListOnly]
GO

CREATE PROCEDURE KAAS_CP_NETOtherCaseDetailsFetchListOnly
( 
	@FIELDNAME VARCHAR(30)
)
AS BEGIN
/*****************************************************************************                  
                  
Stored Procedure Name: KAAS_CP_NETOtherCaseDetailsFetchListOnly 
Copied From      : ky_NETOtherCaseDetailsFetchListOnly   
               
Description:  To Fetch validation on selected list only (L) is selected in UDF
              Fields.
Last Udpated: 30May2014 08:00 PM  
		      18 FEB 2015 Arun- Change NVARCHAR to VARCHAR
			  23JUN2015	Sridharen  KEYD - 2332 - Use of LTRIM(RTRIM(

* 2022-04-21	Vinodhkumar.M		Created for client portal                                          
*****************************************************************************/     
SET NOCOUNT ON
    SELECT 
        --RTRIM([FIELDNAME])		AS [FieldName],
        RTRIM([CODE])			AS [Code],
        RTRIM([DESCRIPTION])	AS [Description]
    FROM 
        UDFLookups 
    WHERE 
        [FIELDNAME] = @FIELDNAME
SET NOCOUNT OFF
END

GO




IF OBJECT_ID(N'KAAS_CP_NETOtherCaseDetailsInsert',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_NETOtherCaseDetailsInsert]
GO

CREATE PROCEDURE
       [dbo].[KAAS_CP_NETOtherCaseDetailsInsert]
      (@CaseCode        VARCHAR(200),
       @FIELDNAME       VARCHAR(200),
       @Result          INT OUTPUT)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * SP NAME : [dbo].[KAAS_CP_NETOtherCaseDetailsInsert]                                                        *
 * Copied from : [dbo].[ky_NETOtherCaseDetailsInsert]                                                        *
 *                                                                                                           *
 * To insert data for other case details main grid.                                                          *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * First compatible version:                -                                                        *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History                                                                                      *
 * 2014-??-??   ???????????       Created                                                                    *
 * 2015-02-12   Arun V.           Change NVARCHAR to VARCHAR                                                 *
 * 2015-06-23   Sridharan         KEYD-2332 - Use of LTRIM(RTRIM(                                            *
 * 2015-06-15   Pino Carafa       FIELDNAME can be up to 30 characters,                                      *
 * 2016-02-29   Pino Carafa       DateValue '' equates to 1900-01-01. Use NULL instead                       *
 * 2019-02-05   Pino Carafa       Added the Default Value                                                    *
 * 2019-02-06   Pino Carafa       Cater for longer date formats                                              *
 * 2019-02-07   Pino Carafa       A blank default date should result in a NULL Datevalue, not 01 JAN 1900    *
 * 2020-04-01   John Ginnane      KEYD-6341 - Moved the default value handling into its own function         *
 *                                ky_NETFNGetUDFDefaultValue                                                 *
 *                                                                                                           *
 * 2022-04-21   Vinodhkumar.M      Created				                                                     *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

IF NOT EXISTS
  (SELECT TOP 1 1
     FROM [dbo].[CaseUDFAnswers] CUF
    WHERE CUF.[CASECODE] = @CaseCode
      AND RTRIM(ISNULL(CUF.[UDFFILE], '')) = 'UDF:'
      AND RTRIM(ISNULL(CUF.[UDFNAME], '')) = @FIELDNAME)
  BEGIN
    DECLARE @SEQNO BIGINT

    SET @SEQNO = 0

      SELECT TOP 1
             @SEQNO = CUF.[SEQNO]
        FROM [dbo].[CaseUDFAnswers] CUF
       WHERE CUF.[CASECODE] = @CaseCode
    ORDER BY CUF.[SEQNO] DESC

    SET @SEQNO = @SEQNO + 1

    INSERT
      INTO [dbo].[CaseUDFAnswers]
          ([CASECODE],
           [UDFFILE],
           [UDFNAME],
           [SEQNO],
           [DateValue],
           [NumberValue],
           [TEXT1])
    SELECT @CaseCode,
           'UDF:',
           RTRIM(@FIELDNAME),
           @SEQNO,
           [DV].[DateValue],
           [DV].[NumberValue],
           [DV].[TEXT1]
      FROM [dbo].[KAAS_CP_NETFNGetUDFDefaultValue](@FIELDNAME) AS [DV]

    SET @Result = 1
  END
ELSE
  BEGIN
    SET @Result = 0
  END

SET NOCOUNT OFF
END

GO



IF OBJECT_ID(N'KAAS_CP_NETOtherCaseDetailsUpdate',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_NETOtherCaseDetailsUpdate]
GO


CREATE PROCEDURE
       [dbo].[KAAS_CP_NETOtherCaseDetailsUpdate]
      (@CaseCode        VARCHAR(200),
       @FILEPREFIX      VARCHAR(200),
       @FIELDNAME       VARCHAR(200),
       @Text            VARCHAR(MAX),
       @Number          DECIMAL(18,2),
       @Date            DATETIME,
       @Result          INT               OUTPUT)
AS

/*****************************************************************************************************************
 * Stored Procedure Name: [dbo].[KAAS_CP_NETOtherCaseDetailsUpdate]
 * Copied from : ky_NETOtherCaseDetailsUpdate
 * Description:  To insert data for other case details main grid.
 *
 * Modification History
 * 2015-10-14   Sridharan           RDJ-155 - Dates on UDFs
 * 2016-02-29   Pino Carafa         DateTime Values of '' are converted to 1900-01-01
 *                                   Should be Null
 * 2016-02-29    Arun				Update Text Value is empty if Number = 0.00 and Date = empty
 * 2016-09-16    Suriya             KEYD-4045-Urgent: The UDF vales for the TEXT fields are not working properly
 * 2022-04-21    Vinodhkumar.M      Created				                                                     
 ******************************************************************************************************************/
BEGIN
SET NOCOUNT ON

IF @Date = CONVERT(DATETIME, '')
  BEGIN
    SET @Date = NULL
  END
ELSE IF YEAR(@Date) < 1901
  BEGIN
    SET @Date = NULL
  END
ELSE
  BEGIN
    SET @DATE = CONVERT(DATETIME, CONVERT(VARCHAR, @Date, 112))
  END

IF RTRIM(ISNULL(@Text, '')) = ''
  BEGIN
    IF (@Number = '0.00') AND (@Date IS NULL) 
      BEGIN
        SET @Text = ''
      END
    ELSE IF (@Date IS NULL)
      BEGIN
         IF (SELECT TYPE from SystemUserDefinedFields where FILEPREFIX=@FILEPREFIX and FIELDNAME=@FIELDNAME )<> 'Text'
         BEGIN
             SET @Text = CONVERT(VARCHAR(30), @Number)
         END
      END
    ELSE
      BEGIN
        SET @Number = [dbo].[ky_NETFNConvertDateToClarion](@Date)
        SET @Text = CONVERT(VARCHAR(30), @Number)
      END
  END

IF EXISTS
  (SELECT TOP 1 1 
     FROM [dbo].[CaseUDFAnswers] CUF
    WHERE CUF.[CASECODE] = @CaseCode
      AND CUF.[UDFFILE] = @FILEPREFIX
      AND CUF.[UDFNAME] = @FIELDNAME)
  BEGIN
    UPDATE CUF
       SET CUF.[TEXT1]            = @Text,
           CUF.[NumberValue]      = @Number,
           CUF.[DateValue]        = @Date
      FROM [dbo].[CaseUDFAnswers] CUF
     WHERE CUF.[CASECODE]         = @CaseCode
       AND CUF.[UDFFILE]          = @FILEPREFIX
       AND CUF.[UDFNAME]          = @FIELDNAME
        SET @Result = 1
  END
ELSE
  BEGIN
    SET @Result = 0
  END

SET NOCOUNT OFF
END

GO

IF OBJECT_ID(N'KAAS_CP_OtherCaseDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_OtherCaseDetails]
GO

CREATE PROCEDURE 
	 [dbo].[KAAS_CP_OtherCaseDetails]            
     (@CaseCode          VARCHAR(20),
	  @PageNumber         INT           = NULL, 
      @PageSize           INT           = NULL,
      @SearchText         VARCHAR(400)  = NULL, 
      @SortColumn         VARCHAR(50)   = NULL,
      @SortDirection      VARCHAR(10)   = NULL)
            
AS            
/*******************************************************************************************************
* To FETCH data for other case details main grid.													   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_OtherCaseDetails]											   *
* Copied from			: [dbo].[KAAS_OtherCaseDetailsFetchMainGrid]								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
* 2019-08-23    Dheepin Vijith K  Modified - Default sorting changed to DESC to show the latest values *
*											on the top of the grid first							   *
* 2021-06-22    Aakif			  List only published UDF data                                         *
 *******************************************************************************************************/
BEGIN           
 SET NOCOUNT ON

    DECLARE @StartRow INT;
    DECLARE @EndRow INT;
    
    SET @PageNumber = ISNULL(@PageNumber, 0) - 1; --  0 BASED INDEX
    
    IF(@PageNumber > -1)
    BEGIN
    	SET @StartRow = ((@PageNumber) * @PageSize) + 1;
    	SET @EndRow = (@StartRow + @PageSize) - 1;
    END
    

    IF(RTRIM(ISNULL(@SearchText, '')) = '' OR RTRIM(@SearchText) = '')
    BEGIN
    	SET @SearchText = ''
    END
    
	IF(ISNULL(@SortColumn, '') = '' OR RTRIM(LTRIM(@SortColumn)) = '')
	BEGIN
		SET @SortColumn = 'SeqNo'
	END

    IF(ISNULL(@SortDirection, '') = '' OR RTRIM(LTRIM(@SortDirection)) = '')
	BEGIN
		SET @SortDirection = 'DESC'
	END

	SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#OtherCaseDetailTable
	FROM
	(SELECT RTRIM(ISNULL(UDFCategory.UDFCategory,'')) AS GroupName,
		   RTRIM( SystemUserDefinedFields.PROMPT) AS Detail,          
		   CONVERT(DATETIME, RTRIM(CaseUDFAnswers.DateValue), 23) AS DateValue,
		   --ISNULL(CONVERT(VARCHAR,CaseUDFAnswers.DateValue,23),'') AS  DateValue,
		            
		   CASE RTRIM(SystemUserDefinedFields.[VALIDATION]) 
			  WHEN 'L' 
				THEN CONVERT(VARCHAR(MAX),RTRIM(ISNULL(CaseUDFAnswers.TEXT1,'')))+' - ' +  
			  	(SELECT RTRIM(ISNULL(UDFLookups.[DESCRIPTION],'')) 
				   FROM UDFLookups 
				  WHERE SystemUserDefinedFields.FIELDNAME = UDFLookups.FIELDNAME 
						AND CONVERT(VARCHAR(MAX),CaseUDFAnswers.TEXT1) = UDFLookups.CODE)        
			  WHEN 'R' 
				THEN CONVERT(VARCHAR(200),RTRIM(ISNULL(CaseUDFAnswers.TEXT1,'')))  
			  WHEN 'T' 
				THEN CONVERT(VARCHAR(200),RTRIM(ISNULL(CaseUDFAnswers.TEXT1,'')))  
			  ELSE   
				CASE RTRIM(SystemUserDefinedFields.[TYPE]) 
					WHEN 'Text' 
						THEN (CASE 
								WHEN CONVERT(VARCHAR(200),RTRIM(ISNULL(CaseUDFAnswers.TEXT1,'')))='' 
									THEN '' 
								ELSE  CONVERT(VARCHAR(200),RTRIM(ISNULL(CaseUDFAnswers.TEXT1,'')))  
							  END)      
					WHEN 'Numeric' 
						THEN 
							--(CASE 
							--	WHEN SystemUserDefinedFields.DECMIAL=0 THEN  CONVERT(VARCHAR(20),CONVERT(DECIMAL(18,0),CaseUDFAnswers.NumberValue) )
							--	WHEN SystemUserDefinedFields.DECMIAL=1 THEN  CONVERT(VARCHAR(20),CONVERT(DECIMAL(18,1),CaseUDFAnswers.NumberValue) )
							--	WHEN SystemUserDefinedFields.DECMIAL=2 THEN  CONVERT(VARCHAR(20),CONVERT(DECIMAL(18,2),CaseUDFAnswers.NumberValue) )
							--END)
							CONVERT(VARCHAR(20),CAST(CaseUDFAnswers.NumberValue AS MONEY ),1)
					 WHEN 'Date' 
						THEN
							 CASE 
								WHEN CONVERT(VARCHAR(20), CaseUDFAnswers.DateValue, 23) = '1900-01-01' 
									THEN '' 
								--ELSE CONVERT(VARCHAR(20), CaseUDFAnswers.DateValue, 23) 
								ELSE CONVERT(VARCHAR(20), CaseUDFAnswers.DateValue, 106) 
							 END  
					 ELSE CONVERT(VARCHAR(200),RTRIM(ISNULL(CaseUDFAnswers.TEXT1,'')))        
				END  
			END AS Value    
		, RTRIM(ISNULL(CaseUDFAnswers.NumberValue,0))			AS NumberValue    
		, RTRIM(ISNULL(CaseUDFAnswers.TEXT1,''))				AS [Text1]
		, RTRIM(SystemUserDefinedFields.TYPE)					AS [Type]    
		, RTRIM(ISNULL(CaseUDFAnswers.SEQNO,0))					AS [SeqNo]    
		, RTRIM(SystemUserDefinedFields.FILEPREFIX)				AS [FilePrefix]    
		, RTRIM(SystemUserDefinedFields.FIELDNAME)				AS [FieldName]    
		, RTRIM(ISNULL(SystemUserDefinedFields.UDFCategory,0))	AS  UDFCategory      
		, CASE WHEN RTRIM(ISNULL(CaseUDFAnswers.ForCopy,0)) = '1' THEN 'True' ELSE 'False' END AS  ForCopy  
		, SystemUserDefinedFields.DECMIAL						AS [Decimal]
		, SystemUserDefinedFields.LENGTH						AS [Length]
	FROM CaseUDFAnswers 
		 INNER JOIN SystemUserDefinedFields 
		 ON CaseUDFAnswers.UDFFILE = SystemUserDefinedFields.FILEPREFIX 
		 AND CaseUDFAnswers.UDFNAME = SystemUserDefinedFields.FIELDNAME 
		 LEFT OUTER JOIN UDFCategory 
		 ON SystemUserDefinedFields.UDFCategory = UDFCategory.ID     
   WHERE
   (
   ISNULL(@SearchText, '') = '' OR RTRIM(LTRIM(@SearchText)) = ''
   OR
   (
   [UDFCategory].[UDFCategory] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[PROMPT] LIKE '%' + @SearchText + '%'
   OR
   [CaseUDFAnswers].[DateValue] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[VALIDATION] LIKE '%' + @SearchText + '%'
   OR
   [CaseUDFAnswers].[TEXT1] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[TYPE] LIKE '%' + @SearchText + '%'
   OR
   [CaseUDFAnswers].[NumberValue] LIKE '%' + @SearchText + '%'
   OR
   [CaseUDFAnswers].[SEQNO] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[FILEPREFIX] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[FIELDNAME] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[UDFCategory] LIKE '%' + @SearchText + '%'
   OR
   [CaseUDFAnswers].[ForCopy] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[DECMIAL] LIKE '%' + @SearchText + '%'
   OR
   [SystemUserDefinedFields].[LENGTH] LIKE '%' + @SearchText + '%'
   )
   )
   AND 
   SystemUserDefinedFields.PUBLISH = 1
   AND
   (RTRIM(CaseUDFAnswers.CASECODE) = RTRIM(@CaseCode)))
   AS FoundTable     
   ORDER BY 
   CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'SeqNo'   THEN CAST([SeqNo] AS INT)
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'SeqNo'   THEN CAST([SeqNo] AS INT)
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'GroupName' THEN [GroupName]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'GroupName'   THEN [GroupName]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Detail'   THEN [Detail]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Detail'   THEN [Detail]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'DateValue'   THEN [DateValue]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'DateValue'   THEN [DateValue]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Value'   THEN [Value]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Value'   THEN [Value]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'NumberValue'   THEN [NumberValue]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'NumberValue'   THEN [NumberValue]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Text1'   THEN [Text1]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Text1'   THEN [Text1]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Type'   THEN [Type]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Type'   THEN [Type]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'FilePrefix'   THEN [FilePrefix]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'FilePrefix'   THEN [FilePrefix]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'FieldName'   THEN [FieldName]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'FieldName'   THEN [FieldName]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'UDFCategory'   THEN [UDFCategory]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'UDFCategory'   THEN [UDFCategory]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'ForCopy'   THEN [ForCopy]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'ForCopy'   THEN [ForCopy]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Decimal'   THEN [Decimal]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Decimal'   THEN [Decimal]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Length'   THEN [Length]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Length'   THEN [Length]
	  	  END
	  END DESC

	SELECT
		*
	FROM
		#OtherCaseDetailTable
	WHERE
	(
		@StartRow IS NULL
		OR
		(
			[Row_Number] BETWEEN @StartRow AND @EndRow		
		)
	)

	SELECT
		(COUNT([Row_Number])) AS TotalRecords
	FROM
        #OtherCaseDetailTable
SET NOCOUNT OFF
END

GO

IF OBJECT_ID(N'KAAS_CP_RegisterNewUser',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_RegisterNewUser]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_RegisterNewUser]
    (@EmailId               VARCHAR(200),
	 @IsTwoFactorEnabled    BIT = 0,
	 @EmailActivationToken  NVARCHAR(252) = NULL,
	 @TokenCreationTime     DATETIME = NULL,
	 @TokenExpirationTime   DATETIME = NULL,
	 @IsResendMail			BIT		 = 0,
	 @ClientName			VARCHAR(256) = NULL,
	 @PhoneNo				VARCHAR(50)  = NULL)

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_RegisterNewUser] 											   *
* Description: To register new user in Client Portal												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-07    Aakif        Created                                                                   *
* 2021-06-28    Aakif        Included condition to resend account activation mail					   *
 *******************************************************************************************************/

BEGIN

-- Update OTP with its expiry time

IF(@IsResendMail = 0)
BEGIN
	INSERT INTO
		[dbo].[ClientLogin]
		(
		[Email],
		[IsActiveLogin],
		[IsTwoFactorEnabled],
		[EmailActivationToken],
		[EmailActivationTokenCreatedTime],
		[EmailActivationTokenExpirationTime]
		)
	VALUES
	(
	 @EmailId,
	 0,
	 @IsTwoFactorEnabled,
	 @EmailActivationToken,
	 @TokenCreationTime,
	 @TokenExpirationTime
	)

END

ELSE
BEGIN
	UPDATE [dbo].[ClientLogin]
	SET
		[EmailActivationToken]				 = @EmailActivationToken,
		[EmailActivationTokenCreatedTime]	 = @TokenCreationTime,
		[EmailActivationTokenExpirationTime] = @TokenExpirationTime
	WHERE
		[Email] = @EmailId
END

-- Check if name and phone number is availabe and update user data
IF (ISNULL(@ClientName, '') != '')
BEGIN
	UPDATE [dbo].[ClientLogin]
	SET
		[Name] = @ClientName
	WHERE
		[Email] = @EmailId
END

IF (ISNULL(@PhoneNo, '') != '')
BEGIN
	UPDATE [dbo].[ClientLogin]
	SET
		[PhoneNumber] = @PhoneNo
	WHERE
		[Email] = @EmailId
END


END

GO


IF OBJECT_ID(N'KAAS_CP_ReportGeneration',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KAAS_CP_ReportGeneration]
GO
CREATE PROCEDURE
       [dbo].[KAAS_CP_ReportGeneration]      
		(@FromDate VARCHAR(50),
		 @ToDate   VARCHAR(50),
		 @LoginId  BIGINT)       
      
AS        
/*******************************************************************************************************
* This procedure is used to Generate Case Associate code.				  							   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_ReportGeneration]									           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2022-04-28	Vinodhkumar.M		Created for client portal report                                   *
* 2022-07-20	Vinodhkumar.M		Modified - added Client Name	                                   *
* 2024-07-11	Aakif				Modified - Included publish filters for CaseContacts               *
 *******************************************************************************************************/
BEGIN	

	DECLARE @FormatedToDate DATETIME = DATEADD(MINUTE,59,DATEADD(hh,23,CAST(@ToDate AS DATETIME)));
	
	SELECT DISTINCT
				Row_Number() 
				OVER ( ORDER BY  
				MAT.[Started] DESC)     					AS  [UniqueId],
				MAT.USER1									AS	[RateNo],
				MAT.ORIGINALDEBT							AS	[OriginalDebt],
				CASEASSOCIATE.NAME							AS	[Name],
				CASEASSOCIATE.ADDRESS						AS	[Address],
				CASEASSOCIATE.LEGALNAME						AS	[LegalName],
				CASEASSOCIATE.LEGALADDRESS					AS  [LegalAddress],
				MAT.COMMENT									AS  [Comment],
				MAT.[Started]						 	    AS	[Started],
				ISNULL(CL.CLNAME,'')					    AS  [ClientName]
		FROM  [DBO].KAAS_CP_TFGetMatterCodeForClient(@LoginId) LOGINACCESS
  INNER JOIN [DBO].[MATTERS] MAT 
		  ON LOGINACCESS.MatterCode = MAT.CODE
  INNER JOIN [DBO].[Client] CL
		  ON MAT.ClientCode = CL.CLCODE 
  INNER JOIN [DBO].[CASECONTACTS] CSC
		  ON MAT.CODE = (SELECT TOP 1 CSC.CASECODE )
  INNER JOIN [DBO].[CASEASSOCIATESNAMES] CASEASSOCIATE
		  ON  CASEASSOCIATE.CODE = CSC.NAMECODE
	   WHERE ISNULL([CSC].PUBLISH, '') = 'Y'
		 AND MAT.[Started] 
	 BETWEEN @FromDate 
		 AND @FormatedToDate

END   
GO



IF OBJECT_ID(N'KAAS_CP_RevokeClientAccessForCode',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_RevokeClientAccessForCode]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_RevokeClientAccessForCode]
    (@LoginId       BIGINT,
	 @ClientCode	VARCHAR(20)
	 )

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_RevokeClientAccessForCode]									   *
* Description: To revoke users access for client codein Client Portal								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-28    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN
	
	DELETE FROM
		[ClientLoginAccess]
	WHERE
		ClientLoginId = @LoginId
		AND ContactCode	  = @ClientCode

END

GO

IF NOT((SELECT SERVERPROPERTY('Edition') AS	[Edition]) = 'SQL Azure')
BEGIN
	IF EXISTS
		(SELECT TOP 1 1
		 FROM SYS.[objects] SO
		 WHERE SO.[name] = N'KAAS_CP_SaveUploadDiaryAttachment'
		 AND SO.[type] = 'P')
	BEGIN
		DROP PROCEDURE [dbo].[KAAS_CP_SaveUploadDiaryAttachment]
	END

	DECLARE @NCOMMAND NVARCHAR(MAX)
	
	SET @NCOMMAND = 
	N'CREATE PROCEDURE [dbo].[KAAS_CP_SaveUploadDiaryAttachment] (
		@FilePath	VARCHAR(1000),
		@FileName	VARCHAR(1000),
		@FileData	VARBINARY(MAX),
		@Result		INT		OUTPUT
	   )
	AS
	/*******************************************************************************************************
	* To save the attachment to the physical path                                                          *
	*                                                                                                      *
	* Stored Procedure Name	: [dbo].[KAAS_CP_SaveUploadDiaryAttachment]                                    *
	* Copied from			: [dbo].[KAAS_SaveDiaryAttachement]                                            *
	*                                                                                                      *
	* Modification History	:                                                                              *
	* 2019-04-12	Vinodhan K		Created                                                                *
	* 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                          *
	 *******************************************************************************************************/
	BEGIN
		DECLARE @FullPath NVARCHAR (2000);
		SET @FullPath = @FilePath + @FileName;

		DECLARE @Obj INT;
 
		SET NOCOUNT ON

		BEGIN TRY
			DECLARE @IsFolderExist AS INT
 
			DECLARE @FileResult TABLE
			(
				IsFileExist				INT,
				IsFileDirectory			INT,
				IsParentDirectoryExist	INT
			)
 
			INSERT INTO
				@FileResult
				(
				IsFileExist,
				IsFileDirectory,
				IsParentDirectoryExist
				)
			EXECUTE XP_FILEEXIST @FilePath
     
			SELECT
				@IsFolderExist = IsFileDirectory
			FROM
				@FileResult
     
			--Script to create directory       
			IF(@IsFolderExist = 0)
				BEGIN
					EXECUTE XP_CREATE_SUBDIR @FilePath

					INSERT INTO
						@FileResult
						(
						IsFileExist,
						IsFileDirectory,
						IsParentDirectoryExist
						)
					EXECUTE XP_FILEEXIST @FilePath

					SELECT
						@IsFolderExist = IsFileDirectory
					FROM
						@FileResult
				END


			IF(@IsFolderExist = 1)
				BEGIN
					EXEC SP_OACREATE		''ADODB.Stream'' ,@Obj OUTPUT;
					EXEC SP_OASETPROPERTY	@Obj ,''Type'',1;
					EXEC SP_OAMETHOD		@Obj,''Open'';
					EXEC SP_OAMETHOD		@Obj,''Write'', NULL, @FileData;
					EXEC SP_OAMETHOD		@Obj,''SaveToFile'', NULL, @FullPath, 2;
					EXEC SP_OAMETHOD		@Obj,''Close'';
					EXEC SP_OADESTROY		@Obj;
					SELECT @Result = 1;
					RETURN;
				END
			ELSE
				BEGIN
				SELECT @Result = 0;
					RETURN;
				END
		END TRY
    
		BEGIN CATCH
			EXEC SP_OADESTROY @Obj;
			SELECT @Result = 1;
			RETURN;
		END CATCH
 
	   SET NOCOUNT OFF
	END'

	EXECUTE SP_EXECUTESQL @NCOMMAND
END
GO
IF OBJECT_ID(N'KAAS_CP_UnlockOrToggleIsActive',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UnlockOrToggleIsActive]
GO

CREATE PROCEDURE 
	  [dbo].[KAAS_CP_UnlockOrToggleIsActive]
	 (@LoginId			BIGINT,
	  @ToggleIsActive	BIT,
	  @IsActive			BIT = 0)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UnlockOrToggleIsActive]									   *
* Description: To unlock a user or toggle IsActive													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-07    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN
-- UNLOCK A USER

	IF(@ToggleIsActive = 0)
	BEGIN
		UPDATE [dbo].[ClientLogin]
		SET 
		    [NoOfAttempt]		   = 0,
		    [LockedOutEndDate]     = NULL,
		    [IsActiveLogin]        = 1
		WHERE 
			[ClientLoginId] = @LoginId
	END

	-- TOGGLE ISACTIVE FLAG FOR USER
	ELSE IF(@ToggleIsActive = 1)
	BEGIN
		UPDATE [dbo].[ClientLogin]
		SET 
		    [IsActiveLogin] = @IsActive
		WHERE 
			[ClientLoginId] = @LoginId
	END

END

GO

IF OBJECT_ID(N'KAAS_CP_UpdateAccessCodeForUser',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdateAccessCodeForUser]
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_CP_UpdateAccessCodeForUser]
	(@EmailId            VARCHAR(200),
	 @AccessCode		  VARCHAR(50)  = NULL,
	 @AccessCodeStatus   VARCHAR(200) = NULL,
	 @OffSetForOtpExpiry TINYINT      = 10)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdateAccessCodeForUser] 									   *
* Description: To store Access Code and OTP Expirty time for user									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-31    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN
	DECLARE @CurrentDateTime DATETIME = GETUTCDATE();

-- Update OTP with its expiry time
	UPDATE [dbo].[ClientLogin]
		SET 
			[AccessCode]				   = @AccessCode,
		    [AccessCodeStatus]			   = @AccessCodeStatus,
		    [OTPAccessTokenCreationTime]   = @CurrentDateTime,
		    [OTPAccessTokenExpirationTime] = DATEADD(MINUTE, @OffSetForOtpExpiry, @CurrentDateTime)
		WHERE 
			[Email] = @EmailId
END

GO
IF OBJECT_ID(N'KAAS_CP_UpdateClientAccess',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdateClientAccess]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_UpdateClientAccess]
    (@EmailId       VARCHAR(200),
	 @HandlerCode	VARCHAR(10),
	 @ContactCode	VARCHAR(25),
	 @MatterCode	VARCHAR(25) = NULL,
	 @Result		BIT OUTPUT)

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdateClientAccess] 										   *
* Description: To add accesss to clients for a code													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-25    Aakif        Created                                                                   *
* 2021-06-29    Aakif        Included out paramter to denote if client code is already added for user  *
 *******************************************************************************************************/

BEGIN

-- CLIENT ACCESS LOGIN TO CONTACT CODES

	DECLARE @ClientId BIGINT = 0;
	DECLARE @IsNewEntry BIT = 0;

	SELECT 
		@ClientId = ClientLoginId
	FROM
		[ClientLogin]
	WHERE
		Email = @EmailId

	-- INSERT TO CLIENT LOGIN ACCESS
	IF NOT EXISTS (SELECT 1 FROM ClientLoginAccess WHERE ClientLoginId = @ClientId AND ContactCode = @ContactCode)
	BEGIN
		INSERT INTO [ClientLoginAccess]
		(
		 ClientLoginId,
		 ContactCode,
		 MatterCode,
		 HasAccessToAllMatter,
		 PublishedHandlerCode,
		 PublishedDateTime
		)
		VALUES
		(
		 @ClientId,
		 @ContactCode,
		 @MatterCode,
		 'Y',
		 @HandlerCode,
		 GETUTCDATE()
		)

		SELECT @Result = 1
	END

	ELSE
	BEGIN
		SELECT @Result = 0
	END

END

GO

IF OBJECT_ID(N'KAAS_CP_UpdateIncorrectLoginAttempt',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdateIncorrectLoginAttempt]
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_CP_UpdateIncorrectLoginAttempt]
	(@EmailId VARCHAR(200),
	 @Result  INT = 0 OUTPUT)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdateIncorrectLoginAttempt]								   *
* Description: To update lockout date and number of attempts for user								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-01    Aakif        Created																   *
 *******************************************************************************************************/

BEGIN
	DECLARE @CurrentLoginAttempt TINYINT;
	DECLARE @MaxLockoutAttemp INT, @LockoutTimeoutLimit INT;

--GET current incorrect login attempt count
	SELECT 
	  @CurrentLoginAttempt   = ISNULL(NoOfAttempt,0) 
	FROM 
	  [dbo].[ClientLogin]
	WHERE 
	  [Email] = @EmailId

-- GET Max attempt and lockout duration from setting
	SELECT 
		@MaxLockoutAttemp    = ISNULL(IsLockOut_Attempt, 3),
		@LockoutTimeoutLimit = ISNULL(LockoutDurationInMins, 10)
	FROM 
		[dbo].[ClientPortalSetting]

-- Step 1: Update current attempt at login
	UPDATE [dbo].[ClientLogin]
	  SET 
		[NoOfAttempt] = (@CurrentLoginAttempt + 1)
	  WHERE 
		[Email] = @EmailId

-- Step 2: Check if current attempt exceeds limit and update lockedout date
IF(@MaxLockoutAttemp <= (@CurrentLoginAttempt + 1 ))
	BEGIN
	    UPDATE [dbo].[ClientLogin]
		  SET 
			[LockedOutEndDate] = DATEADD(MINUTE, @LockoutTimeoutLimit, GETUTCDATE())
		  WHERE 
			[Email] = @EmailId
			
		SET @Result = @LockoutTimeoutLimit

	END
END

GO

IF OBJECT_ID(N'KAAS_CP_UpdateLastLoginData',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdateLastLoginData]
GO
CREATE PROCEDURE 
	  [dbo].[KAAS_CP_UpdateLastLoginData]
	 (@EmailId     VARCHAR(200),
	  @LoginId     BIGINT,
	  @DeviceInfo  NVARCHAR(20)   = NULL,
	  @BrowserInfo NVARCHAR(20)   = NULL,
	  @IPAddress   NVARCHAR(30)   = NULL)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdateLastAccessDate] 										   *
* Description: To update last accessed datetime for user											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-27    Aakif        Created                                                                   *
* 2021-06-31    Aakif        Reset LockedoutEndDate after successful login							   *
 *******************************************************************************************************/

BEGIN
-- Step 1: Update last login access date
	UPDATE [dbo].[ClientLogin]
		SET [LastAccessedDateTime] = GETUTCDATE(),
		    [NoOfAttempt]		   = 0,
		    [LockedOutEndDate]     = NULL,
		    [IsFirstlogin]         = 0,
		    [IsActiveLogin]        = 1
		WHERE 
			[Email] = @EmailId

-- Step 2: Add user login history
	INSERT INTO 
	    [dbo].[ClientPortalLogonInfo]
		([ClientLoginId]
		,[LastAccessedDateTime]
		,[DeviceInfo]
		,[Browser]
		,[IPAddress])
	VALUES
		(@LoginId
		,GETUTCDATE()
		,@DeviceInfo
		,@BrowserInfo
		,@IPAddress)
END

GO






IF OBJECT_ID(N'KAAS_CP_UpdatePasswordHash',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdatePasswordHash]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_UpdatePasswordHash]
    (@LoginId         BIGINT,
	 @NewPasswordHash NVARCHAR(512))

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdatePasswordHash] 										   *
* Description: To update password hash after the reset is successful								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-02    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN

-- Update password hash after password is reset
UPDATE [dbo].[ClientLogin]
	SET
		[PasswordHash]				  = @NewPasswordHash,
		[PasswordResetLockOutEndDate] = NULL
	WHERE [ClientLoginId] = @LoginId


END

GO
IF OBJECT_ID(N'KAAS_CP_UpdatePortalSetting',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdatePortalSetting]
GO
CREATE PROCEDURE
	[dbo].[KAAS_CP_UpdatePortalSetting]
	(@IsTwoFactor		 BIT,
	 @LockoutCount		 INT,
	 @LockoutDuration	 INT,
	 @PasswordNotifyMode TINYINT = 0,
	 @UpeKey			 VARCHAR(200) = NULL,
	 @IsKeyUpdated		 BIT = 0,
	 @TenantLogo		 IMAGE = NULL,
	 @LogoType			 VARCHAR(15) = NULL)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdatePortalSetting]  										   *
* Description: To get settings for client portal													   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-29    Aakif        Created																   *
* 2021-07-01    Aakif        Included option to modify tenant Logo									   *
 *******************************************************************************************************/

BEGIN

	IF (@IsKeyUpdated = 1)
	BEGIN
		UPDATE [ClientPortalSetting]
		SET
			[IsTwoFactorEnabled]		= @IsTwoFactor,
			[IsLockOut_Attempt]			= @LockoutCount,
			[LockoutDurationInMins]		= @LockoutDuration,
			[PasswordResetNotification] = @PasswordNotifyMode
	END
	ELSE
	BEGIN
		INSERT INTO
			[dbo].[ClientPortalSetting]
			(
			[UPEKey],
			[IsTwoFactorEnabled],
			[IsLockOut_Attempt],
			[LockoutDurationInMins],
			[PasswordResetNotification]
			)
		VALUES
			(
			 @UpeKey,
			 @IsTwoFactor,
			 @LockoutCount,
			 @LockoutDuration,
			 @PasswordNotifyMode
			)
	END

	IF(ISNULL(@LogoType, '') <> '')
	BEGIN
		UPDATE [ClientPortalSetting]
		SET 
		[TenantLogoType] = @LogoType,
		[TenantLogo] = @TenantLogo	
	END


END

GO

IF OBJECT_ID(N'KAAS_CP_UpdateResetPasswordCode',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdateResetPasswordCode]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_UpdateResetPasswordCode]
    (@LoginId            BIGINT,
	 @ResetPasswordCode  VARCHAR(10),
	 @CodeCreationTime   DATETIME = NULL,
	 @CodeExpirationTime DATETIME = NULL)

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdateResetPasswordCode] 									   *
* Description: To store Reset password OTP Expirty time for user									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-02    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN

-- Update OTP with its expiry time
UPDATE [dbo].[ClientLogin]
	SET
		[IsPasswordResetOTPVerified]	 = 0,
		[PasswordResetOtp]               = @ResetPasswordCode,
		[PasswordResetOtpcreationTime]   = @CodeCreationTime,
		[PasswordResetOtpexpirationTime] = @CodeExpirationTime
	WHERE [ClientLoginId] = @LoginId

END

GO
IF OBJECT_ID(N'KAAS_CP_UpdateUserPhoneNumber',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_UpdateUserPhoneNumber]
GO

CREATE PROCEDURE 
	  [dbo].[KAAS_CP_UpdateUserPhoneNumber]
	 (@PhoneNo		VARCHAR(50),
	  @LoginId		BIGINT,
	  @HandlerCode  VARCHAR(10))
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_UpdateUserPhoneNumber] 									   *
* Description: To update user phone number and log who updated it									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-30    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN
-- Step 1: Update user data
	UPDATE [dbo].[ClientLogin]
		SET 
			[PhoneNumber] = @PhoneNo
		WHERE 
			[ClientLoginId] = @LoginId

-- Step 2: Add modification history for user
	INSERT INTO 
	    [dbo].[ClientPortalPhoneNoUpdateLog]
		(
		 [ClientLoginId],
		 [UpdatedByHandler],
		 [UpdateDateTime]
		 )
	VALUES
		(
		 @LoginId,
		 @HandlerCode,
		 GETUTCDATE()
		 )
END

GO

IF EXISTS (SELECT TOP 1 1 FROM SYS.[objects] SO WHERE SO.[name] = 'KAAS_CP_UploadDiaryAttachment' AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_CP_UploadDiaryAttachment]
  END
GO

CREATE PROCEDURE 
       [dbo].[KAAS_CP_UploadDiaryAttachment]
      (@DIARYID            INT,
       @TRACKREFERENCE     INT,
       @CASECODE           VARCHAR(20),
       @NAME               VARCHAR(10),
       @DOCUMENT           VARCHAR(100),
       @FILEPATH           VARCHAR(255),
       @TYPE               VARCHAR(5),
       @DOCCLASS           VARCHAR(3),
       @DATEENTERED        DATETIME,
       @ENTEREDBY          VARCHAR(8),
       @LASTACCESSDATE     DATETIME,
       @LASTACCESSBY       VARCHAR(8),
       @SYSTEM             VARCHAR(1),
       @DICTATIONFILE      VARCHAR(255),
       @Source             VARCHAR(20),
       @Fees               INT,
       @Outlay             INT,
	   @DefaultActionCode  VARCHAR(15) = '',
	   @Subject            VARCHAR(500) ='',
	   @FileDescription    VARCHAR(MAX) ='',
	   @IslastFileToUpload BIT,
       @Result             VARCHAR(255) OUTPUT)    
AS
/*******************************************************************************************************
* This stored procedure is used to insert or update the Client Case Action                             *
* Attachment information.IF ID is already exist then it will update that record. otherwise             *
* new record will insert.                                                                              *    
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_CP_UploadDiaryAttachment]                                        *
* Copied from			: [dbo].[ky_NETAAInsertDiaryAttchement]                                        *
* Copied from			: [dbo].[KAAS_InsertDiaryAttachment]                                           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-10	Vinodhan K		Created                                                                *
* 2020-05-26    Arun V          Modified the type extenaion size from 3 to 5                           *
* 2021-10-06    Arun V          Set Context info                                                       *
* 2022-02-10	Vinodhkumar.M   Created - to upload Document in client portal                          *
* 2022-02-11	Vinodhkumar.M   KAAS_CP_GETFILEPATH is created by copying Function KAAS_FN_GETFILEPATH *
* 2022-02-11	Vinodhkumar.M   Subject,text1, action code and handled date and due date is added 
								and removed client portal flag		                 			       *
* 2022-02-17	Vinodhkumar.M   default action code, subject, file description parameters range updated*
* 2022-11-03	Vinodhkumar.M   IslastFileToUpload Parameter is added for diary table update		   *
							    query should call only once											   *
 *******************************************************************************************************/
BEGIN

	SET NOCOUNT OFF


	DECLARE @HandlerBin VARBINARY(128)
	SET @HandlerBin = CONVERT(VARBINARY(128), convert(varchar(8),@LASTACCESSBY))
	SET CONTEXT_INFO @HandlerBin


	IF NOT EXISTS
	(SELECT 1 
		FROM [dbo].[DiaryAttachments] DAT
		WHERE DAT.[TRACKREFERENCE] = @TRACKREFERENCE) 
	BEGIN
	SET @FILEPATH = dbo.KAAS_CP_GETFILEPATH (SUBSTRING(@FILEPATH,LEN(@FILEPATH)-CHARINDEX ('\',REVERSE(@FILEPATH))+2,LEN(@FILEPATH)) ,@FILEPATH )  
	IF NOT(@FILEPATH = 'NOCHANGE')  
		BEGIN
		INSERT 
		INTO [dbo].[DiaryAttachments]
			([DIARYID],
				[TRACKREFERENCE],
				[CASECODE],
				[NAME],
				[DOCUMENT],
				[FILEPATH],
				[TYPE],
				[DOCCLASS],
				[DATEENTERED],
				[ENTEREDBY],
				[LASTACCESSDATE],
				[LASTACCESSBY],
				[SYSTEM],
				[DICTATIONFILE],
				[Source],
				[Fees],
				[Outlay])
		VALUES(@DIARYID,
				@TRACKREFERENCE,
				@CASECODE,
				@NAME,
				@DOCUMENT,
				@FILEPATH,
				@TYPE,
				@DOCCLASS,
				@DATEENTERED,
				@ENTEREDBY,
				@LASTACCESSDATE,
				@LASTACCESSBY,
				@SYSTEM,
				@DICTATIONFILE,
				@Source,
				@Fees,
				@Outlay)
               
			IF(@IslastFileToUpload = 1)
			BEGIN
				IF EXISTS(SELECT TOP 1 1 FROM diary WHERE ACTIONID = @DIARYID)
				 BEGIN
					UPDATE [diary]
					   SET [SUBJECT]    = @Subject,
						   [TEXT1]		= @FileDescription,
						   [ACTIONCODE] = @DefaultActionCode,
						   [DATE]       = dbo.KAAS_FNConvertDateToUTC(GETDATE(),@ENTEREDBY),
						   [DUEDATE]    = dbo.KAAS_FNConvertDateToUTC(GETDATE(),@ENTEREDBY)
					 WHERE [ACTIONID]   = @DIARYID
				 END
			END

			SET @Result = @FILEPATH 
		END
		ELSE  
		BEGIN  
			SET @Result = 'NOCHANGE'  
		END  
	END 

END
GO
IF OBJECT_ID(N'KAAS_CP_ValidateResetPassword',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CP_ValidateResetPassword]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_CP_ValidateResetPassword]
    (@LoginId		  BIGINT,
	 @IsOtpValid	  BIT,
	 @IsPasswordReset BIT = 0)

AS

/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CP_ValidateResetPassword] 									   *
* Description: To validate Reset password OTP and lockout user if invalid credentails provided		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-03    Aakif        Created                                                                   *
 *******************************************************************************************************/

BEGIN

DECLARE @CurrentAttempt TINYINT, @LockoutLimit TINYINT, @LockoutDuration INT;

--HANDLE FOR VALID RESET PWD OTP
IF(@IsOtpValid = 1)
BEGIN
	UPDATE [dbo].[ClientLogin]
		SET
			[IsPasswordResetOTPVerified] = 1
		WHERE [ClientLoginId] = @LoginId

END

ELSE
BEGIN
	
	--GET CURRENT ATTEMPT COUNT TO DECIDE WHETHER TO LOCKOUT USER
	SELECT 
		@CurrentAttempt = ISNULL(PasswordResetOTPAttemptCount, 0)
	FROM 
		[dbo].[ClientLogin]

	-- SET LOCKOUT TENANT SETTINGS
	SELECT
		@LockoutLimit	 = ISNULL(IsLockOut_Attempt, 3),
		@LockoutDuration = ISNULL(LockoutDurationInMins, 10)
	FROM
		[dbo].[ClientPortalSetting]

	-- LOCKOUT USER FOR MAX LIMIT REACHED
	IF(@CurrentAttempt >= @LockoutLimit)
	BEGIN
		UPDATE [dbo].[ClientLogin]
			SET
				[PasswordResetLockOutEndDate] = DATEADD(MINUTE, @LockoutDuration, GETUTCDATE())
			WHERE [ClientLoginId] = @LoginId
	END

	--INCREMENT CURRENT ATTEMPT COUNT
	UPDATE [dbo].[ClientLogin]
		SET
			[PasswordResetOTPAttemptCount] = (@CurrentAttempt + 1)
		WHERE [ClientLoginId] = @LoginId
END


--RESET ALL DATA AFTER PASSWORD IS RESET
IF(@IsPasswordReset = 1)
BEGIN
	UPDATE [dbo].[ClientLogin]
		SET
			[PasswordResetOTPAttemptCount]	 = 0,
			[IsPasswordResetOTPVerified]	 = 0,
			[PasswordResetLockOutEndDate]	 = NULL,
			[PasswordResetOTP]				 = NULL,
			[PasswordResetOTPCreationTime]	 = NULL,
			[PasswordResetOTPExpirationTime] = NULL
		WHERE [ClientLoginId] = @LoginId

END

END

GO
