IF [dbo].[ISSAM4]() = 0
BEGIN
    EXEC ('
IF OBJECT_ID(N''KEYHM_BGDelete'', N''P'') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_BGDelete]
END')

    EXEC ('
CREATE PROCEDURE [dbo].[KEYHM_BGDelete] (
       @DraftNo int,
       @BatchNo int)
AS
/*****************************************************************************
 *																			 *
 * Deletes a the billing guide for specified bill							 *
 * SP only suitable for SAM3												 *
 *																			 *
 * Stored Procedure name : KEYHM_BGDelete									 *
 * Copied From           : ky_BGDelete										 *
 *																			 *
 * ????-??-??   ????           Created										 *
 * 2018-08-23   John Ginnane   Added to SVN									 *
 * 2020-05-02   Vinodhan       Created KAAS_BGDelete						 *
 *			
 * Modification History	:                                                                              *
 * 2020-03-13	Rajesh P	from  ky_BGDelete
 *****************************************************************************/   
BEGIN

   DELETE BGD
     from [dbo].[BGControl] BGC
          INNER JOIN [dbo].[BGGroups] BGG
                     INNER JOIN [dbo].[BGDetail] BGD
                             ON BGD.[BGGroupID] = BGG.[ID]
                  ON BGG.[BGControlID] = BGC.[Id]
    WHERE (    (IsNull(@DraftNo, 0) <> 0)
           AND (BGC.[DraftNo] = IsNull(@DraftNo, 0)))
       OR (    (IsNull(@DraftNo, 0) = 0)
           AND (IsNull(@BatchNo, 0) <> 0)
           AND (BGC.[BatchNo] = @BatchNo))

   DELETE BGG
     from [dbo].[BGControl] BGC
          INNER JOIN [dbo].[BGGroups] BGG
                  ON BGG.[BGControlID] = BGC.[Id]
    WHERE (    (IsNull(@DraftNo, 0) <> 0)
           AND (BGC.[DraftNo] = IsNull(@DraftNo, 0)))
       OR (    (IsNull(@DraftNo, 0) = 0)
           AND (IsNull(@BatchNo, 0) <> 0)
           AND (BGC.[BatchNo] = @BatchNo))

   DELETE BGC
     from [dbo].[BGControl] BGC
    WHERE (    (IsNull(@DraftNo, 0) <> 0)
           AND (BGC.[DraftNo] = IsNull(@DraftNo, 0)))
       OR (    (IsNull(@DraftNo, 0) = 0)
           AND (IsNull(@BatchNo, 0) <> 0)
           AND (BGC.[BatchNo] = @BatchNo))

END')
END
ELSE
BEGIN
EXEC ('
IF OBJECT_ID(N''KEYHM_BGDeleteSAM4'', N''P'') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_BGDelete]
END')

    EXEC ('
CREATE PROCEDURE [dbo].[KEYHM_BGDelete] (
       @DraftNo INT)
AS
/*****************************************************************************
 *
 * ky_BGDeleteSAM4
 *
 * Deletes a the billing guide for specified bill
 * SP only suitable for SAM4
 *
 * 2018-08-23   John Ginnane   Created
 *
 * Modification History	:                                                                              *
 * 2020-03-13	Rajesh P	from  ky_BGDeleteSAM4
 *****************************************************************************/   
BEGIN
   DELETE BGF
     FROM [dbo].[BillingGuideFormated] AS BGF
    WHERE BGF.[BillGuideNo] = @DraftNo

   DELETE BCM
     FROM [dbo].[BillCompMatter] AS BCM
    WHERE BCM.[BillingNo] = @DraftNo

   DELETE BG
     FROM [dbo].[BillingGuide] AS BG
    WHERE BG.[BillingNo] = @DraftNo
END')
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_CASEDIARYFetchActionTypes'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_CASEDIARYFetchActionTypes]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_CASEDIARYFetchActionTypes]
      (@LoginHandlerCode VARCHAR(10),
       @MatterCode       VARCHAR(20) = '',
	   @SearchText VARCHAR(4000) = '')
AS
/*******************************************************************************************************
* This procedure is used to FETCH Action Type .					 									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_CASEDIARYFetchActionTypes]									   *
* Copied from			: [dbo].[ky_NETCASEDIARYFetchActionTypes]									   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
* 2019-08-27    Vinodhan K      Search functionality added (KEYHM-495)                                 *
*******************************************************************************************************/ 
BEGIN

SET NOCOUNT ON

DECLARE @Code VARCHAR(10)
SET @Code = (SELECT RTRIM(ISNULL([CSM].[CSWKTCODE], '')) AS [CsWktCode]
               FROM [dbo].[CaseMaster] [CSM]
              WHERE [CSM].[CSCODE] = @MatterCode)

SELECT ISNULL(RTRIM([TMP].[WKCODE]),'')  AS [Code],
       RTRIM(ISNULL([TMP].[WKDESC], '')) AS [Actions]
  FROM [dbo].[Templates] [TMP]
 WHERE 
        (
		 ISNULL(@SearchText, '') = '' OR RTRIM(LTRIM(@SearchText)) = ''
		 OR
		  (
		  [TMP].[WKDESC] LIKE '%' + @SearchText + '%'
		  )
        )
		AND
       (   ISNULL([TMP].[Dept], '') = ''
        OR [TMP].[Dept] = (SELECT [HAN].[Dept]
                             FROM [dbo].[Handlers] [HAN]
                            WHERE [HAN].[CODE] = @LoginHandlerCode))
   AND (   ISNULL([TMP].[Retired], 'N') <> 'Y'
        OR [TMP].[WKCODE] = @Code)

SET NOCOUNT OFF

END

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

CREATE PROCEDURE
       [KEYHM_CASEDIARYFetchActionWorkTypebyActionCode]
      (@ActionCode VARCHAR(5),
	   @SearchText VARCHAR(4000) = '')
AS
/*******************************************************************************************************
* This procedure is used to FETCH Work Type by Action code.		 									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_CASEDIARYFetchActionWorkTypebyActionCode]						   *
* Copied from			: [dbo].[ky_NETCASEDIARYFetchActionWorkTypebyActionCode]					   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
* 2019-08-27    Vinodhan K      Search functionality added (KEYHM-495)                                 *
*******************************************************************************************************/
BEGIN
SET NOCOUNT ON

--Case type action list
SELECT T.[WORKTYPE],
       T.[ACTIONCODE],
       T.[SEQ],
       T.[TEXT1] AS [DESCRIPTION],
       T.[WKTCODE],
       T.[ACTIONCATEGORY],
       T.[STATUS],
       T.[MILESTONETYPE],
       T.[CASECODE],
       T.[DATE],
       T.[PROCESSTYPE],
       T.[FNCODE],
       T.[TEAMCODE],
       T.[DYSTARTTIME],
       T.[ACTIONID],
       T.[ORGINALACTIONID],
       T.[PRIORITY],
       T.[HIGHLIGHTED],
       T.[ATTACHMENTS],
       T.[PROCESSSTATE],
       T.[WORKPROCESS],
       T.[BILLABLE],
       T.[EMALADDRESS],
       T.[ADDRESSTO],
       T.[EMAIL],
       T.[SUBJECT],
       T.[DELEGATIONSTATUS],
       T.[DRAFTBILLNO],
       T.[DDStatus],
       T.[DStatus],
       T.[AlternativeRow],
       REPLACE(  (  'Double click the select action to process the following**Action Code: '
                  + ISNULL(T.[ACTIONCODE],'')
                  + '**'
                  + ISNULL(T.[TEXT1],'')
                  + '****'
                  + 'Associated document to generate:'
                  + '**'
                  + ISNULL((SELECT STUFF((SELECT '**' + RTRIM(ISNULL(TDTT.[NAME],''))
                                            FROM [dbo].[TemplateActionDcouments] TADTT
                                                 INNER JOIN [dbo].[TemplateDocuments] TDTT
                                                         ON TADTT.[DOCUMENT] = TDTT.[CODE]
                                           WHERE TADTT.[ACTION] = T.[ACTIONCODE]
                                             FOR XML PATH('')), 1, 2, '')), 'Nil')
                  + '****'
                  + 'Associated action to process:**')
               + ISNULL((SELECT STUFF((SELECT '**' + Rtrim(Isnull(TATT.[DESC],''))
                                         FROM [dbo].[TemplateActions] TATT
                                              INNER JOIN [dbo].[TemplateNextActions] TNATT
                                                      ON TNATT.[NEXTACTION] = TATT.[ACTIONCODE]
                                        WHERE TNATT.[ACTION] = T.[ACTIONCODE]
                                          FOR XML PATH('')), 1, 2, '')), 'Nil')
               ,'**'
               ,CHAR(13)) AS [ToolTips],
       [Flag]
  FROM (SELECT AWT.[WORKTYPE],
               AWT.[ACTIONCODE],
               AWT.[SEQ],
               TAC.[DESC] AS [TEXT1],
               TAC.[WKTCODE],
               TAC.[ACTIONCATEGORY],
               TAC.[STATUS],
               TAC.[MILESTONETYPE],
               '' AS [CASECODE],
               NULL AS [DATE],
               TAC.[PROCESSTYPE],
               NULL AS [FNCODE],
               NULL AS [TEAMCODE],
               NULL AS [DYSTARTTIME],
               0 AS [ACTIONID],
               NULL AS [ORGINALACTIONID],
               TAC.[PRIORITY],
               TAC.[HIGHLIGHTED],
               NULL AS [ATTACHMENTS],
               NULL AS [PROCESSSTATE],
               0 AS [WORKPROCESS],
               NULL AS [BILLABLE],
               NULL AS [EMALADDRESS],
               NULL AS [ADDRESSTO],
               NULL AS [EMAIL],
               NULL AS [SUBJECT],
               0 AS [DELEGATIONSTATUS],
               0 AS [DRAFTBILLNO],
               0 AS [DDStatus],
               0 AS [DStatus],
               ROW_NUMBER()
                     OVER(ORDER BY AWT.[WORKTYPE],
                                   AWT.[SEQ]) % 2 AS AlternativeRow,
               ISNULL(TAC.[flag], 0) AS [Flag]
          FROM dbo.[ActionWorkTypes] AWT
               INNER JOIN dbo.[TemplateActions] TAC
                       ON AWT.[ACTIONCODE] = TAC.[ACTIONCODE]
         WHERE
		 (
		 ISNULL(@SearchText, '') = '' OR RTRIM(LTRIM(@SearchText)) = ''
		 OR
		  (
		  [DESCRIPTION] LIKE '%' + @SearchText + '%'
		  )
		 )
		 AND
		 AWT.[WORKTYPE] = @ActionCode) AS T

SET NOCOUNT OFF
END
GO
IF OBJECT_ID(N'KEYHM_CaseSummaryPageLoad',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_CaseSummaryPageLoad]
GO

CREATE PROCEDURE      
       [dbo].[KEYHM_CaseSummaryPageLoad]      
      (@CaseCode            VARCHAR(20))      
AS      
/*******************************************************************************************************
* To get all detail about the matter to load it on to the grid.                                        *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_CaseSummaryPageLoad]                                             *
* Copied from			: [dbo].[ky_NETCaseSummaryPageLoad]			                                   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-16	Vinodhan K		Created                                                                *
* 2019-05-29    John Ginnane    KEYD-5916 - Changed "Last Action" to be the last completed action      *
 *******************************************************************************************************/      
BEGIN      
      
DECLARE @NCOMMAND nvarchar(MAX)      
      
SET NOCOUNT ON      
      
DECLARE @DraftBillValue DECIMAL(18, 2)      
DECLARE @IsSAM4 bit      
      
SET @IsSAM4 = [dbo].[ISSAM4]()      
      
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] = @CaseCode      
      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] = @CaseCode      
    AND HED.[BillStatus] <> ''Approved''      
    AND ISNULL(HED.[ProForma], '''') = ''Y'''      
  END      
EXECUTE sp_executesql @NCOMMAND, N'@CaseCode VARCHAR(20),@DraftBillValue DECIMAL(18, 2) OUTPUT', @CaseCode = @CaseCode, @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]  = @CaseCode      
      
DECLARE @LDIADATE DATETIME      
DECLARE @LDIAACTIONTYPE VARCHAR(1)      
DECLARE @LDIATEXT1 VARCHAR(MAX)      
DECLARE @LDIAFNCODE VARCHAR(10)  
DECLARE @LDIAFNNAME VARCHAR(50)  
      
  SELECT TOP 1      
         @LDIADATE = LDIA.[DATE],      
         @LDIAACTIONTYPE = LDIA.[ACTIONTYPE],      
         @LDIATEXT1 = LDIA.[TEXT1],      
         @LDIAFNCODE = LDIA.[FNCODE],  
		 @LDIAFNNAME = [FEC].[Name]   
    FROM [dbo].[diary] LDIA  
		 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]  
	  ON LDIA.FNCODE = [FEC].[CODE]       
   WHERE LDIA.[CASECODE] = @CaseCode
     AND LDIA.[STATUS] = 1
ORDER BY LDIA.[DATE] DESC      
      
DECLARE @MDIADATE DATETIME      
DECLARE @MDIAACTIONTYPE VARCHAR(1)      
DECLARE @MDIATEXT1 VARCHAR(MAX)      
DECLARE @MDIAFNCODE VARCHAR(10)  
DECLARE @MDIAFNNAME VARCHAR(50)      
      
  SELECT TOP 1      
         @MDIADATE= MDIA.[DATE],      
         @MDIAACTIONTYPE = MDIA.[ACTIONTYPE],      
         @MDIATEXT1 = MDIA.[TEXT1],      
         @MDIAFNCODE = MDIA.[FNCODE],  
   @MDIAFNNAME = [FEC].[Name]  
    FROM [dbo].[diary] MDIA  
		 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]  
	  ON MDIA.FNCODE = [FEC].[CODE]  
   WHERE MDIA.[CASECODE] = @CaseCode      
     AND MDIA.[HIGHLIGHTED] = 'Y'      
ORDER BY MDIA.[DATE] DESC      
      
DECLARE @NDIADATE DATETIME      
DECLARE @NDIAACTIONTYPE VARCHAR(1)      
DECLARE @NDIATEXT1 VARCHAR(MAX)      
DECLARE @NDIAFNCODE VARCHAR(10)  
DECLARE @NDIAFNNAME VARCHAR(50)  
      
  SELECT TOP 1      
         @NDIADATE = NDIA.[DATE],      
         @NDIAACTIONTYPE = NDIA.[ACTIONTYPE],      
         @NDIATEXT1 = NDIA.[TEXT1],      
         @NDIAFNCODE = NDIA.[FNCODE],  
		 @NDIAFNNAME = [FEC].[Name]   
    FROM dbo.[diary] NDIA      
		 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]  
	  ON NDIA.FNCODE = [FEC].[CODE]  
   WHERE NDIA.[CASECODE] = @CaseCode  
		 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] = @CaseCode      
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] = @CaseCode'      
  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] = @CaseCode      
           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'@CaseCode VARCHAR(20), @TIEDATE DATETIME OUTPUT', @CaseCode = @CaseCode, @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 @LastTimeEntryFEName    VARCHAR(50)  
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],  
		 @LastTimeEntryFEName  = [FEC].[Name]    
    FROM [dbo].[TimeEntry] TIE  
		 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]  
      ON [TIE].[FeeEarn] = [FEC].[CODE]  
   WHERE TIE.[Matter] = @CaseCode      
		 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: KAAS_MatterClosable. If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
--                  KAAS_PMatterClosable.  If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
--                  KAAS_TLFetchTimeEntry. 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] = @CaseCode      
		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: KAAS_MatterClosable. If you change any of these calculations,      
--                                          ensure the ones in there are changed as well.      
--                  KAAS_TLFetchTimeEntry. 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] = @CaseCode      
					AND TRN.[Posted] = ''Y''      
					AND TRN.[RecType] <> ''V''      
					AND TRN.[CorrectionInd] = ''L'''      
EXECUTE sp_executesql @NCOMMAND,      
                      N'@CaseCode 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',      
                      @CaseCode      = @CaseCode,      
                      @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],
	   CTL.USERPROMPT1		                                                          AS [User1Label],      
       RTRIM(ISNULL(MAT.[User1], ''))                                                 AS [User1Value],
	   CTL.USERPROMPT2                                                                AS [User2Label],
       RTRIM(ISNULL(MAT.[User2], ''))                                                 AS [User2Value],
	   CTL.USERPROMPT3                                                                AS [User3Label], 
       RTRIM(ISNULL(MAT.[User3], ''))                                                 AS [User3Value],
	   CTL.YourRef																	  AS [YourRefLabel],
	   RTRIM(ISNULL(MAT.[YourRef], ''))                                               AS [YourRefValue],     
       MAT.[Value]                                                                    AS [Value],      
       @TimeBal                                                                       AS [TimeBal],      
         CONVERT(VARCHAR(20), (CONVERT(INT, @TimeBal) / 60))      
       + ':'      
       + SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(INT, @TimeBal) % 60), 2, 2)      AS [TimeBalHours],      
       @ChargeBal                                                                     AS [ChargeBal],      
         CONVERT(VARCHAR(20), (CONVERT(INT, @TotalTime) / 60))      
       + ':'      
       + 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],  
	   RTRIM(ISNULL(@LDIAFNNAME, ''))												  AS [LastActionFEName],      
       @MDIADATE                                                                      AS [LastMilestoneDate],      
       RTRIM(ISNULL(@MDIAActionType, ''))                                             AS [LastMilestoneType],      
       RTRIM(ISNULL(@MDIATEXT1, ''))                                                  AS [LastMilestoneText],      
       RTRIM(ISNULL(@MDIAFNCODE, ''))                                                 AS [LastMilestoneFE],      
	   RTRIM(ISNULL(@MDIAFNNAME, ''))												  AS [LastMilestoneFEName],  
       @NDIADATE                                                                      AS [NextActionDate],      
       RTRIM(ISNULL(@NDIAActionType, ''))                                             AS [NextActionType],      
       RTRIM(ISNULL(@NDIATEXT1, ''))                                                  AS [NextActionText],      
       RTRIM(ISNULL(@NDIAFNCODE, ''))                                                 AS [NextActionFE],  
	   RTRIM(ISNULL(@NDIAFNNAME, ''))                                                 AS [NextActionFEName],     
       @LastTimeEntryDate                                                             AS [LastTimeEntryDate],      
       @LastTimeEntryTime                                                             AS [LastTimeEntryTime],      
       @LastTimeEntryRate                                                             AS [LastTimeEntryRate],      
       @LastTimeEntryCharge                                                           AS [LastTimeEntryCharge],      
       @LastTimeEntryTask                                                             AS [LastTimeEntrytask],      
       @LastTimeEntryComment                                                          AS [LastTimeEntryComment],      
       @LastTimeEntryFE                                                               AS [LastTimeEntryFE],  
       @LastTimeEntryFEName                                                           AS [LastTimeEntryFEName],  
       @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]    
		CROSS JOIN [CONTROL] [Ctl]     
		WHERE MAT.[Code] = @CaseCode      
      
--Result Set 1      
--WIP      
  SELECT TIES.[FeeEarn]                                                                          AS [FeeEarn],      
         TIES.[NAME]                                                                             AS [Name],      
         CONVERT(VARCHAR(20), TIES.[TOTALTIME] / 60)      
         + ':'      
         + SUBSTRING(CONVERT(VARCHAR(3), 100 + (TIES.[TOTALTIME] % 60)), 2, 2)                   AS [FETotalHours],      
         TIES.[Charge]                                                                           AS [FECharge],      
         TIES.[ChargeBal]                                                                        AS [FEChargeBal],      
         CONVERT(VARCHAR(20), TIES.[WIPTOTALTIME] / 60)      
         + ':'      
         + SUBSTRING(CONVERT(VARCHAR(3), 100 + (TIES.[WIPTOTALTIME] % 60)), 2, 2)                AS [FEWIPHours]      
    FROM (  SELECT TIE.[FeeEarn]                                                                 AS [FeeEarn],      
                   HAN.[NAME]																	 AS [NAME],      
                   ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)                                         AS [TOTALTIME],      
                   SUM(CONVERT(DECIMAL(18, 2),ISNULL(TIE.[Charge],0)))							 AS [Charge],      
                   SUM(CONVERT(DECIMAL(18, 2),      
                               CASE WHEN @IsSAM4 = 1 AND TIE.[InvoiceNo] <> 0      
                                         THEN 0      
                                    WHEN @IsSAM4 = 0      
                                         THEN   ISNULL(TIE.[Charge],0)      
                                              - ISNULL(TIE.[BilledAmount],0)      
                                    ELSE ISNULL(TIE.[Charge],0)
							    END)) 
								AS [ChargeBal],      
                   CONVERT(INT, FLOOR(CONVERT(DECIMAL(18, 2), ISNULL(SUM(CASE WHEN @IsSAM4 = 1      
                                                                          AND [TIE].[InvoiceNo] <> 0      
                                                                              THEN 0      
                                                                         WHEN [TIE].[Charge] - [TIE].[BilledAmount] = 0      
																			  THEN 0      
                                                                         ELSE TIE.[TIME] END)      
                                                                     , 0))      
                                 *      
                                 CASE WHEN SUM(CONVERT(DECIMAL(18, 2),      
                                                       CASE WHEN @IsSAM4 = 1 AND [TIE].[InvoiceNo] <> 0      
                                                                 THEN 0      
                                                            WHEN [TIE].[Charge] - [TIE].[BilledAmount] = 0      
                                                                 THEN 0      
                                                            ELSE TIE.[Charge] END)) = 0      
                                      THEN 0      
                                      ELSE SUM(CONVERT(DECIMAL(18, 2),      
                                                       CASE WHEN @IsSAM4 = 1 AND TIE.[InvoiceNo] <> 0      
                                                                 THEN 0      
                                                            WHEN @IsSAM4 = 0      
                                                                 THEN   ISNULL(TIE.[Charge], 0)      
                                                                      - ISNULL(TIE.[BilledAmount], 0)      
                                                            ELSE ISNULL(TIE.[Charge],0)
															 END))      
                                           /      
										   SUM(CONVERT(DECIMAL(18, 2),      
                                                       CASE WHEN @IsSAM4 = 1      
                                                             AND [TIE].[InvoiceNo] <> 0      
                                                                 THEN 0      
                                                            WHEN [TIE].[Charge] - [TIE].[BilledAmount] = 0      
																 THEN 0      
                                                            ELSE TIE.[Charge] END)) END))
															AS [WIPTOTALTIME]      
              FROM [dbo].[matters] MAT      
                   INNER JOIN [dbo].[TimeEntry] TIE      
                           ON TIE.[MATTER] = MAT.[Code]      
                   INNER JOIN [dbo].[Handlers] HAN      
                           ON HAN.[CODE] = TIE.[FeeEarn]      
             WHERE TIE.[MATTER] = @CaseCode      
               AND TIE.[DATE] < GETDATE()      
               AND (   (TIE.[TimeOrCharge] = 'T')      
                    OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun      
               AND TIE.[REC_IRR] <> 'N'      
          GROUP BY TIE.[FEEEARN],      
                   HAN.[NAME]) TIES      
		  ORDER BY TIES.[ChargeBal] DESC,      
				   TIES.[TOTALTIME] DESC      
      
--Result Set 2      
-- Critical dates      
  SELECT ISNULL(CONVERT(VARCHAR, DIA.[DATE], 106), '')   AS [DiaryDate],      
         RTRIM(ISNULL(DIA.[FNCODE],''))                  AS [Who],      
         RTRIM(ISNULL(DIA.[TEXT1],''))                   AS [Description],      
         CASE RTRIM(ISNULL([Status], ''))      
              WHEN '1'      
                   THEN 'True'      
              ELSE 'False' END                           AS [Status]      
    FROM [dbo].[diary] DIA      
   WHERE DIA.[ACTIONTYPE] = 'c'      
     AND DIA.[CASECODE] = @CaseCode      
ORDER BY DIA.[date]      
      
--Result Set 3      
--Court Date Grid      
SELECT ISNULL(CONVERT(VARCHAR, DIA.[DATE], 106), '')            AS [Date],      
       DIA.[FNCODE]                                             AS [FNCode],      
       DIA.[TEXT1]                        AS [CourtDate]      
  FROM [dbo].[diary] DIA      
 WHERE DIA.[ACTIONTYPE] = 'o'      
   AND DIA.[CASECODE] = @CaseCode      
      
--Result Set 4      
--Activity to Date      
  SELECT TIES.[Activity],      
            CASE WHEN TIES.[TOTALTIME] < 0      
                      THEN '-'      
                 ELSE '' END      
         + CONVERT(VARCHAR(20), ABS(TIES.[TOTALTIME]) / 60)      
         + ':'      
         + SUBSTRING(CONVERT(VARCHAR(3), 100 + (ABS(TIES.[TOTALTIME]) % 60)), 2, 2)  AS [ActivityToDateTime],      
         TIES.[Value]                                                                AS [ActivityToDateValue]      
    FROM (  SELECT TIE.[TASK]                                                        AS [Task],      
                   CASE WHEN TSC.[DESC] IS NULL      
                             THEN 'Task Code: ' + ISNULL(TIE.[TASK], '')      
                        ELSE RTRIM(ISNULL(TSC.[DESC],'')) END                        AS [Activity],      
							 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      
                              LEFT OUTER JOIN [dbo].[TasksCodes] TSC      
                                           ON TSC.[CODE] = TIE.[Task]      
                           ON TIE.[MATTER] = MAT.[Code]      
             WHERE TIE.[MATTER] = @CaseCode      
               AND TIE.[DATE] < GETDATE()      
               AND (   (TIE.[TimeOrCharge] = 'T')      
                    OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun      
               AND TIE.[REC_IRR] <> 'N'      
               AND TIE.[Task] <> 'WRI'      
          GROUP BY TIE.[TASK],      
                   CASE WHEN TSC.[DESC] IS NULL      
                             THEN 'Task Code: ' + ISNULL(TIE.[TASK], '')      
                        ELSE RTRIM(ISNULL(TSC.[DESC],'')) END) TIES      
		  ORDER BY TIES.[Value] DESC,      
				   TIES.[TOTALTIME] DESC      
      
--Result Set 5      
--UNDERTAKINGS      
SELECT UND.[DESCRIPTION]										AS [Description],      
       UND.[VALUE]                                              AS [Value],    
       UND.[WHO]                                                AS [Who],    
       CASE [GIVENORRECEIVED]    
            WHEN 'G' THEN 'Given'      
            WHEN 'R' THEN 'Received'      
            ELSE '' END                                         AS [GivenOrReceived]      
  FROM [dbo].[UNDERTAKINGS] UND      
 WHERE UND.[MATTER] = @CaseCode      
      
--Result Set 6      
--Total Time  [Activity]      
SELECT CONVERT(VARCHAR(20), TIES.[TOTALTIME] / 60)      
       + ':'      
       + 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] = @CaseCode      
				 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] = @CaseCode      
				 AND (   (TIE.[TimeOrCharge] = 'T')      
                 OR (TIE.[TimeOrCharge] = 'C'))      
				 AND TIE.[Task] = 'WRI') TIES      
      
--Result Set 8      
--Date for Debtor Ledger      
IF @IsSAM4 = 0      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT [dbo].[KEYHM_FN_DateDiffVerbose](LDL.[LastDebtLedgerDate],      
                                       LDL.[TODAY]) AS [DebtLedgerOSVerbose],      
       CASE WHEN DATEDIFF(DAY, LDL.[LastDebtLedgerDate], LDL.[TODAY]) > 0      
                 THEN DATEDIFF(DAY, LDL.[LastDebtLedgerDate], LDL.[TODAY])      
            ELSE 0 END AS [DebtLedgerOSDays]      
  FROM (  SELECT GetDate() AS [TODAY],      
                 MAX(DTL.[DATE]) AS [LastDebtLedgerDate]      
            FROM [dbo].[DebtorsLedger] DTL      
           WHERE DTL.[MATTER] = @CaseCode) LDL'      
    EXECUTE sp_executesql @NCOMMAND, N'@CaseCode VARCHAR(20)', @CaseCode = @CaseCode      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT [dbo].[KEYHM_FN_DateDiffVerbose](LDL.[LastDebtLedgerDate],      
                                       LDL.[TODAY]) AS [DebtLedgerOSVerbose],      
       CASE WHEN DATEDIFF(DAY, LDL.[LastDebtLedgerDate], LDL.[TODAY]) > 0      
                 THEN DATEDIFF(DAY, LDL.[LastDebtLedgerDate], LDL.[TODAY])      
            ELSE 0 END AS [DebtLedgerOSDays]      
  FROM (  SELECT GetDate() AS [TODAY],      
                 @DebtBalDate AS [LastDebtLedgerDate]) LDL'      
    EXECUTE sp_executesql @NCOMMAND, N'@DebtBalDate DATETIME', @DebtBalDate = @DebtBalDate      
  END      
      
--Result Set 9      
--Date for Matter Ledger (Outstanding)      
IF @IsSAM4 = 0      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT [dbo].[KEYHM_FN_DateDiffVerbose](LDL.[LastMatLedgerDate],      
                                       LDL.[TODAY]) AS [MatLedgerOSVerbose],      
       CASE WHEN DATEDIFF(DAY, LDL.[LastMatLedgerDate], LDL.[TODAY]) > 0      
                 THEN DATEDIFF(DAY, LDL.[LastMatLedgerDate], LDL.[TODAY])      
            ELSE 0 END AS [MatLedgerOSDays]      
  FROM (  SELECT GetDate() AS [TODAY],      
                 MAX(MAL.[DATE]) AS [LastMatLedgerDate]      
            FROM [dbo].[MatterLedger] MAL     
           WHERE MAL.[MATTER] = @CaseCode      
             AND ISNULL(MAL.[VALUEO], 0) <> 0) LDL'      
    EXECUTE sp_executesql @NCOMMAND, N'@CaseCode VARCHAR(20)', @CaseCode = @CaseCode      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = N'      
SELECT [dbo].[KEYHM_FN_DateDiffVerbose](LDL.[LastMatLedgerDate],      
                                       LDL.[TODAY]) AS [MatLedgerOSVerbose],      
       CASE WHEN DATEDIFF(DAY, LDL.[LastMatLedgerDate], LDL.[TODAY]) > 0      
                 THEN DATEDIFF(DAY, LDL.[LastMatLedgerDate], LDL.[TODAY])      
            ELSE 0 END AS [MatLedgerOSDays]      
  FROM (  SELECT GetDate() AS [TODAY],      
                 @OutlayBalDate AS [LastMatLedgerDate]) LDL'      
    EXECUTE sp_executesql @NCOMMAND, N'@OutlayBalDate DATETIME', @OutlayBalDate = @OutlayBalDate      
  END      
      
-- PLEASE NOTE THAT THE CALCULATION BELOW IS ALSO USED IN KAAS_TLFetchTimeEntry, 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] = @CaseCode      
   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] = @CaseCode      
      
--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] = @CaseCode      
   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'@CaseCode VARCHAR(20)', @CaseCode = @CaseCode      
      
-- 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] = @CaseCode'      
  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] = @CaseCode      
   AND TRN.[Posted] = ''Y''      
   AND TRN.[RecType] <> ''V''      
   AND TRN.[CorrectionInd] = ''L'''      
  END      
      
EXECUTE sp_executesql @NCOMMAND, N'@CaseCode VARCHAR(20)', @CaseCode = @CaseCode      
      
-- Result set 12      
-- Print job tracker totals - KEYD-4348      
DECLARE @DOCBILLED DECIMAL(19, 2)
      
IF [dbo].[ISSAM4]() = 1      
BEGIN      
 SET @NCOMMAND = N'
  SELECT
        @DOCBILLED = SUM(ISNULL(TRN.[NominalValue], 0)) * -1      
  FROM
        [dbo].[TransactionsHeaders] AS HED
  INNER JOIN
        [dbo].[Transactions] AS TRN      
  ON
        HED.[BatchNo] = TRN.[BatchNo]      
  WHERE HED.[Posted] = ''Y''      
  AND   HED.[XnType] = ''I''      
  AND   TRN.[RecType] = ''D''      
  AND   TRN.[LineType] = ''M''      
  AND   TRN.[OutlayCode] = ISNULL((SELECT TOP 1 [KeyValue] FROM [dbo].[Settings] WHERE [KeyName] = ''PrintLedgerOutlayCode''), '''')      
  AND   TRN.[CorrectionInd] = ''L''      
  AND   HED.[MatterCode] = @CaseCode'

  EXECUTE SP_EXECUTESQL @NCOMMAND, N'@CaseCode VARCHAR(20), @DOCBILLED DECIMAL(19, 2)', @CaseCode = @CaseCode, @DOCBILLED = @DOCBILLED
END      
ELSE      
BEGIN      
 SET @NCOMMAND = N'
  SELECT
        @DOCBILLED = SUM(ISNULL(BAD.[VALUE], 0))      
  FROM
        [dbo].[BatchH] AS BAH      
  INNER JOIN
        [dbo].[BatchDetails] AS BAD      
  ON
        BAH.[BATCHNO] = BAD.[BATCHNO]      
  INNER JOIN
        [dbo].[control] AS CON      
  ON
        BAD.[CODE] = CON.[MISCOUTLAY]      
  WHERE BAH.[POSTED] = ''Y''      
  AND   BAH.[TYPE]= ''I''      
  AND   BAD.[OUTLAY] = ''F''      
  AND   BAD.[OUTLAYCODE] = ISNULL((SELECT TOP 1 [KeyValue] FROM [dbo].[Settings] WHERE [KeyName] = ''PrintLedgerOutlayCode''), '''')      
  AND   BAH.[MATTER] = @CaseCode'  

  EXECUTE SP_EXECUTESQL @NCOMMAND, N'@CaseCode VARCHAR(20), @DOCBILLED DECIMAL(19, 2)', @CaseCode = @CaseCode, @DOCBILLED = @DOCBILLED
END      
      
SELECT ISNULL(SUM(ISNULL(PJT.[Cost], 0)), 0) AS [TotalDoc],      
       ISNULL(SUM(ISNULL(CASE WHEN ISNULL(PJT.[InvoiceNo], 0) <= 0 AND ISNULL(PJT.[Status], '') = 'Printed' 
								THEN ISNULL(PJT.[Cost], 0)
							 ELSE 0 
						 END, 0)), 0) 
						 AS [UnbilledDoc],      
       ISNULL(@DOCBILLED, 0) AS [BilledDoc],      
       ISNULL(SUM(ISNULL(CASE WHEN ISNULL(PJT.[Status], '') <> 'Printed' 
								THEN ISNULL(PJT.[Cost], 0) 
							 ELSE 0
						 END, 0)), 0)
						 AS [WriteOffDoc]      
  FROM [dbo].[matters] AS MAT      
       LEFT OUTER JOIN [dbo].[PrintJobTracker] AS PJT      
    ON MAT.[Code] = PJT.[MatterCode]      
 WHERE MAT.[Code] = @CaseCode       

 SET NOCOUNT OFF      
END
GO
IF OBJECT_ID(N'KEYHM_CheckUnpostableEntries',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KEYHM_CheckUnpostableEntries]
GO


CREATE PROCEDURE
       [dbo].[KEYHM_CheckUnpostableEntries]
      (@HANDLER varchar(10))
AS
/*******************************************************************************************************
* Flags unpostable entries as "do not post".											               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_CheckUnpostableEntries]										   *
* Copied from			: [dbo].[ky_NETCheckUnpostableEntries]										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
  UPDATE TDB
     SET TDB.[POST] = CASE WHEN MAT.[CODE] IS NULL
                                THEN 'N'
                           ELSE 'Y' END
    FROM WDNTEID NTEID
         INNER JOIN [dbo].[TimeDayBook] TDB
                 ON TDB.[RECORDID] = NTEID.[RECORDID]
		 AND RTRIM(ISNULL(TDB.[MATTER], '')) <> ''
         INNER JOIN [dbo].[matters] MAT
                 ON MAT.[Code] = TDB.[MATTER]
   WHERE NTEID.[HANDLER] = @HANDLER
END
GO

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

CREATE PROCEDURE [dbo].[KEYHM_Dashboard] (
       @Handler     VARCHAR(10),
       @Fromdate    DATETIME,
       @todate      DATETIME)
AS
/*******************************************************************************************************
* Populates the My Overview page																	   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_Dashboard]						                               *
* Copied from			: [dbo].[KY_NETDashboard3]						                               *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-16	Vinodhan K		Created                                                                *
 *******************************************************************************************************/ 
BEGIN
DECLARE @NCOMMAND NVARCHAR(MAX)
DECLARE @TotalUndertakings  INT
DECLARE @TotalStatuteLimits INT
DECLARE @IsSAM4             BIT
DECLARE @BitWiseID          BIGINT
DECLARE @GETDATE            DATETIME

SET @GETDATE = GETDATE()

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

SET @handler = CASE WHEN RTRIM(ISNULL(@handler, '')) = '' THEN 'ADM' ELSE RTRIM(@handler) END

SELECT @BitWiseID = HNG.[BitWiseID]
  FROM HandlerNETGroupMembership HNG
 WHERE HNG.[HANDLER] = CONVERT(VARCHAR(10), @handler)

SET @BitWiseID = ISNULL(@BitWiseID, [dbo].[KEYHM_FN_GetOldPermissions](RTRIM(ISNULL(@handler, ''))))

IF (@handler = 'ADM')
  BEGIN
    SET @BitWiseID = CONVERT(BIGINT, -1)
  END

SELECT @TotalUndertakings = count(1)
  FROM dbo.[Undertakings] UND
 INNER JOIN [dbo].[matters] MAT
    ON MAT.[Code] = UND.[MATTER]
 WHERE UND.[AuthorisedByFE] = @Handler
   AND MAT.[Closed] <> 'Y'
   AND UND.[DISCHARGEDATE] IS NULL

SELECT @TotalStatuteLimits = count(1)
  FROM dbo.[matters] MAT
 WHERE MAT.[FECode] = @Handler
   AND DATEDIFF(DD, @GETDATE, CASE WHEN ISNULL(MAT.[StatuteLimits], '21000101')='19000101' THEN '21000101' ELSE MAT.[StatuteLimits] END) <= 60
   AND MAT.[Closed] <> 'Y'

--Statement to get No. of Overdue and No. of Outstandings
SELECT ISNULL(ADT.[Overdue Task], 0) AS [OverdueTask],
       ISNULL(ADT.[Outstanding Task], 0) AS [OutstandingTask],
       ISNULL(ADT.[Critical Tasks], 0) AS [CriticalTasks],
       ISNULL(ADT.[Court Dates], 0) AS [CourtDates],
       ISNULL(ADT.[High Priority], 0) AS [HighPriority],
       ISNULL(ADT.[Phone Message], 0) AS [PhoneMessage],
       @TotalUndertakings AS [UnderTaking],
       @TotalStatuteLimits AS [StatuteDateApproaching]
  FROM (  SELECT SUM(CASE WHEN DEL.[DATE] < @fromdate
                               THEN 0
                          WHEN DEL.[DATE] >= DATEADD(DD, 1, CONVERT (DATETIME, CONVERT(VARCHAR, @GETDATE, 112)))
                               THEN 0
                          WHEN [DEL].[STATUS] = 0
                               THEN 1
                          ELSE 0 END) AS [Overdue Task],
                 SUM(CASE WHEN DEL.[DATE] < @fromdate
                               THEN 0
                          WHEN DEL.[DATE] >= DATEADD(DD, 1, CONVERT (DATETIME, CONVERT(VARCHAR, @todate, 112)))
                               THEN 0
                          WHEN [DEL].[STATUS] = 0
                               THEN 1
                          ELSE 0 END) AS [Outstanding Task],
                 SUM(CASE WHEN DEL.[DATE] < @fromdate
                               THEN 0
                          WHEN DEL.[DATE] >= DATEADD(DD, 1, CONVERT (DATETIME, CONVERT(VARCHAR, @todate, 112)))
                               THEN 0
                          WHEN [DIA].[ActionType] = 'C'
                               THEN 1
                          ELSE 0 END) AS [Critical Tasks],
                 SUM(CASE WHEN DEL.[DATE] < @fromdate
                               THEN 0
                          WHEN DEL.[DATE] >= DATEADD(DD, 1, CONVERT (DATETIME, CONVERT(VARCHAR, @todate, 112)))
                               THEN 0
                          WHEN [DIA].[ActionType] = 'O'
                               THEN 1
                          ELSE 0 END) AS [Court Dates],
                 SUM(CASE WHEN DEL.[DATE] < @fromdate
                               THEN 0
                          WHEN DEL.[DATE] >= DATEADD(DD, 1, CONVERT (DATETIME, CONVERT(VARCHAR, @todate, 112)))
                               THEN 0
                          WHEN [DIA].[PRIORITY] = 'H'
                               THEN 1
                          ELSE 0 END) AS [High Priority],
                 SUM(CASE WHEN DEL.[DATE] < @fromdate
                               THEN 0
                          WHEN DEL.[DATE] >= DATEADD(DD, 1, CONVERT (DATETIME, CONVERT(VARCHAR, @todate, 112)))
                               THEN 0
                          WHEN [DIA].[ActionType] = 'T'
                               THEN 1
                          ELSE 0 END) AS [Phone Message]
            FROM [dbo].[DiaryDelegations] DEL
                 INNER JOIN [dbo].[Diary] DIA
                            INNER JOIN [dbo].[matters] MAT
                                       INNER JOIN [dbo].[Contacts] CON
                                               ON CON.[CODE] = MAT.[CLIENTCODE]
                                       LEFT OUTER JOIN [dbo].[MatterNetPrivileges] MNP
                                                    ON MNP.[MATTER] = MAT.[Code]
                                    ON MAT.[CODE] = DIA.[CASECODE]
                                   AND ISNULL(MAT.[Closed], 'N') <> 'Y'
                         ON DIA.[ACTIONID] = DEL.[ACTIONID]
           WHERE DEL.[HANDLER] = @Handler
             AND DEL.[STATUS] = 0
             AND DEL.[DelType] <> 'Completed'
             AND DEL.[DelType] <> 'Processed'
             AND DEL.[DelType] <> 'Returned'
             AND (   ISNULL(MNP.[Privileges], CONVERT (BIGINT, -1)) & @BitWiseID <> 0
                  OR ISNULL(MNP.[Privileges], CONVERT (BIGINT, 0)) = 0)) ADT

SELECT 0 AS [Zero]

DECLARE @MyTimeDayBook        DECIMAL(18, 2)
DECLARE @MyTimeDayBookHr      VARCHAR(20)
DECLARE @MyTimeDayBookWeek    DECIMAL(18, 2)
DECLARE @MyTimeDayBookWeekHr  VARCHAR(20)
DECLARE @MyTimeDayBookMonth   DECIMAL(18, 2)
DECLARE @MyTimeDayBookMonthHr VARCHAR(20)
DECLARE @MyTimeDayBookYear    DECIMAL(18, 2)
DECLARE @MyTimeDayBookYearHr  VARCHAR(20)
DECLARE @AdminTimeDayBookMonth   DECIMAL(18, 2)
DECLARE @AdminTimeDayBookMonthHr VARCHAR(20)
DECLARE @AdminTimeDayBookYear    DECIMAL(18, 2)
DECLARE @AdminTimeDayBookYearHr  VARCHAR(20)
DECLARE @DailyAverageMTD      DECIMAL(18, 2) -- Average time recorded per day in the current month
DECLARE @DailyAverageYTD      DECIMAL(18, 2) -- Average time recorded per day in the current year

DECLARE @TODAYNUM     INT
DECLARE @MONDAY       DATETIME
DECLARE @STARTOFMONTH DATETIME
DECLARE @STARTOFYEAR  DATETIME
DECLARE @MONTHTODATE  DATETIME -- This is the current date, up to the end of the financial month

SELECT @TODAYNUM = DATEPART(WEEKDAY, @GETDATE) - DATEPART(WEEKDAY, '20000102') --the 2nd of January, 2000 was a Monday

IF @TODAYNUM <= 0
  SET @TODAYNUM = @TODAYNUM + 7

SET @MONDAY = CONVERT(DATETIME, CONVERT(VARCHAR, DATEADD(DAY, 1 - @TODAYNUM, @GETDATE), 112))

SELECT @TODAYNUM = DATEPART(DAY, @GETDATE)

SELECT @STARTOFMONTH = KPI.[FromDate],
       @STARTOFYEAR  = KPI.[StartOfYear],
	   @MONTHTODATE  = CASE WHEN @GETDATE > KPI.[ToDate] THEN KPI.[ToDate] ELSE @GETDATE END
  FROM [dbo].[KPIParameters] AS KPI

SET @STARTOFYEAR = ISNULL(@STARTOFYEAR, CONVERT(DATETIME, CONVERT(VARCHAR(4), YEAR(@GETDATE)) + '0101'))

SELECT @MyTimeDayBook = ISNULL(SUM(ISNULL(TDB.[TIME], 0)), 0)
  FROM [dbo].[TimeDayBook] TDB
 WHERE TDB.[FEEEARN] = @Handler
   AND TDB.[TIMEORCHARGE] = 'T'
   AND TDB.[Rec_irr] = 'C'

SELECT @MyTimeDayBookWeek = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[FEEEARN] = @Handler
   AND TIE.[TIMEORCHARGE] = 'T'
   AND TIE.[Rec_irr] = 'C'
   AND TIE.[Date] >= @MONDAY
   AND TIE.[DATE] <= @GETDATE
   AND ISNULL(TIE.[TASK], '') <> 'WRI'
   AND TIE.[Matter] <> '~'

SELECT @MyTimeDayBookMonth = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[FEEEARN] = @Handler
   AND TIE.[TIMEORCHARGE] = 'T'
   AND TIE.[Rec_irr] = 'C'
   AND TIE.[Date] >= @STARTOFMONTH
   AND TIE.[DATE] <= @MONTHTODATE
   AND ISNULL(TIE.[TASK], '') <> 'WRI'
   AND TIE.[Matter] <>'~'

SELECT @MyTimeDayBookYear = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[FEEEARN] = @Handler
   AND TIE.[TIMEORCHARGE] = 'T'
   AND TIE.[Rec_irr] = 'C'
   AND TIE.[Date] >= @STARTOFYEAR
   AND TIE.[DATE] <= @MONTHTODATE
   AND ISNULL(TIE.[TASK], '') <> 'WRI'
   AND TIE.[Matter] <>'~'

SELECT @AdminTimeDayBookMonth = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[FEEEARN] = @Handler
   AND TIE.[TIMEORCHARGE] = 'T'
   AND TIE.[Date] >= @STARTOFMONTH
   AND TIE.[DATE] <= @MONTHTODATE
   AND ISNULL(TIE.[TASK], '') <> 'WRI'
   AND TIE.[Matter] = '~'

SELECT @AdminTimeDayBookYear = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[FEEEARN] = @Handler
   AND TIE.[TIMEORCHARGE] = 'T'
   AND TIE.[Date] >= @STARTOFYEAR
   AND TIE.[DATE] <= @MONTHTODATE
   AND ISNULL(TIE.[TASK], '') <> 'WRI'
   AND TIE.[Matter] = '~'

SET @MyTimeDayBook = CASE WHEN @MyTimeDayBook < 0 THEN 0 ELSE @MyTimeDayBook END
SET @MyTimeDayBookHr =
                       CASE
                     	  WHEN
                     		LEN(CONVERT(INT, @MyTimeDayBook) / 60) < 2
                     	  THEN
                     		'0' +  CAST(CONVERT(INT, @MyTimeDayBook) / 60 AS VARCHAR)
                     	  ELSE
                     		CAST(CONVERT(INT, @MyTimeDayBook) / 60 AS VARCHAR)
                       END
                       + ':'
                       + SUBSTRING(CONVERT(VARCHAR(3), 100 + (CONVERT(INT, @MyTimeDayBook) % 60)), 2, 2)

SET @MyTimeDayBookWeek = CASE WHEN @MyTimeDayBookWeek < 0 THEN 0 ELSE @MyTimeDayBookWeek END
SET @MyTimeDayBookWeekHr = 
                         CASE
                            WHEN
                      	      LEN(CONVERT(INT, @MyTimeDayBookWeek) / 60) < 2
                            THEN
                      	      '0' +  CAST(CONVERT(INT, @MyTimeDayBookWeek) / 60 AS VARCHAR)
                            ELSE
                      	      CAST(CONVERT(INT, @MyTimeDayBookWeek) / 60 AS VARCHAR)
                         END
                         + ':'
                         + SUBSTRING(CONVERT(VARCHAR(3), 100 + (CONVERT(INT, @MyTimeDayBookWeek) % 60)), 2, 2)

SET @MyTimeDayBookMonth = CASE WHEN @MyTimeDayBookMonth < 0 THEN 0 ELSE @MyTimeDayBookMonth END
SET @MyTimeDayBookMonthHr = 
                          CASE
                             WHEN
                      	       LEN(CONVERT(INT, @MyTimeDayBookMonth) / 60) < 2
                             THEN
                      	       '0' +  CAST(CONVERT(INT, @MyTimeDayBookMonth) / 60 AS VARCHAR)
                             ELSE
                      	       CAST(CONVERT(INT, @MyTimeDayBookMonth) / 60 AS VARCHAR)
                          END
                          + ':'
                          + SUBSTRING(CONVERT(VARCHAR(3), 100 + (CONVERT(INT, @MyTimeDayBookMonth) % 60)), 2, 2)

SET @MyTimeDayBookYear = CASE WHEN @MyTimeDayBookYear < 0 THEN 0 ELSE @MyTimeDayBookYear END
SET @MyTimeDayBookYearHr = 
                          CASE
                             WHEN
                      	       LEN(CONVERT(INT, @MyTimeDayBookYear) / 60) < 2
                             THEN
                      	       '0' +  CAST(CONVERT(INT, @MyTimeDayBookYear) / 60 AS VARCHAR)
                             ELSE
                      	       CAST(CONVERT(INT, @MyTimeDayBookYear) / 60 AS VARCHAR)
                          END
                         + ':'
                         + SUBSTRING(CONVERT(VARCHAR(3), 100 + (CONVERT(INT, @MyTimeDayBookYear) % 60)), 2, 2)

SET @AdminTimeDayBookMonth   = CASE WHEN @AdminTimeDayBookMonth < 0 THEN 0 ELSE @AdminTimeDayBookMonth END
SET @AdminTimeDayBookMonthHr =
                              CASE
                                 WHEN
                      	           LEN(CONVERT(INT, @AdminTimeDayBookMonth) / 60) < 2
                                 THEN
                      	           '0' +  CAST(CONVERT(INT, @AdminTimeDayBookMonth) / 60 AS VARCHAR)
                                 ELSE
                      	           CAST(CONVERT(INT, @AdminTimeDayBookMonth) / 60 AS VARCHAR)
                              END
                            + ':'
                            + SUBSTRING(CONVERT(VARCHAR(3), 100 + (CONVERT(INT, @AdminTimeDayBookMonth) % 60)), 2, 2)

SET @AdminTimeDayBookYear    = CASE WHEN @AdminTimeDayBookYear < 0 THEN 0 ELSE @AdminTimeDayBookYear END
SET @AdminTimeDayBookYearHr = 
                              CASE
                                 WHEN
                      	           LEN(CONVERT(INT, @AdminTimeDayBookYear) / 60) < 2
                                 THEN
                      	           '0' +  CAST(CONVERT(INT, @AdminTimeDayBookYear) / 60 AS VARCHAR)
                                 ELSE
                      	           CAST(CONVERT(INT, @AdminTimeDayBookYear) / 60 AS VARCHAR)
                              END
                            + ':'
                            + SUBSTRING(CONVERT(VARCHAR(3), 100 + (CONVERT(INT, @AdminTimeDayBookYear) % 60)), 2, 2)

SELECT @DailyAverageMTD = SUM(ISNULL(TIE.[Time], 0)) / CASE WHEN ISNULL([dbo].[KEYHM_NetWorkingDays](@STARTOFMONTH, @MONTHTODATE), 0) = 0 
                                                                 THEN 1
                                                            ELSE [dbo].[KEYHM_NetWorkingDays](@STARTOFMONTH, @MONTHTODATE) END
  FROM [dbo].[TimeEntry] AS TIE
 WHERE TIE.[FeeEarn] = @HANDLER
   AND TIE.[Rec_Irr] = 'C'
   AND TIE.[TimeOrCharge] <> 'B'
   AND TIE.[Task] <> 'WRI'
   AND TIE.[Matter] <> '~'
   AND TIE.[Date] <= @MONTHTODATE
   AND TIE.[Date] >= @STARTOFMONTH
   
SELECT @DailyAverageYTD = SUM(ISNULL(TIE.[Time], 0)) / CASE WHEN ISNULL([dbo].[KEYHM_NetWorkingDays](@STARTOFYEAR, @MONTHTODATE), 0) = 0 
                                                                 THEN 1
                                                            ELSE [dbo].[KEYHM_NetWorkingDays](@STARTOFYEAR, @MONTHTODATE) END
  FROM [dbo].[TimeEntry] AS TIE
 WHERE TIE.[FeeEarn] = @HANDLER
   AND TIE.[Rec_Irr] = 'C'
   AND TIE.[TimeOrCharge] <> 'B'
   AND TIE.[Task] <> 'WRI'
   AND TIE.[Matter] <> '~'
   AND TIE.[Date] <= @GETDATE
   AND TIE.[Date] >= @STARTOFYEAR

-- Statement to get Time recorder value
SELECT @MyTimeDayBookHr            AS [MyTimedayBookHr],
       @MyTimeDayBookWeekHr        AS [TimeRecordedThisWeekHr],
       @MyTimeDayBookMonthHr       AS [TimeRecordedThisMonthHr],
       @MyTimeDayBookYearHr        AS [TimeRecordedThisYearHr],
       @MyTimeDayBook              AS [MyTimedayBook],
       @MyTimeDayBookWeek          AS [TimeRecordedThisWeek],
       @MyTimeDayBookMonth         AS [TimeRecordedThisMonth],
       @MyTimeDayBookYear          AS [TimeRecordedThisYear],
       @AdminTimeDayBookMonthHr    AS [AdminTimeRecordedThisMonthHr],
       @AdminTimeDayBookYearHr     AS [AdminTimeRecordedThisYearHr],
       @AdminTimeDayBookMonth      AS [AdminTimeRecordedThisMonth],
       @AdminTimeDayBookYear       AS [AdminTimeRecordedThisYear],
       ISNULL(@DailyAverageMTD, 0) AS [AverageTimeMTD],
       ISNULL(@DailyAverageYTD, 0) AS [AverageTimeYTD]

--Statement to get fees details
DECLARE @FeesCurrent  DECIMAL(18, 2)
DECLARE @FeesLastPer  DECIMAL(18, 2)
DECLARE @FeesYTD      DECIMAL(18, 2)
DECLARE @FeesLastYTD  DECIMAL(18, 2)
DECLARE @FeesLastYear DECIMAL(18, 2)

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = '
  SELECT @FeesCurrent = ISNULL(SUM(CASE WHEN BH.[INVCR] = ''I'' THEN BD.[VALUE] ELSE 0 END - CASE WHEN BH.[INVCR] = ''C'' THEN BD.[VALUE] ELSE 0 END), 0)
    FROM dbo.[BatchDetails] BD
         INNER JOIN dbo.[BatchH] BH
                 ON BD.[BATCHNO] = BH.[BATCHNO]
                AND BH.[POSTED] = ''Y''
         INNER JOIN [dbo].[KPIParameters] KPI
                 ON KPI.[Year] = BD.[YEAR]
                AND KPI.[Period] = BD.[PERNO]
   WHERE BD.[FEE] = @Handler
     AND BD.[TYPE] = ''I''
     AND BD.[OUTLAY] = ''F'''
  END
ELSE
  BEGIN
    SET @NCOMMAND = '
  SELECT @FeesCurrent = ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)
  FROM [dbo].[Transactions] 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'')
              AND TRN.[FeeEarner] = @Handler
       INNER JOIN [dbo].[KPIParameters] KPI
               ON KPI.[Year] = HED.[PostingYear]
              AND KPI.[Period] = HED.[PostingPeriod]
 WHERE HED.[RecType] = ''H'''
  END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10),@FeesCurrent DECIMAL(18, 2) OUTPUT', @Handler = @Handler, @FeesCurrent=@FeesCurrent OUTPUT

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = '
  SELECT @FeesLastPer = ISNULL(SUM(CASE WHEN BH.[INVCR] = ''I'' THEN BD.[VALUE] ELSE 0 END - CASE WHEN BH.[INVCR] = ''C'' THEN BD.[VALUE] ELSE 0 END), 0)
    FROM dbo.[BatchDetails] BD
         INNER JOIN dbo.[BatchH] BH
                 ON BD.[BATCHNO] = BH.[BATCHNO]
                AND BH.[POSTED] = ''Y''
         INNER JOIN [dbo].[KPIParameters] KPI
                 ON (    KPI.[Year] = BD.[YEAR]
                     AND KPI.[Period] <> 1
                     AND KPI.[Period] - 1 = BD.[PERNO])
                 OR (    KPI.[Year] = BD.[YEAR] - 1
                     AND KPI.[Period] = 1
                     AND BD.[PERNO] = 12)
   WHERE BD.[FEE] = @Handler
     AND BD.[TYPE] = ''I''
     AND BD.[OUTLAY] = ''F'''
  END
ELSE
  BEGIN
    SET @NCOMMAND = '
  SELECT @FeesLastPer = ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)
    FROM [dbo].[Transactions] 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'')
                AND TRN.[FeeEarner] = @Handler
        INNER JOIN [dbo].[KPIParameters] KPI
                ON (    KPI.[Year] = HED.[PostingYear]
                    AND KPI.[Period] <> 1
                    AND KPI.[Period] - 1 = HED.[PostingPeriod])
                OR (    KPI.[Year] = HED.[PostingYear] - 1
                    AND KPI.[Period] = 1
                    AND HED.[PostingPeriod] = 12)
  WHERE HED.[RecType] = ''H'''
  END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10),@FeesLastPer DECIMAL(18, 2) OUTPUT', @Handler = @Handler, @FeesLastPer=@FeesLastPer OUTPUT

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = '
  SELECT @FeesYTD = ISNULL(SUM(CASE WHEN BH.[INVCR] = ''I'' THEN BD.[VALUE] ELSE 0 END - CASE WHEN BH.[INVCR] = ''C'' THEN BD.[VALUE] ELSE 0 END), 0)
    FROM dbo.[BatchDetails] BD
         INNER JOIN dbo.[BatchH] BH
                 ON BD.[BATCHNO] = BH.[BATCHNO]
                AND BH.[POSTED] = ''Y''
         INNER JOIN [dbo].[KPIParameters] KPI
                 ON KPI.[Year] = BD.[YEAR]
                AND KPI.[Period] >= BD.[PERNO]
   WHERE BD.[FEE] = @Handler
     AND BD.[TYPE] = ''I''
     AND BD.[OUTLAY] = ''F'''
  END
ELSE
  BEGIN
    SET @NCOMMAND = '
SELECT @FeesYTD = ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)
  FROM [dbo].[Transactions] 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'')
              AND TRN.[FeeEarner] = @Handler
       INNER JOIN [dbo].[KPIParameters] KPI
               ON KPI.[Year] = HED.[PostingYear]
              AND KPI.[Period] >= HED.[PostingPeriod]
 WHERE HED.[RecType] = ''H'''
  END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10),@FeesYTD DECIMAL(18, 2) OUTPUT', @Handler = @Handler, @FeesYTD=@FeesYTD OUTPUT

IF @IsSAM4 = 0
BEGIN
    SET @NCOMMAND = 'SELECT @FeesLastYTD = ISNULL(SUM(CASE WHEN BH.[INVCR] = ''I'' THEN BD.[VALUE] ELSE 0 END - CASE WHEN BH.[INVCR] = ''C'' THEN BD.[VALUE] ELSE 0 END), 0)
                       FROM dbo.[BatchDetails] BD
                            INNER JOIN dbo.[BatchH] BH
                                    ON BD.[BATCHNO] = BH.[BATCHNO]
                                   AND BH.[POSTED] = ''Y''
                            INNER JOIN [dbo].[KPIParameters] KPI
                                    ON KPI.[Year]-1 = BD.[YEAR]
                                   AND KPI.[Period] >= BD.[PERNO]
                      WHERE BD.[FEE] = @Handler
                        AND BD.[TYPE] = ''I''
                        AND BD.[OUTLAY] = ''F'''
END
ELSE
BEGIN
    SET @NCOMMAND = 'SELECT @FeesLastYTD = ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)
                       FROM [dbo].[Transactions] 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] IN (''L'', ''X'')
                                   AND TRN.[FeeEarner] = @Handler
                            INNER JOIN [dbo].[KPIParameters] KPI
                                    ON KPI.[Year]-1 = HED.[PostingYear]
                                   AND KPI.[Period] >= HED.[PostingPeriod]
                      WHERE HED.[RecType] = ''H'''
END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10),@FeesLastYTD DECIMAL(18, 2) OUTPUT', @Handler = @Handler, @FeesLastYTD=@FeesLastYTD OUTPUT

IF @IsSAM4 = 0
BEGIN
    SET @NCOMMAND = 'SELECT @FeesLastYear = ISNULL(SUM(CASE WHEN BH.[INVCR] = ''I'' THEN BD.[VALUE] ELSE 0 END - CASE WHEN BH.[INVCR] = ''C'' THEN BD.[VALUE] ELSE 0 END), 0)
                       FROM dbo.[BatchDetails] BD
                            INNER JOIN dbo.[BatchH] BH
                                    ON BD.[BATCHNO] = BH.[BATCHNO]
                                   AND BH.[POSTED] = ''Y''
                            INNER JOIN [dbo].[KPIParameters] KPI
                                    ON KPI.[Year]-1 = BD.[YEAR]
                      WHERE BD.[FEE] = @Handler
                        AND BD.[TYPE] = ''I''
                        AND BD.[OUTLAY] = ''F'''
END
ELSE
BEGIN
    SET @NCOMMAND = 'SELECT @FeesLastYear = ISNULL(SUM(ISNULL(TRN.[FeesBilled], 0) * ISNULL(TRN.[DrCr], 1) * (-1)), 0)
                       FROM [dbo].[Transactions] 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] IN (''L'', ''X'')
                                   AND TRN.[FeeEarner] = @Handler
                            INNER JOIN [dbo].[KPIParameters] KPI
                                    ON KPI.[Year]-1 = HED.[PostingYear]
                      WHERE HED.[RecType] = ''H'''
END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10),@FeesLastYear DECIMAL(18, 2) OUTPUT', @Handler = @Handler, @FeesLastYear=@FeesLastYear OUTPUT

SELECT REPLACE(CONVERT(VARCHAR, CAST(ROUND(ISNULL(@FeesCurrent, 0), 0) AS MONEY), 1), '.00', '') AS [FeesIssuedCurrentMonth],
       REPLACE(CONVERT(VARCHAR, CAST(ROUND(ISNULL(@FeesLastPer, 0), 0) AS MONEY), 1), '.00', '') AS [FeesIssuedLastMonth],
       REPLACE(CONVERT(VARCHAR, CAST(ROUND(ISNULL(@FeesYTD, 0), 0) AS MONEY), 1), '.00', '') AS [FeesIssuedYearToDate],
       REPLACE(CONVERT(VARCHAR, CAST(ROUND(ISNULL(@FeesLastYTD, 0), 0) AS MONEY), 1), '.00', '') AS [FeesIssuedLastYearToDate],
       REPLACE(CONVERT(VARCHAR, CAST(ROUND(ISNULL(@FeesLastYear, 0), 0) AS MONEY), 1), '.00', '') AS [FeesIssuedLastYear]

DECLARE @DraftInvoice DECIMAL(18, 2)

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = '
SELECT @DraftInvoice = ISNULL(SUM((ISNULL(BD.[NET], 0) + 
                                   ISNULL(BD.[VATVALUE], 0)) * 
                                  CASE WHEN ISNULL(BH.[INVCR], ''I'') = ''C'' 
                                            THEN -1
                                  ELSE 1 END), 0)
  FROM [dbo].[matters] MAT
       INNER JOIN [dbo].[BillHeader] BH
                  INNER JOIN [dbo].[BillDetails] BD
                          ON BD.[DRAFTNO] = BH.[DRAFTNO]
               ON BH.[MATTER] = MAT.[Code]
              AND BH.[BILLNO] = 0
 WHERE MAT.[FECode] = @Handler'
  END
ELSE
  BEGIN
    SET @NCOMMAND = '
SELECT @DraftInvoice = ISNULL(SUM((ISNULL(BD.[NetValue], 0) + 
                                   ISNULL(BD.[VatValue], 0)) *
                                  CASE WHEN ISNULL(BH.[TYPE], ''I'') = ''C''
                                            THEN -1
                                       ELSE 1 END), 0)
  FROM [dbo].[matters] AS MAT
       INNER JOIN [dbo].[Billhead] BH
               ON BH.[MatterCode] = MAT.[Code]
       INNER JOIN [dbo].[BillDetail] BD
               ON BD.[BillID] = BH.[BillingID]
              AND BD.[RecordType] = ''F''
              AND BD.[FeCode] = @Handler
 WHERE MAT.[FECode] = @Handler
   AND BH.[BillStatus] <> ''Approved'''
  END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10),@DraftInvoice DECIMAL(18, 2) OUTPUT', @Handler = @Handler, @DraftInvoice=@DraftInvoice OUTPUT

DECLARE @OSFees DECIMAL(19, 2)
DECLARE @OSInvoices DECIMAL(19, 2)
DECLARE @AVGDDays INT

-- Pino 2015-05-26 - Please make sure that this calculation exactly mirrors the corresponding one
--                   in [dbo].[KAAS_DashboardCaseAlert] - if either is changed, change the other one
--                   accordingly
IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = N'
SELECT @OSFees = DT.[OSFees],
       @OSInvoices = DT.[OSInvoices],
       @AVGDDays = CASE WHEN DT.[DebtorEntries] = 0
                             THEN 0
                        ELSE DT.[DebtorDays] / DT.[DebtorEntries] END
  FROM (SELECT CONVERT(DECIMAL(19, 2), ISNULL(SUM(CONVERT(DECIMAL(19, 2), ISNULL(DTL.[OSFees], 0))), 0)) AS [OSFees],
               CONVERT(DECIMAL(19, 2), ISNULL(SUM(CONVERT(DECIMAL(19, 2), ISNULL(DTL.[OSVALUE], 0))), 0)) AS [OSInvoices],
               ISNULL(SUM(CASE WHEN DTL.[DATE] IS NULL
                                    THEN 0
                               WHEN DTL.[DATE] > @GETDATE
                                    THEN 0
                               WHEN DTL.[OSVALUE] = 0
                                    THEN 0
                               ELSE DATEDIFF(Day, DTL.[DATE], @GETDATE) END), 0) AS [DebtorDays],
               ISNULL(SUM(CASE WHEN DTL.[DATE] IS NULL
                                    THEN 0
                               WHEN DTL.[DATE] > @GETDATE
                                    THEN 0
                               WHEN DTL.[OSVALUE] = 0
                                    THEN 0
                               ELSE 1 END), 0) AS [DebtorEntries]
          FROM [dbo].[matters] MAT
               INNER JOIN [dbo].[DebtorsLedger] DTL
                       ON DTL.[MATTER] = MAT.[Code]
                      AND DTL.[OSValue] > 0
          WHERE MAT.[FECode] = @Handler) DT'

    EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @GETDATE DATETIME, @OSFees DECIMAL(19, 2) OUTPUT, @OSInvoices DECIMAL(19, 2) OUTPUT, @AVGDDays INT OUTPUT', @Handler = @Handler, @GETDATE = @GETDATE, @OSFees = @OSFees OUTPUT, @OSInvoices = @OSInvoices OUTPUT, @AVGDDays = @AVGDDays OUTPUT

  END
ELSE
  BEGIN
    SET @NCOMMAND = N'
SELECT @OSFees = DT.[OSFees],
       @OSInvoices = DT.[OSInvoices],
       @AVGDDays = CASE WHEN DT.[DebtorEntries] = 0
                             THEN 0
                        ELSE DT.[DebtorDays] / DT.[DebtorEntries] END
  FROM (SELECT CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[DebtorsValueOS], 0)), 0)) AS [OSInvoices],
               CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[FeesOS], 0)), 0)) AS [OSFees],
               ISNULL(SUM(CASE WHEN TRN.[TransDate] IS NULL
                                    THEN 0
                               WHEN TRN.[TransDate] > @GETDATE
                                    THEN 0
                               WHEN TRN.[DebtorsValueOS] = 0
                                    THEN 0
                               ELSE DATEDIFF(Day, TRN.[TransDate], @GETDATE) END), 0) AS [DebtorDays],
               ISNULL(SUM(CASE WHEN TRN.[TransDate] IS NULL
                                    THEN 0
                               WHEN TRN.[TransDate] > @GETDATE
                                    THEN 0
                               WHEN TRN.[DebtorsValueOS] = 0
                                    THEN 0
                               ELSE 1 END), 0) AS [DebtorEntries]
          FROM [dbo].[matters] AS MAT
               INNER JOIN [dbo].[Transactions] TRN
                       ON MAT.[Code] = TRN.[MatterCode]
         WHERE TRN.[Posted] = ''Y''
           AND MAT.[FECode] = @Handler
           AND TRN.[CorrectionInd] = ''L''
           AND TRN.[DebtorsValueOS] > 0
           AND ((TRN.[XnType] = ''I'' AND TRN.[RecType] = ''H'')
             OR (TRN.[XnType] = ''J'' AND TRN.[RecType] = ''D''))) DT'

    EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @GETDATE DATETIME, @OSInvoices DECIMAL(19, 2) OUTPUT, @OSFees DECIMAL(19, 2) OUTPUT, @AVGDDays INT OUTPUT', @Handler = @Handler, @GETDATE = @GETDATE, @OSInvoices = @OSInvoices OUTPUT, @OSFees = @OSFees OUTPUT, @AVGDDays = @AVGDDays OUTPUT
  END

DECLARE @WIP DECIMAL(19, 2)

-- Pino 2015-05-26 - Please make sure that this calculation exactly mirrors the corresponding one
--                   in [dbo].[KAAS_DashboardCaseAlert] - if either is changed, change the other one
--                   accordingly
-- John 2016-01-25 - Made query match the one in KAAS_DashboardCaseAlert
IF @IsSAM4 = 0
  BEGIN
    --SELECT @WIP = ISNULL(SUM(ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0)), 0)
    --  FROM [dbo].[TimeEntry] TIE
    --       INNER JOIN [dbo].[matters] MAT
    --               ON MAT.[Code] = TIE.[Matter]
    --              AND MAT.[Closed] = 'N'
    -- WHERE TIE.[FeeEarn] = @Handler
    --   AND TIE.[Rec_Irr] <> 'N'
    --   AND TIE.[Matter] <> '~'
    --   AND (   TIE.[TimeOrCharge] = 'T'
    --        OR TIE.[TimeOrCharge] = 'C')
    SELECT @WIP = ISNULL(SUM(WP.[WIP]), 0)
      FROM (  SELECT TIE.[Matter],
                     ISNULL(SUM(ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0)), 0) AS [WIP]
                FROM [dbo].[TimeEntry] TIE
                     INNER JOIN [dbo].[matters] MAT
                             ON MAT.[Code] = TIE.[Matter]
                            AND MAT.[Closed] = 'N'
               WHERE TIE.[FeeEarn] = @Handler
                 AND TIE.[Rec_Irr] <> 'N'
                 AND TIE.[Matter] <> '~'
                 AND (   TIE.[TimeOrCharge] = 'T'
                      OR TIE.[TimeOrCharge] = 'C')
            GROUP BY TIE.[Matter]) WP
          INNER JOIN [dbo].[matters] MT2
                     INNER JOIN [dbo].[Contacts] CON
                                ON CON.[Code] = MT2.[ClientCode]
                  ON MT2.[Code] = WP.[Matter]
  END
ELSE
  BEGIN
    --SELECT @WIP = ISNULL(SUM(CASE WHEN TIE.[InvoiceNo] = 0
    --                                   THEN ISNULL(TIE.[Charge], 0)
    --                              ELSE 0 END), 0)
    --  FROM [dbo].[TimeEntry] TIE
    --       INNER JOIN [dbo].[matters] MAT
    --               ON MAT.[Code] = TIE.[Matter]
    --              AND MAT.[Closed] = 'N'
    -- WHERE TIE.[FeeEarn] = @Handler
    --   AND TIE.[Rec_Irr] <> 'N'
    --   AND TIE.[Matter] <> '~'
    --   AND (   TIE.[TimeOrCharge] = 'T'
    --        OR TIE.[TimeOrCharge] = 'C')
    SELECT @WIP = ISNULL(SUM(WP.[WIP]), 0)
      FROM (  SELECT TIE.[Matter],
                     ISNULL(SUM(CASE WHEN TIE.[InvoiceNo] = 0
                                     THEN ISNULL(TIE.[Charge], 0)
                                     ELSE 0 END), 0)                                         AS [WIP]
                FROM [dbo].[TimeEntry] TIE
                     INNER JOIN [dbo].[matters] MAT
                             ON MAT.[Code] = TIE.[Matter]
                            AND MAT.[Closed] = 'N'
               WHERE TIE.[FeeEarn] = @Handler
                 AND TIE.[Rec_Irr] <> 'N'
                 AND TIE.[Matter] <> '~'
                 AND (   TIE.[TimeOrCharge] = 'T'
                      OR TIE.[TimeOrCharge] = 'C')
            GROUP BY TIE.[Matter]) WP
          INNER JOIN [dbo].[matters] MT2
                     INNER JOIN [dbo].[Contacts] CON
                             ON CON.[Code] = MT2.[ClientCode]
                  ON MT2.[Code] = WP.[Matter]
  END

-- Pino 2015-06-24 Start
DECLARE @OutlayBalance DECIMAL(19, 2)

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = N'
SELECT @OutlayBalance = ISNULL(SUM(ISNULL(MAT.[OutlayBal], 0)), 0)
  FROM [dbo].[matters] MAT
 WHERE MAT.[FECode] = @Handler
   AND MAT.[Closed] <> ''Y'''
  END
ELSE
  BEGIN
    SET @NCOMMAND = N'
SELECT @OutlayBalance = ISNULL(SUM(ISNULL(OBL.[OutlayBalance], 0)), 0)
  FROM (  SELECT MAT.[Code],
                 ISNULL(SUM(ISNULL(TRN.[OutlayValue], 0)), 0) AS [OutlayBalance]
            FROM [dbo].[matters] MAT
                 INNER JOIN [dbo].[Transactions] TRN
                         ON TRN.[MatterCode] = MAT.[Code]
                        AND (   (    (TRN.[Posted] = ''Y'')
                                 AND (TRN.[RecType] <> ''V'')
                                 AND (TRN.[CorrectionInd] = ''L''))
                             OR (    (TRN.[Posted] IS NULL)
                                 AND (TRN.[RecType] IS NULL)
                                 AND (TRN.[CorrectionInd] IS NULL)))
           WHERE MAT.[FECode] = @Handler
             AND MAT.[Closed] <> ''Y''
        GROUP BY MAT.[Code]) OBL'
  END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @OutlayBalance DECIMAL(19, 2) OUTPUT', @Handler = @Handler, @OutlayBalance = @OutlayBalance OUTPUT
-- Pino 2015-06-24 END

--Statement to get OS fee and invoice
SELECT REPLACE(CONVERT(VARCHAR,CAST(ROUND(@OSInvoices,0) AS MONEY),1),'.00','')  AS [OSInvoice],
       REPLACE(CONVERT(VARCHAR,CAST(ROUND(@OSFees,0) AS MONEY),1),'.00','') AS [OSFees],
       REPLACE(CONVERT(VARCHAR,CAST(ROUND(@AVGDDays,0) AS MONEY),1),'.00','') AS [AverageDebtorsDays],
       REPLACE(CONVERT(VARCHAR,CAST(ROUND(@WIP,0) AS MONEY),1),'.00','') AS [CurrentWIP],
       REPLACE(CONVERT(VARCHAR,CAST(ROUND(@DraftInvoice,0) AS MONEY),1),'.00','') AS [DraftInvoice],
       REPLACE(CONVERT(VARCHAR,CAST(ROUND((@OSInvoices + @OutlayBalance + @WIP),0) AS MONEY),1),'.00','') AS [CurrentLookupValue], --Pino 2015-09-29
       REPLACE(CONVERT(VARCHAR,CAST(ROUND(@OutlayBalance,0) AS MONEY),1),'.00','') AS [OutlayBalance] --Added Pino 2015-06-24

DECLARE @Open INT
DECLARE @Dormant INT
DECLARE @Expectinvoice INT
DECLARE @Noestimatefee INT
DECLARE @Approachingestimatedfee INT
DECLARE @Lockedupvalue INT
DECLARE @Noestimategiven INT
DECLARE @MoneyLaunderingchecks INT
DECLARE @EffectivelyCompleted INT

DECLARE @EstFeeWarningLimit DECIMAL(19, 2)
DECLARE @LockupUpValue      DECIMAL(19, 2)

SELECT @EstFeeWarningLimit = CONVERT(DECIMAL(19, 2), ISNULL([SET].[KeyValue], '0'))
  FROM [dbo].[Settings] [SET]
 WHERE [SET].[KeyName] = 'EstFeeWarningLimit'

SET @EstFeeWarningLimit = ISNULL(@EstFeeWarningLimit, 0)

SELECT @LockupUpValue = CONVERT(DECIMAL(19, 2), ISNULL([SET].[KeyValue], '0'))
  FROM [dbo].[Settings] [SET]
 WHERE [SET].[KeyName] = 'LockupUpValue'

SET @LockupUpValue = ISNULL(@LockupUpValue, 0)

SELECT @Open = ISNULL(SUM(CASE WHEN MAT.[Closed] = 'Y'
                                    THEN 0
                               WHEN MAT.[ClientCode] = 'ZZZZZZ'
                                    THEN 0
                               WHEN isnumeric(MAT.[matter]) = 0 --system matters like ZZZZZZ/ZZZ2
                                    THEN 0
                               WHEN convert(int, MAT.[matter]) = 0 --ignore "0" matter
                                    THEN 0
                               ELSE 1 END), 0),
       @Expectinvoice = ISNULL(SUM(CASE WHEN MAT.[ExpBillD] <= @GETDATE
                                             THEN 1
                                        ELSE 0 END), 0),
       @Noestimatefee = ISNULL(SUM(CASE WHEN isnumeric(MAT.[matter]) = 0 --system matters like ZZZZZZ/ZZZ2
                                             THEN 0
                                        WHEN convert(int, MAT.[matter]) = 0 --ignore "0" matter
                                             THEN 0
                                        WHEN MAT.[EstFee] = 0
                                             THEN 1
                                        ELSE 0 END), 0),
       @Approachingestimatedfee = ISNULL(SUM(CASE WHEN (COALESCE ((ISNULL(MAT.[ChargeBal], 0) / NULLIF (MAT.[EstFee], 0) * 100), 0)) > @EstFeeWarningLimit
                                                       THEN 1
                                                  ELSE 0 END), 0),
       @Lockedupvalue = ISNULL(SUM(CASE WHEN (MAT.[ChargeBal] + MAT.[DebtBal] + MAT.[OutlayBal]) > @LockupUpValue
                                             THEN 1
                                        ELSE 0 END), 0),
       @Noestimategiven = ISNULL(SUM(CASE WHEN isnumeric(MAT.[matter]) = 0 --system matters like ZZZZZZ/ZZZ2
                                               THEN 0
                                          WHEN convert(int, MAT.[matter]) = 0 --ignore "0" matter
                                               THEN 0
                                          WHEN MAT.[Section68] = 'Y'
                                               THEN 0
                                          ELSE 1 END), 0),
       @EffectivelyCompleted=ISNULL(SUM(CASE WHEN isnumeric(MAT.[matter]) = 0 --system matters like ZZZZZZ/ZZZ2
                                                  THEN 0
                                             WHEN convert(int, MAT.[matter]) = 0 --ignore "0" matter
                                                  THEN 0
                                             WHEN ISNULL(MAT.PCODE, '') = '' AND ISNULL(PFECODE, '') = ''
                                                  THEN 1
                                             ELSE 0 END),0)
  FROM [dbo].[matters] MAT
 WHERE MAT.[FECode] = @Handler
   AND MAT.Closed <> 'Y'

DECLARE @MATTERS TABLE ([Code] VARCHAR(20), [LastActionDate] DATETIME)

INSERT INTO @MATTERS ([Code], [LastActionDate])
EXEC @Dormant = [dbo].[KEYHM_GetDormantMatters] @Handler

SELECT @MoneyLaunderingchecks = COUNT(DISTINCT CON.[CODE])
  FROM [dbo].[Contacts] CON
       INNER JOIN [dbo].[matters] MAT
               ON MAT.[ClientCode] = CON.[Code]
              AND MAT.[Closed] <> 'Y'
 WHERE CON.[FE] = @Handler
   AND ISNULL(CON.[Approved], 0) <> 1

SELECT ISNULL(@Open, 0)                    AS [OpenMatters],
       ISNULL(@Dormant, 0)                 AS [MyDormantMatters],
       ISNULL(@Expectinvoice, 0)           AS [NoCaseWhereExpectInvoiceDateHasPassed],
       ISNULL(@Noestimatefee, 0)           AS [NoCaseWithNoEstimateFee],
       ISNULL(@Approachingestimatedfee, 0) AS [NoCaseApproachingEstimatedFee],
       ISNULL(@Lockedupvalue, 0)           AS [NoCaseApproachingLockedUpValue],
       ISNULL(@MoneyLaunderingchecks, 0)   AS [NoClientsThatRequireMoneyLaunderingChecks],
       ISNULL(@Noestimategiven, 0)         AS [NoCasesWithNoEstimateGiven],
       ISNULL(@EffectivelyCompleted, 0)    AS [NoCasesEffectivelyComplete]
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_DashboardCaseAlert'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_DashboardCaseAlert]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_DashboardCaseAlert]
      (@Handler			VARCHAR(10),
       @Function		VARCHAR(50),
	   @PageNumber		INT,
	   @PageSize		INT,
	   @SearchText		VARCHAR(100),
	   @SortColumn		VARCHAR(20),
	   @SortDirection	VARCHAR(10))
AS
/*******************************************************************************************************************************************************
 *
 * Retrieves Detailed information for the entries displayed on the Dashboard (My Overview) page
 *
 * Stored Procedure Name : KEYHM_DashboardCaseAlert
 * Copied From           : ky_NETDashboardCaseAlert
 *
 * Pino           2014-11-19 - changed statements for Open Matters and Dormant Matters.
 *                             assigned task to review remaining select statements
 *			      
 * Magesh         2015-05-05 - Changed conditions to get data more specifically
 *			      
 * Pino           2015-05-26 - SAM4 calculations
 *			      
 * Pino           2015-06-24 - Include Outlay Balance
 *			      
 * Pino           2015-06-25 - Fix drilldown for Clients Requiring Money Laundering Checks
 *                             Exclude zero balances from Outlay Balance drilldown
 *			      
 * Magesh         2015-08-31 - Added condition to the query used to find out @TotalStatuteLimits to exculed min date values '1900-01-01'
 *			      
 * Magesh         2015-09-15 - Added three more function for fees for current month , last month and year to date.
 *			      
 * Magesh         2015-10-10 - Added three more funtions to show timedaybook and time enty for week,month and year.
 *			      
 * Magesh         2015-10-09 - Added three more funtions to show Admin time enty for week,month and year.
 *			      
 * Magesh         2015-10-16 - Added extra funtions to show effectively complete matters.
 * 			      
 * John           2015-11-09 - Fixed function 'TimeDayBookforWeek' looking for 'ADM' handler instead of @Handler
 *			      
 * John           2015-11-19 - KEYD-2939 - Changed the inner join from batchdetails to matters to now be 
 *		   	        	          batchh to matters
 * John           2015-11-25 - KEYD-2943 - Wrapped a number of financial figures in new function )
 *			      
 * John           2016-01-11 - Undid previous change as the VB .NET handles this now. 
 *                             It was also messing up totals for the figures (e.g. can't add "(-123.45)" to "512.12")
 *                             Also excluding matters with no WIP from the WIP drill down
 *			      
 * John           2016-02-02 - Now excluding close matters from undertakings and statute approaching
 *                             http://jira1.dsrc.in:8080/browse/KEYD-3158
 *			      
 * Arun           2016-02-05 - Specified the Varchar size
 *			      
 * Pino           2016-04-11 - Ignore No Estimate Fee calculation for system matters like ZZZZZZ/ZZZ2 and 
 *                             for the "zero" matters
 *			      
 * Pino           2016-04-12 - Exclude further "zero" matters
 *			      
 * Suriya         2016-04-26 - KEYD-3536-In the My Overview page the "Admin time recorded this week" drill down list is not showing any details.
 *			      
 * Arun           2016-05-16 - Have added OSFees and Debtors Days in Dashboard alert
 *			      
 * John           2016-08-02 - Code refactor
 *			      
 * Sridharan      2016-08-16 - KEYD:3591: In  "My over view" page the "Fee" column of the Fees issued Year to Date 
 *                             drill down list is displayed wrong.
 *			      
 * John           2016-09-26 - KEYD-4090 Fees issued must now be posted before appearing in My Overview
 *			      
 * John           2017-03-20 - Added Last Year and Last Year to Date functions
 *                             Also serious overhaul of some queries
 *			      
 * John           2017-03-27 - Fixed getdate not being passed into SQL statement
 *                             Corrected SAM3 Fees Last Year (to Date) clause so it looks at last year, not next
 *			      
 * Pino           2017-03-28 - Fixed use of ISNULL(RTRIM(
 *			      
 * John           2017-06-06 - Time for this year now only looks at chargeable time (to be consistent with other time frames)
 *			      
 * Pino           2017-06-15 - Fixed calculation for Debtors Days - @GETDATE not passed in.
 *			      
 * John           2017-10-26 - Fixed potential mismatch with ky_NETDashboard_v2
 *			      
 * John           2018-10-25 - KEYD-5519: Made date check for dormant matters consistent with warning on diary (using setting now)
 *			      
 * John           2018-11-05 - Dormant check now only looks at complete actions
 *			      
 * John           2018-11-08 - Dormant check looks at any activity in diary, time ledger, matter ledger and undertakings
 *			      
 * John           2018-11-09 - Fixed Outstanding Fees window not showing anything - KEYD-5558
 *			      
 * John           2018-11-12 - Fixed SAM4 debtors days not showing anything - KEYD-5558
 *			      
 * John           2018-12-06 - Added return for "DraftInvoices" - KEYD-5563
 *
 * Vinodhan K     2019-18-07 - Added KAAS_DashboardCaseAlert
 *******************************************************************************************************************************************************/
BEGIN
 SET NOCOUNT ON

DECLARE @NCOMMAND     NVARCHAR(MAX)
DECLARE @TODAYNUM     INT
DECLARE @MONDAY       DATETIME
DECLARE @STARTOFMONTH DATETIME
DECLARE @STARTOFYEAR  DATETIME
DECLARE @MONTHTODATE  DATETIME
DECLARE @GETDATE      DATETIME

SELECT @GETDATE = GETDATE()

SELECT @STARTOFMONTH = KPI.[FromDate],
       @STARTOFYEAR  = KPI.[StartOfYear],
	   @MONTHTODATE  = CASE WHEN @GETDATE > KPI.[ToDate] THEN KPI.[ToDate] ELSE @GETDATE END
  FROM [dbo].[KPIParameters] AS KPI

SELECT @STARTOFYEAR = ISNULL(@STARTOFYEAR, CONVERT(DATETIME, CONVERT(VARCHAR(4), YEAR(@GETDATE)) + '0101')),
       @TODAYNUM = DATEPART(WEEKDAY, @GETDATE) - DATEPART(WEEKDAY, '20000102') --the 2nd of January, 2000 was a Monday

IF @TODAYNUM <= 0
  SET @TODAYNUM = @TODAYNUM + 7

SET @MONDAY = CONVERT(DATETIME, CONVERT(VARCHAR, DATEADD(DAY, 1 - @TODAYNUM, @GETDATE), 112))

SELECT @FUNCTION = UPPER(ISNULL(@FUNCTION, ''))

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 @FUNCTION = 'OPENMATTER'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#OpenMatterTable
	FROM
	(SELECT RTRIM(ISNULL(MAT.[Code], ''))        AS [Code],
           RTRIM(ISNULL(CON.[Name], ''))         AS [Name],
           RTRIM(ISNULL(MAT.[Description], ''))  AS [Description]
      FROM [dbo].[matters] MAT
           LEFT OUTER JOIN [dbo].[Contacts] CON
                        ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
	   )
	   AND MAT.[FECode] = @Handler
       AND MAT.[ClientCode] <> 'ZZZZZZ'
       AND CASE WHEN ISNUMERIC(MAT.[matter]) = 0
                     THEN 1
                WHEN CONVERT(INT, MAT.[matter]) = 0
                     THEN 1
                ELSE 0 END = 0
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#OpenMatterTable
END
ELSE IF @FUNCTION = 'EFFECTIVELYCOMPLETE'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#EffectivelyCompleteTable
	FROM
	(SELECT RTRIM(ISNULL(MAT.[Code], ''))       AS [Code],
           RTRIM(ISNULL(CON.[Name], ''))        AS [Name],
           RTRIM(ISNULL(MAT.[Description], '')) AS [Description]
      FROM [dbo].[matters] AS MAT
           LEFT OUTER JOIN [dbo].[Contacts] AS CON
                        ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
	   )
	   AND [MAT].[FECode] = @Handler
       AND ISNULL(MAT.[PCODE], '') = ''
       AND ISNULL(MAT.[PFECODE], '') = ''
       AND CASE WHEN ISNUMERIC(MAT.[matter]) = 0
                     THEN 1
                WHEN CONVERT(INT, MAT.[matter]) = 0
                     THEN 1
                ELSE 0 END = 0
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#EffectivelyCompleteTable
END
ELSE IF @FUNCTION = 'DORMANTMATTER'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

    DECLARE @MATTERS TABLE ([Code] VARCHAR(20), [LastActionDate] DATETIME)

    INSERT INTO @MATTERS ([Code], [LastActionDate])
    EXEC [dbo].[KEYHM_GetDormantMatters] @Handler

    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#DormantMatterTable
	FROM
	(SELECT MAT.[Code]                            AS [Code],
           ISNULL(RTRIM([CNT].[Name]), '')        AS [Name],
           ISNULL(RTRIM([MAT].[Description]), '') AS [Description],
           TMP.[LastActionDate]
      FROM [dbo].[matters] AS MAT
           LEFT OUTER JOIN [dbo].[Contacts] AS CNT
                        ON MAT.[ClientCode] = CNT.[Code]
           INNER JOIN @MATTERS AS TMP
                   ON MAT.[Code] = TMP.[Code]
	 WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CNT].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
	   )) AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#DormantMatterTable
END
ELSE IF @FUNCTION = 'INVOICEDATEPASSED'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#InvoiceDatePassedTable
	FROM
	(SELECT MAT.[Code]                          AS [Code],
	       RTRIM(ISNULL(CON.[Name], ''))        AS [Name],
	       RTRIM(ISNULL(MAT.[Description], '')) AS [Description],
	       MAT.[ExpBillD]                       AS [ExpectedBillDate],
	       ISNULL(MAT.[EstFee], 0)              AS [EstimatedFee],
	       ISNULL(MAT.[ChargeBal], 0)           AS [WIP]
      FROM [dbo].[matters] AS MAT
           LEFT JOIN [dbo].[Contacts] AS CON
                  ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[ExpBillD] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[EstFee] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[ChargeBal] LIKE '%' + @SearchText + '%'
	   )
	   AND MAT.[FECode] = @Handler
       AND MAT.[ExpBillD] <= @GETDATE
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'ExpectedBillDate'   THEN [ExpectedBillDate]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'ExpectedBillDate'   THEN [ExpectedBillDate]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'EstimatedFee' THEN [EstimatedFee]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'EstimatedFee'   THEN [EstimatedFee]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'WIP'   THEN [WIP]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'WIP'   THEN [WIP]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#InvoiceDatePassedTable
END
ELSE IF @FUNCTION = 'NOESTIMATEFEE'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#NoEstimateFeeTable
	FROM
	(SELECT MAT.[Code]                          AS [Code],
	       RTRIM(ISNULL(CON.[Name], ''))        AS [Name],
	       RTRIM(ISNULL(MAT.[Description], '')) AS [Description]
      FROM [dbo].[matters] AS MAT
           LEFT OUTER JOIN [dbo].[Contacts] AS CON
                        ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
	   )
	   AND MAT.[FECode] = @Handler
       AND CASE WHEN ISNUMERIC(MAT.[matter]) = 0
                     THEN 1
                WHEN CONVERT(INT, MAT.[matter]) = 0
                     THEN 1
                ELSE MAT.[EstFee] END = 0
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#NoEstimateFeeTable
END
ELSE IF @FUNCTION = 'APPROACHINGESTIMATEFEE'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#ApproachingEstimateFeeTable
	FROM
	(SELECT MAT.[Code]                         AS [Code],
	       RTRIM(ISNULL(CON.[Name],''))        AS [Name],
	       RTRIM(ISNULL(MAT.[Description],'')) AS [Description],
	       ISNULL(EstFee,0)                    AS [EstimatedFee],
	       ISNULL(ChargeBal,0)                 AS [WIP],
	       CAST(CAST((COALESCE((ISNULL(MAT.[ChargeBal], 0) / NULLIF(MAT.[EstFee], 0) * 100), 0)) AS DECIMAL(18,2)) AS VARCHAR(100)) + '%' AS [PercentageOfEstimatedFee]
      FROM [dbo].[matters] AS MAT
           LEFT OUTER JOIN [dbo].[Contacts] AS CON
                        ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[Name] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[EstFee] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[ChargeBal] LIKE '%' + @SearchText + '%'
		OR
		(CAST(CAST((COALESCE((ISNULL(MAT.[ChargeBal], 0) / NULLIF(MAT.[EstFee], 0) * 100), 0)) AS DECIMAL(18,2)) AS VARCHAR(100)) + '%') LIKE '%' + @SearchText + '%'
	   ) 
	   AND FECode = @Handler
       AND COALESCE((ISNULL(MAT.[ChargeBal], 0) / NULLIF(MAT.[EstFee], 0) * 100), 0) > (SELECT ISNULL([KeyValue], 0) FROM [dbo].[Settings] WHERE [KeyName] = 'EstFeeWarningLimit')
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'EstimatedFee'   THEN [EstimatedFee]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'EstimatedFee'   THEN [EstimatedFee]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'WIP' THEN [WIP]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'WIP'   THEN [WIP]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'PercentageOfEstimatedFee'   THEN [PercentageOfEstimatedFee]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'PercentageOfEstimatedFee'   THEN [PercentageOfEstimatedFee]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#ApproachingEstimateFeeTable
END
ELSE IF @FUNCTION = 'APPROACHINGLOCKEDUP'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#ApproachingLockedupTable
	FROM
	(SELECT MAT.[Code]                         AS [Code],
	       RTRIM(ISNULL(CON.[Name],''))        AS [Name],
	       RTRIM(ISNULL(MAT.[Description],'')) AS [Description]
      FROM [dbo].[matters] AS MAT
           LEFT OUTER JOIN [dbo].[Contacts] AS CON
                        ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
	   )
	   AND MAT.[FECode] = @Handler
       AND (ISNULL(MAT.[ChargeBal], 0) + ISNULL(MAT.[DebtBal], 0) + ISNULL(MAT.[OutlayBal], 0)) > (SELECT ISNULL([KeyValue], 0) FROM [dbo].[Settings] WHERE KeyName = 'LockupUpValue')
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#ApproachingLockedupTable
END
ELSE IF @Function='MONEYLANDERINGCHECKS'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#MoneyLanderingCheckTable
	FROM
	(
          -- Pino 2015-06-25 Rewrite START
          SELECT RTRIM(ISNULL(CON.[Code], ''))                                                    AS [ClientCode],
                 RTRIM(ISNULL(CON.[Name], ''))                                                    AS [Name],
                 [dbo].[ky_RemoveSpuriousWhitespace2](RTRIM(ISNULL(CON.[Address], '')), 200)      AS [Address],
                 RM.[Code]                                                                        AS [Code],
                 RM.[Description]                                                                 AS [Description]
            FROM [dbo].[Contacts] CON
                 -- Get code and description of most recently started matter for this client
                 -- Because it's a Cross Apply it works akin to an INNER JOIN so clients with
                 -- no open matters are automatically excluded.
                 CROSS APPLY (  SELECT TOP 1
                                       RTRIM(ISNULL(MAT.[Code], '')) AS [Code],
                                       RTRIM(ISNULL(MAT.[Description], '')) AS [Description]
                                  FROM [dbo].[matters] MAT
                                 WHERE MAT.[ClientCode] = CON.[Code]
                                   AND MAT.[Closed] <> 'Y'
                              ORDER BY MAT.[Started] DESC) RM
           WHERE
		     (
		       [CON].[Code] LIKE '%' + @SearchText + '%'
		       OR
		       [CON].[Name] LIKE '%' + @SearchText + '%'
		       OR
		       [dbo].[ky_RemoveSpuriousWhitespace2](RTRIM(ISNULL(CON.[Address], '')), 200) LIKE '%' + @SearchText + '%'
			   OR
			   [RM].[Code] LIKE '%' + @SearchText + '%'
			   OR
			   [RM].[Description] LIKE '%' + @SearchText + '%'
	         )
		     AND CON.[FE] = @Handler
             AND ISNULL(CON.[Approved], 0) <> 1
          -- Pino 2015-06-25 Rewrite END
		  ) AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'ClientCode'   THEN [ClientCode]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'ClientCode'   THEN [ClientCode]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Address'   THEN [Address]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Address'   THEN [Address]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#MoneyLanderingCheckTable
END
ELSE IF @Function='NOESTIMATEGIVEN'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#NoEstimateGivenTable
	FROM
	(SELECT RTRIM(ISNULL(MAT.[Code], ''))       AS [Code],
           RTRIM(ISNULL(CON.[Name], ''))        AS [Name],
           RTRIM(ISNULL(MAT.[Description], '')) AS [Description]
      FROM [dbo].[matters] MAT
           INNER JOIN [dbo].[Contacts] CON
                   ON CON.[Code] = MAT.[ClientCode]
     WHERE
	   (
		[MAT].[Code] LIKE '%' + @SearchText + '%'
		OR
		[CON].[NAME] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
	   )
	   AND MAT.[FECode] = @Handler
       AND ISNULL(MAT.[Section68], '') <> 'Y'
       AND CASE WHEN isnumeric(MAT.[matter]) = 0
                     THEN 1
                WHEN convert(int, MAT.[matter]) = 0
                     THEN 1
                ELSE 0 END = 0
       AND MAT.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name' THEN [Name]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Name'   THEN [Name]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#NoEstimateGivenTable
END
ELSE IF @Function='WIP'
    -- Pino 2015-05-26 - Please make sure that this calculation exactly mirrors the corresponding one
    --                   in [dbo].[Ky_NETDashBoard] - if either is changed, change the other one
    --                   accordingly
    BEGIN
	  IF(@SortColumn = '' OR @SortColumn = NULL)
	  BEGIN
	  	  SET @SortColumn = 'Code'
	  END
      IF(@SortDirection = '' OR @SortDirection = NULL)
	  BEGIN
	  	  SET @SortDirection = 'ASC'
	  END

      IF [dbo].[ISSAM4]() = 0
        BEGIN
          SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #WIPTable
	      FROM
	       (SELECT WP.[Matter]                             AS [Code],
                 RTRIM(ISNULL(CON.[NAME], ''))           AS [ClientName],
                 RTRIM(ISNULL(CON.[CODE], ''))           AS [ClientCode],
                 RTRIM(ISNULL(MT2.[Description], ''))    AS [Description],
                 WP.[WIP]								 AS [WIP],
                 WP.[LastTimeEntryDate]                  AS [LastTimeEntryDate]
            FROM (  SELECT TIE.[Matter],
                           ISNULL(SUM(ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0)), 0) AS [WIP],
                           MAX(TIE.[Date])                                                         AS [LastTimeEntryDate]
                      FROM [dbo].[TimeEntry] TIE
                           INNER JOIN [dbo].[matters] MAT
                                   ON MAT.[Code] = TIE.[Matter]
                                  AND MAT.[Closed] = 'N'
                     WHERE TIE.[FeeEarn] = @Handler
                       AND TIE.[Rec_Irr] <> 'N'
                       AND TIE.[Matter] <> '~'
                       AND (   TIE.[TimeOrCharge] = 'T'
                            OR TIE.[TimeOrCharge] = 'C')
                  GROUP BY TIE.[Matter]) WP
                 INNER JOIN [dbo].[matters] MT2
                            INNER JOIN [dbo].[Contacts] CON
                                    ON CON.[Code] = MT2.[ClientCode]
                         ON MT2.[Code] = WP.[Matter]
           WHERE
		   (
		    [WP].[Matter] LIKE '%' + @SearchText + '%'
		    OR
		    [CON].[NAME] LIKE '%' + @SearchText + '%'
		    OR
		    [CON].[CODE] LIKE '%' + @SearchText + '%'
			OR
			[MT2].[Description] LIKE '%' + @SearchText + '%'
			OR
			[WP].[WIP] LIKE '%' + @SearchText + '%'
			OR
			[WP].[LastTimeEntryDate] LIKE '%' + @SearchText + '%'
	       )
	       AND
	       WP.[WIP] <> 0) AS FoundTable
           ORDER BY
           CASE WHEN @SortDirection = 'ASC' THEN
             CASE @SortColumn 
                WHEN 'Code'   THEN [Code]
             END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'Code'   THEN [Code]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'ClientName' THEN [ClientName]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'ClientName'   THEN [ClientName]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'ClientCode'   THEN [ClientCode]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'ClientCode'   THEN [ClientCode]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'Description'   THEN [Description]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'Description'   THEN [Description]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'WIP'   THEN [WIP]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'WIP'   THEN [WIP]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'LastTimeEntryDate'   THEN [LastTimeEntryDate]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'LastTimeEntryDate'   THEN [LastTimeEntryDate]
              END
           END DESC

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

	      SELECT
	      	(COUNT([Row_Number])) As [TotalRecords]
	      FROM
	          #WIPTable
        END
      ELSE
        BEGIN
		  SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #WIPSamTable
	      FROM
	       (SELECT WP.[Matter]                           AS [Code],
                 RTRIM(ISNULL(CON.[NAME], ''))           AS [ClientName],
                 RTRIM(ISNULL(CON.[CODE], ''))           AS [ClientCode],
                 RTRIM(ISNULL(MT2.[Description], ''))    AS [Description],
                 WP.[WIP]                                AS [WIP],
                 WP.[LastTimeEntryDate]                  AS [LastTimeEntryDate]
            FROM (  SELECT TIE.[Matter],
                           ISNULL(SUM(CASE WHEN TIE.[InvoiceNo] = 0
                                           THEN ISNULL(TIE.[Charge], 0)
                                           ELSE 0 END), 0)                                         AS [WIP],
                           MAX(TIE.[Date])                                                         AS [LastTimeEntryDate]
                      FROM [dbo].[TimeEntry] TIE
                           INNER JOIN [dbo].[matters] MAT
                                   ON MAT.[Code] = TIE.[Matter]
                                  AND MAT.[Closed] = 'N'
                     WHERE TIE.[FeeEarn] = @Handler
                       AND TIE.[Rec_Irr] <> 'N'
                       AND TIE.[Matter] <> '~'
                       AND (   TIE.[TimeOrCharge] = 'T'
                            OR TIE.[TimeOrCharge] = 'C')
                  GROUP BY TIE.[Matter]) WP
                 INNER JOIN [dbo].[matters] MT2
                            INNER JOIN [dbo].[Contacts] CON
                                    ON CON.[Code] = MT2.[ClientCode]
                         ON MT2.[Code] = WP.[Matter]
           WHERE
		   (
		    [WP].[Matter] LIKE '%' + @SearchText + '%'
		    OR
		    [CON].[NAME] LIKE '%' + @SearchText + '%'
		    OR
		    [CON].[CODE] LIKE '%' + @SearchText + '%'
			OR
			[MT2].[Description] LIKE '%' + @SearchText + '%'
			OR
			[WP].[WIP] LIKE '%' + @SearchText + '%'
			OR
			[WP].[LastTimeEntryDate] LIKE '%' + @SearchText + '%'
	       )
	       AND
	       WP.[WIP] <> 0) AS FoundTable
           ORDER BY
           CASE WHEN @SortDirection = 'ASC' THEN
             CASE @SortColumn 
                WHEN 'Code'   THEN [Code]
             END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'Code'   THEN [Code]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'ClientName' THEN [ClientName]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'ClientName'   THEN [ClientName]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'ClientCode'   THEN [ClientCode]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'ClientCode'   THEN [ClientCode]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'Description'   THEN [Description]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'Description'   THEN [Description]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'WIP'   THEN [WIP]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'WIP'   THEN [WIP]
              END
           END DESC,
           CASE WHEN @SortDirection = 'ASC' THEN
              CASE @SortColumn 
                 WHEN 'LastTimeEntryDate'   THEN [LastTimeEntryDate]
              END
           END,
           CASE WHEN @SortDirection = 'DESC' THEN
              CASE @SortColumn 
                 WHEN 'LastTimeEntryDate'   THEN [LastTimeEntryDate]
              END
           END DESC

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

	      SELECT
	      	(COUNT([Row_Number])) As [TotalRecords]
	      FROM
	          #WIPSamTable
        END
    END
ELSE IF @Function='OSINVOICE'
    -- Pino 2015-05-26 - Please make sure that this calculation exactly mirrors the corresponding one
    --                   in [dbo].[Ky_NETDashBoard] - if either is changed, change the other one
    --                   accordingly
 BEGIN
	  IF(@SortColumn = '' OR @SortColumn = NULL)
	  BEGIN
	  	SET @SortColumn = 'Row_Number'
	  END
      IF(@SortDirection = '' OR @SortDirection = NULL)
	  BEGIN
	  	SET @SortDirection = 'ASC'
	  END

      IF [dbo].[ISSAM4]() = 0
        BEGIN
          SET @NCOMMAND = N'
          SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #OSInvoiceSAM3Table
	      FROM
	     (SELECT RTRIM(ISNULL(DLG.[Ref], ''''))                   AS [InvoiceRef],
               RTRIM(ISNULL(DLG.[MATTER], ''''))                  AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))                    AS [ClientName],
               RTRIM(ISNULL(MAT.[Description],''''))              AS [Description],
               ISNULL(CONVERT(VARCHAR,DLG.[DATE],106),'''')       AS [InvoiceDate],
               CONVERT(DECIMAL(19, 2), DLG.OSVALUE)               AS [Outstanding],
               DATEDIFF(dd, DLG.[DATE], @GETDATE)                 AS [DaysOld]
          FROM [dbo].[matters] MAT
               INNER JOIN [dbo].[DebtorsLedger] DLG
                       ON DLG.[MATTER] = MAT.[Code]
                      AND DLG.[OSVALUE] > 0
               INNER JOIN [dbo].[Contacts] CON
                       ON CON.[Code] = MAT.[ClientCode]
         WHERE
		 (
	      RTRIM(LTRIM(@SearchText)) = ''''
	      OR
	      (
		  [DLG].[Ref] LIKE ''%' + @SearchText + '%''
		  OR
		  [DLG].[MATTER] LIKE ''%' + @SearchText + '%''
		  OR
		  [CON].[Name] LIKE ''%' + @SearchText + '%''
		  OR
		  [MAT].[Description] LIKE ''%' + @SearchText + '%''
		  OR
		  [DLG].[DATE] LIKE ''%' + @SearchText + '%''
		  OR
		  [DLG].[OSVALUE] LIKE ''%' + @SearchText + '%''
	      )
		 )
		 AND
		 MAT.[FECode] = @Handler) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #OSInvoiceSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #OSInvoiceSAM3Table'
        END
      ELSE
        BEGIN
          SET @NCOMMAND = N'
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #OSInvoiceSAM4Table
	      FROM
	     (SELECT TRN.[OutlayBill] AS [InvoiceRef],
               TRN.[MatterCode] AS [Code],
               RTRIM(ISNULL(CON.[Name], '''')) AS [ClientName],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Description],
               CONVERT(VARCHAR, TRN.[TransDate], 106) AS [InvoiceDate],
               CONVERT(DECIMAL(19, 2), ISNULL(TRN.[DebtorsValueOS], 0)) AS [Outstanding],
               CASE WHEN TRN.[TransDate] IS NULL
                         THEN 0
                    WHEN TRN.[TransDate] > @GETDATE
                         THEN 0
                    WHEN TRN.[DebtorsValueOS] = 0
                         THEN 0
                    ELSE DATEDIFF(Day, TRN.[TransDate], @GETDATE) END AS [DaysOld]
          FROM [dbo].[Transactions] TRN
               LEFT OUTER JOIN [dbo].[matters] MAT
                               INNER JOIN [dbo].[contacts] CON
                                       ON CON.[Code] = MAT.[ClientCode]
                            ON MAT.[code] = TRN.[MatterCode]
         WHERE
		    (
	          RTRIM(LTRIM(@SearchText)) = ''''
	          OR
	          (
		      [TRN].[OutlayBill] LIKE ''%' + @SearchText + '%''
		      OR
		      [TRN].[MatterCode] LIKE ''%' + @SearchText + '%''
		      OR
		      [CON].[Name] LIKE ''%' + @SearchText + '%''
		      OR
		      [MAT].[Description] LIKE ''%' + @SearchText + '%''
		      OR
		      [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
		      OR
		      [TRN].[DebtorsValueOS] LIKE ''%' + @SearchText + '%''
	          )
		    )
		   AND TRN.[Posted] = ''Y''
           AND TRN.[FeeEarner] = @Handler
           AND TRN.[CorrectionInd] = ''L''
           AND (   (    TRN.[XnType] = ''I''
                    AND TRN.[RecType] = ''H'')
                OR (    TRN.[XnType] = ''J''
                    AND TRN.[RecType] = ''D''))
           AND TRN.[DebtorsValueOS] > 0) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #OSInvoiceSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #OSInvoiceSAM4Table'
        END

      EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @GETDATE DATETIME, @SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @Handler = @Handler, @GETDATE = @GETDATE, @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
    END
 ELSE IF @Function='UNDERTAKINGS'
  BEGIN
        IF(@SortColumn = '' OR @SortColumn = NULL)
	    BEGIN
	    	SET @SortColumn = 'Code'
	    END
        IF(@SortDirection = '' OR @SortDirection = NULL)
	    BEGIN
	    	SET @SortDirection = 'ASC'
	    END
	    
        SELECT 
	    	IDENTITY(INT, 1,1) AS [Row_Number],
	    	*
	    INTO
	    	#UndertakingTable
	    FROM
	    (SELECT
            RTRIM(ISNULL(UND.MATTER,'')) AS Code,
            RTRIM(ISNULL(Contacts.[Name],'')) AS ClientName,
            RTRIM(ISNULL(M.[Description],'')) AS [Description],
            CASE
            WHEN UND.UNDDATE IS NULL THEN ''
            WHEN CONVERT(VARCHAR(11),UND.UNDDATE,23)='19000101' THEN ''
            ELSE CONVERT(VARCHAR(11),UND.UNDDATE ,20)
            END AS [Date]
        FROM
            dbo.[Undertakings] UND
                LEFT JOIN
            Matters AS M
        ON
            UND.MATTER = M.Code
                LEFT JOIN
            Contacts
        ON
            M.ClientCode = Contacts.Code
        WHERE
		    (
		     [UND].[MATTER] LIKE '%' + @SearchText + '%'
		     OR
		     [Contacts].[Name] LIKE '%' + @SearchText + '%'
		     OR
		     [M].[Description] LIKE '%' + @SearchText + '%'
	        )
			AND
              UND.[AuthorisedByFE] = @Handler
            AND
              UND.[DISCHARGEDATE] IS NULL
            AND M.[Closed] <> 'Y') AS FoundTable
	    ORDER BY
	    CASE WHEN @SortDirection = 'ASC' THEN
		     CASE @SortColumn 
		     	  WHEN 'Code'   THEN [Code]
		     END
	    END,
	    CASE WHEN @SortDirection = 'DESC' THEN
	    	  CASE @SortColumn 
	    	  	  WHEN 'Code'   THEN [Code]
	    	  END
	    END DESC,
	    CASE WHEN @SortDirection = 'ASC' THEN
	    	  CASE @SortColumn 
	    	  	  WHEN 'ClientName' THEN [ClientName]
	    	  END
	    END,
	    CASE WHEN @SortDirection = 'DESC' THEN
	    	  CASE @SortColumn 
	    	  	  WHEN 'ClientName'   THEN [ClientName]
	    	  END
	    END DESC,
	    CASE WHEN @SortDirection = 'ASC' THEN
	    	  CASE @SortColumn 
	    	  	  WHEN 'Description'   THEN [Description]
	    	  END
	    END,
	    CASE WHEN @SortDirection = 'DESC' THEN
	    	  CASE @SortColumn 
	    	  	  WHEN 'Description'   THEN [Description]
	    	  END
	    END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
	    #UndertakingTable
 END
 ELSE IF @Function='STATUTEDATE'
  BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Code'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#StatuteDateTable
	FROM
	(SELECT
            RTRIM(ISNULL(M.Code,''))          AS [Code],
            RTRIM(ISNULL(Contacts.[Name],'')) AS [ClientName],
            RTRIM(ISNULL(M.[Description],'')) AS [Description],
            CASE
            WHEN M.StatuteLimits  IS NULL THEN ''
            WHEN CONVERT(VARCHAR(11),M.StatuteLimits,23)='19000101' THEN ''
            ELSE CONVERT(VARCHAR(11),M.StatuteLimits ,20)
            END AS [Date]
        FROM
            Matters AS M
                INNER JOIN
            Contacts
        ON
            M.ClientCode = Contacts.Code
        WHERE
		    (
		     [M].[Code] LIKE '%' + @SearchText + '%'
		     OR
		     [Contacts].[Name] LIKE '%' + @SearchText + '%'
		     OR
		     [M].[Description] LIKE '%' + @SearchText + '%'
	        )
		AND
            M.FECode = @Handler
        AND
            DATEDIFF(DD, @GETDATE, CASE WHEN ISNULL(M.[StatuteLimits], '21000101')='19000101' THEN '21000101' ELSE M.[StatuteLimits] END) <= 60
        AND
		    M.[Closed] <> 'Y') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'ClientName' THEN [ClientName]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'ClientName'   THEN [ClientName]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) As [TotalRecords]
	FROM
		#StatuteDateTable
  END
ELSE IF @Function='OUTLAYBALANCE'
       BEGIN
         EXEC [dbo].[KEYHM_OutlayBalanceDrilldown] @Handler, @PageNumber, @PageSize, @SearchText, @SortColumn, @SortDirection
       END
ELSE IF @Function='Fees Issued Current Month'
BEGIN
    -- Rewrite by John START
    -- KEYD-3505
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
	  SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
	  SET @SortDirection = 'ASC'
	END

    IF [dbo].[ISSAM4]() = 0
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #FeeIssuedCurrentMonthSAM3Table
	   FROM
	   (SELECT RTRIM(ISNULL(MAT.[Code], ''''))        AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(BAD.[VALUE], 0) *
			   CASE WHEN ISNULL(BAH.[INVCR], '''') = ''C''
			             THEN -1
			        ELSE 1 END                        AS [Fee],
               RTRIM(ISNULL(BAD.[REF], ''''))         AS [Ref],
               RTRIM(ISNULL(BAD.[NARR], ''''))        AS [Narrative],
               BAD.[DATE]                             AS [Date]
        FROM [dbo].[BatchDetails] AS BAD
             INNER JOIN [dbo].[BatchH] AS BAH
                     ON BAD.[BATCHNO] = BAH.[BATCHNO]
                    AND BAH.[Posted] = ''Y''
             INNER JOIN [dbo].[KPIParameters] AS KPI
                     ON KPI.[Year] = BAD.[YEAR]
                    AND KPI.[Period] = BAD.[PERNO]
             INNER JOIN [dbo].[matters] AS MAT
                     ON BAH.[MATTER] = MAT.[Code]
             INNER JOIN [dbo].[Contacts] AS CON
                     ON MAT.[ClientCode] = CON.[Code]
       WHERE
	   (
	      RTRIM(LTRIM(@SearchText)) = ''''
	      OR
	      (
		  [MAT].[Code] LIKE ''%' + @SearchText + '%''
		  OR
		  [CON].[Name] LIKE ''%' + @SearchText + '%''
		  OR
		  [MAT].[Description] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[VALUE] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAH].[INVCR] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[REF] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[NARR] LIKE ''%' + @SearchText + '%''
	      )
		)
	    AND ISNULL(BAD.[FEE], '''') = ''' + @HANDLER + '''
        AND ISNULL(BAD.[TYPE], '''') = ''I''
        AND ISNULL(BAD.[OUTLAY], '''') = ''F'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeeIssuedCurrentMonthSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeeIssuedCurrentMonthSAM3Table'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #FeeIssuedCurrentMonthSAM4Table
	   FROM
	   (SELECT RTRIM(ISNULL(MAT.[Code], ''''))        AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(TRN.[FeesBilled], 0) *
               ISNULL(TRN.[DrCr], 1) * -1            AS [Fee],
               RTRIM(ISNULL(TRN.[TransRef], ''''))   AS [Ref],
               RTRIM(ISNULL(TRN.[Narrative], ''''))  AS [Narrative],
               TRN.[TransDate]                       AS [Date]
          FROM [dbo].[Contacts] AS CON
               INNER JOIN [dbo].[matters] AS MAT
                       ON CON.[Code] = MAT.[ClientCode]
               INNER JOIN [dbo].[Transactions] AS HED
                       ON HED.[MatterCode] = MAT.[Code]
               INNER JOIN [dbo].[Transactions] AS 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] IN (''L'', ''X'')
                      AND TRN.[FeeEarner] = ''' + @Handler + '''
               INNER JOIN [dbo].[KPIParameters] AS KPI
                       ON KPI.[Year] = HED.[PostingYear]
                      AND KPI.[Period] = HED.[PostingPeriod]
         WHERE
		 (
	      RTRIM(LTRIM(@SearchText)) = ''''
	      OR
	      (
		  [MAT].[Code] LIKE ''%' + @SearchText + '%''
		  OR
		  [CON].[Name] LIKE ''%' + @SearchText + '%''
		  OR
		  [MAT].[Description] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[FeesBilled] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[DrCr] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[TransRef] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[Narrative] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
	      )
		)
		AND
		ISNULL(HED.[RecType], '''') = ''H'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeeIssuedCurrentMonthSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeeIssuedCurrentMonthSAM4Table'
    END

	EXECUTE sp_executesql @NCOMMAND, N'@SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
ELSE IF @Function='Fees Issued Last Month'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
	  SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
	  SET @SortDirection = 'ASC'
	END

    IF [dbo].[ISSAM4]() = 0
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #FeesIssuedLastMonthSAM3Table
	    FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))      AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(BAD.[VALUE], 0) *
			   CASE WHEN ISNULL(BAH.[INVCR], '''') = ''C''
			             THEN -1
			        ELSE 1 END                        AS [Fee],
               RTRIM(ISNULL(BAD.[REF], ''''))         AS [Ref],
               RTRIM(ISNULL(BAD.[NARR], ''''))        AS [Narrative],
               BAD.[DATE]                             AS [Date]
          FROM [dbo].[BatchDetails] AS BAD
               INNER JOIN [dbo].[BatchH] AS BAH
                       ON BAD.[BATCHNO] = BAH.[BATCHNO]
                      AND BAH.[Posted] = ''Y''
               INNER JOIN [dbo].[KPIParameters] AS KPI
                       ON (KPI.[Year] = BAD.[YEAR] 
                       AND KPI.[Period] <> 1 
                       AND KPI.[Period] - 1 = BAD.[PERNO])
                       OR (KPI.[Year] = BAD.[YEAR] - 1 
                       AND KPI.[Period] = 1 
                       AND BAD.[PERNO] = 12)
               INNER JOIN [dbo].[matters] AS MAT
                       ON BAH.[MATTER] = MAT.[Code]
               INNER JOIN [dbo].[Contacts] AS CON
                       ON MAT.[ClientCode] = CON.[Code]
         WHERE
		 (
	      RTRIM(LTRIM(@SearchText)) = ''''
	      OR
	      (
		  [MAT].[Code] LIKE ''%' + @SearchText + '%''
		  OR
		  [CON].[Name] LIKE ''%' + @SearchText + '%''
		  OR
		  [MAT].[Description] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[VALUE] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAH].[INVCR] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[REF] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[NARR] LIKE ''%' + @SearchText + '%''
		  OR
		  [BAD].[DATE] LIKE ''%' + @SearchText + '%''
	      )
		 )
		 AND ISNULL(BAD.[FEE], '''') = ''' + @HANDLER + '''
         AND ISNULL(BAD.[TYPE], '''') = ''I''
         AND ISNULL(BAD.[OUTLAY], '''') = ''F'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedLastMonthSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedLastMonthSAM3Table'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #FeesIssuedLastMonthSAM4Table
	    FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))      AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(TRN.[FeesBilled], 0) * 
               ISNULL(TRN.[DrCr], 1) * - 1            AS [Fee],
               RTRIM(ISNULL(TRN.[TransRef], ''''))    AS [Ref],
               RTRIM(ISNULL(TRN.[Narrative], ''''))   AS [Narrative],
               TRN.[TransDate]                        AS [Date]
          FROM [dbo].[Contacts] AS CON
               INNER JOIN [dbo].[matters] AS MAT
                       ON CON.[Code] = MAT.[ClientCode]
               INNER JOIN [dbo].[Transactions] AS HED
                       ON HED.[MatterCode] = MAT.[Code]
               INNER JOIN [dbo].[Transactions] AS 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] IN (''L'', ''X'')
                      AND TRN.[FeeEarner] = ''' + @HANDLER + '''
               INNER JOIN [dbo].[KPIParameters] AS KPI
                       ON (KPI.[Year] = HED.[PostingYear]
                       AND KPI.[Period] <> 1
                       AND KPI.[Period] - 1 = HED.[PostingPeriod])
                       OR (KPI.[Year] = HED.[PostingYear] - 1
                       AND KPI.[Period] = 1
                       AND HED.[PostingYear] = 12)
         WHERE
		 (
	      RTRIM(LTRIM(@SearchText)) = ''''
	      OR
	      (
		  [MAT].[Code] LIKE ''%' + @SearchText + '%''
		  OR
		  [CON].[Name] LIKE ''%' + @SearchText + '%''
		  OR
		  [MAT].[Description] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[FeesBilled] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[DrCr] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[TransRef] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[Narrative] LIKE ''%' + @SearchText + '%''
		  OR
		  [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
	      )
		 )
		 AND ISNULL(HED.[RecType], '''') = ''H'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedLastMonthSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedLastMonthSAM4Table'
    END
    
    EXECUTE sp_executesql @NCOMMAND, N'@SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
ELSE IF @Function='Fees Issued Year to Date'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

    IF [dbo].[ISSAM4]() = 0
    BEGIN
		SET @NCOMMAND = '
		SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #FeesIssuedYearToDateSAM3Table
	      FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))      AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               CASE WHEN ISNULL(BAH.[INVCR], '''') = ''C'' THEN -BAD.[VALUE]
                    WHEN ISNULL(BAH.[INVCR], '''') = ''I'' THEN BAD.[VALUE]			             
			        ELSE 0 END                        AS [Fee],
               RTRIM(ISNULL(BAD.[REF], ''''))         AS [Ref],
               RTRIM(ISNULL(BAD.[NARR], ''''))        AS [Narrative],
               BAD.[DATE]                             AS [Date]
            FROM [dbo].[BatchDetails] AS BAD
                 INNER JOIN [dbo].[BatchH] AS BAH
                         ON BAD.[BATCHNO] = BAH.[BATCHNO]
                        AND BAH.[Posted] = ''Y''
                 INNER JOIN [dbo].[KPIParameters] AS KPI
                         ON KPI.[Year] = BAD.[YEAR]
                        AND KPI.[Period] >= BAD.[PERNO]
                 INNER JOIN [dbo].[matters] AS MAT
                         ON BAH.[MATTER] = MAT.[Code]
                 INNER JOIN [dbo].[Contacts] AS CON
                         ON MAT.[ClientCode] = CON.[Code]
           WHERE
		     (
	           RTRIM(LTRIM(@SearchText)) = ''''
	           OR
	           (
		        [MAT].[Code] LIKE ''%' + @SearchText + '%''
		        OR
		        [CON].[Name] LIKE ''%' + @SearchText + '%''
		        OR
		        [MAT].[Description] LIKE ''%' + @SearchText + '%''
		        OR
		        [BAH].[INVCR] LIKE ''%' + @SearchText + '%''
		        OR
		        [BAD].[REF] LIKE ''%' + @SearchText + '%''
				OR
		        [BAD].[NARR] LIKE ''%' + @SearchText + '%''
		        OR
		        [BAD].[DATE] LIKE ''%' + @SearchText + '%''
	           )
		     )
		     AND ISNULL(BAD.[FEE], '''') = ''' + @HANDLER + '''
             AND ISNULL(BAD.[TYPE], '''') = ''I''
             AND ISNULL(BAD.[OUTLAY], '''') = ''F'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedYearToDateSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedYearToDateSAM3Table'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #FeesIssuedYearToDateSAM4Table
	      FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))      AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(TRN.[FeesBilled], 0) * 
               ISNULL(TRN.[DrCr], 1) * - 1            AS [Fee],
               RTRIM(ISNULL(TRN.[TransRef], ''''))    AS [Ref],
               RTRIM(ISNULL(TRN.[Narrative], ''''))   AS [Narrative],
               TRN.[TransDate]                        AS [Date]
          FROM [dbo].[Contacts] AS CON
               INNER JOIN [dbo].[matters] AS MAT
                       ON CON.[Code] = MAT.[ClientCode]
               INNER JOIN [dbo].[Transactions] AS HED
                       ON MAT.[Code] = HED.[MatterCode]
               INNER JOIN [dbo].[Transactions] AS 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'')
                      AND TRN.[FeeEarner] = ''' + @Handler + '''
               INNER JOIN [dbo].[KPIParameters] AS KPI
                       ON KPI.[Year] = HED.[PostingYear]
                      AND KPI.[Period] >= HED.[PostingPeriod]
         WHERE
		 (
	       RTRIM(LTRIM(@SearchText)) = ''''
	       OR
	       (
		    [MAT].[Code] LIKE ''%' + @SearchText + '%''
		    OR
		    [CON].[Name] LIKE ''%' + @SearchText + '%''
		    OR
		    [MAT].[Description] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[FeesBilled] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[DrCr] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[TransRef] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[Narrative] LIKE ''%' + @SearchText + '%''
			OR
		    [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
	       )
		  )
	      AND
		  HED.[RecType] = ''H'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedYearToDateSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedYearToDateSAM4Table'
    END

    EXECUTE sp_executesql @NCOMMAND, N'@SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
    -- Rewrite by John END
ELSE IF @Function='Fees Issued Last Year to Date'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

    IF [dbo].[ISSAM4]() = 0
	BEGIN
		SET @NCOMMAND = '
		SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #FeesIssuedLastYearToDateSAM3Table
	      FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))      AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               CASE WHEN ISNULL(BAH.[INVCR], '''') = ''C'' THEN -BAD.[VALUE]
                    WHEN ISNULL(BAH.[INVCR], '''') = ''I'' THEN BAD.[VALUE]			             
			        ELSE 0 END                        AS [Fee],
               RTRIM(ISNULL(BAD.[REF], ''''))         AS [Ref],
               RTRIM(ISNULL(BAD.[NARR], ''''))        AS [Narrative],
               BAD.[DATE]                             AS [Date]
            FROM [dbo].[BatchDetails] AS BAD
                 INNER JOIN [dbo].[BatchH] AS BAH
                         ON BAD.[BATCHNO] = BAH.[BATCHNO]
                        AND BAH.[Posted] = ''Y''
                 INNER JOIN [dbo].[KPIParameters] AS KPI
                         ON KPI.[Year] - 1 = BAD.[YEAR]
                        AND KPI.[Period] >= BAD.[PERNO]
                 INNER JOIN [dbo].[matters] AS MAT
                         ON BAH.[MATTER] = MAT.[Code]
                 INNER JOIN [dbo].[Contacts] AS CON
                         ON MAT.[ClientCode] = CON.[Code]
           WHERE
		     (
	           RTRIM(LTRIM(@SearchText)) = ''''
	           OR
	           (
		        [MAT].[Code] LIKE ''%' + @SearchText + '%''
		        OR
		        [CON].[Name] LIKE ''%' + @SearchText + '%''
		        OR
		        [MAT].[Description] LIKE ''%' + @SearchText + '%''
		        OR
		        [BAH].[INVCR] LIKE ''%' + @SearchText + '%''
		        OR
		        [BAD].[REF] LIKE ''%' + @SearchText + '%''
				OR
		        [BAD].[NARR] LIKE ''%' + @SearchText + '%''
		        OR
		        [BAD].[DATE] LIKE ''%' + @SearchText + '%''
	           )
		     )
		     AND ISNULL(BAD.[FEE], '''') = ''' + @HANDLER + '''
             AND ISNULL(BAD.[TYPE], '''') = ''I''
             AND ISNULL(BAD.[OUTLAY], '''') = ''F'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedLastYearToDateSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedLastYearToDateSAM3Table'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #FeesIssuedLastYearToDateSAM4Table
	      FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))        AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(TRN.[FeesBilled], 0) * 
               ISNULL(TRN.[DrCr], 1) * - 1            AS [Fee],
               RTRIM(ISNULL(TRN.[TransRef], ''''))    AS [Ref],
               RTRIM(ISNULL(TRN.[Narrative], ''''))   AS [Narrative],
               TRN.[TransDate]                        AS [Date]
          FROM [dbo].[Transactions] AS HED
               INNER JOIN [dbo].[Transactions] AS 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] IN (''L'', ''X'')
                      AND TRN.[FeeEarner] = ''' + @Handler + '''
               INNER JOIN [dbo].[KPIParameters] AS KPI
                       ON KPI.[Year] - 1 = HED.[PostingYear]
                      AND KPI.[Period] >= HED.[PostingPeriod]
               LEFT OUTER JOIN [dbo].[matters] AS MAT
                            ON MAT.[Code] = HED.[MatterCode]
               LEFT OUTER JOIN [dbo].[Contacts] AS CON
                            ON CON.[Code] = MAT.[ClientCode]
         WHERE
		 (
	       RTRIM(LTRIM(@SearchText)) = ''''
	       OR
	       (
		    [MAT].[Code] LIKE ''%' + @SearchText + '%''
		    OR
		    [CON].[Name] LIKE ''%' + @SearchText + '%''
		    OR
		    [MAT].[Description] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[FeesBilled] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[DrCr] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[TransRef] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[Narrative] LIKE ''%' + @SearchText + '%''
			OR
		    [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
	       )
		  )
		 AND HED.[RecType] = ''H'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedLastYearToDateSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedLastYearToDateSAM4Table'
    END

    EXECUTE sp_executesql @NCOMMAND, N'@SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
ELSE IF @Function='Fees Issued Last Year'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
	  SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
	  SET @SortDirection = 'ASC'
	END

    IF [dbo].[ISSAM4]() = 0
    BEGIN
		SET @NCOMMAND = '
		SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #FeesIssuedLastYearSAM3Table
	      FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))        AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               CASE WHEN ISNULL(BAH.[INVCR], '''') = ''C'' THEN -BAD.[VALUE]
                    WHEN ISNULL(BAH.[INVCR], '''') = ''I'' THEN BAD.[VALUE]			             
			        ELSE 0 END                        AS [Fee],
               RTRIM(ISNULL(BAD.[REF], ''''))         AS [Ref],
               RTRIM(ISNULL(BAD.[NARR], ''''))        AS [Narrative],
               BAD.[DATE]                             AS [Date]
            FROM [dbo].[BatchDetails] AS BAD
                 INNER JOIN [dbo].[BatchH] AS BAH
                         ON BAD.[BATCHNO] = BAH.[BATCHNO]
                        AND BAH.[Posted] = ''Y''
                 INNER JOIN [dbo].[KPIParameters] AS KPI
                         ON KPI.[Year] - 1 = BAD.[YEAR]
                 INNER JOIN [dbo].[matters] AS MAT
                         ON BAH.[MATTER] = MAT.[Code]
                 INNER JOIN [dbo].[Contacts] AS CON
                         ON MAT.[ClientCode] = CON.[Code]
           WHERE
		     (
	          RTRIM(LTRIM(@SearchText)) = ''''
	          OR
	          (
		      [MAT].[Code] LIKE ''%' + @SearchText + '%''
		      OR
		      [CON].[Name] LIKE ''%' + @SearchText + '%''
		      OR
		      [MAT].[Description] LIKE ''%' + @SearchText + '%''
		      OR
			  [BAH].[INVCR] LIKE ''%' + @SearchText + '%''
			  OR
			  [BAD].[REF] LIKE ''%' + @SearchText + '%''
			  OR
			  [BAD].[NARR] LIKE ''%' + @SearchText + '%''
			  OR
		      [BAD].[DATE] LIKE ''%' + @SearchText + '%''
	          )
		     )
		     AND ISNULL(BAD.[FEE], '''') = ''' + @HANDLER + '''
             AND ISNULL(BAD.[TYPE], '''') = ''I''
             AND ISNULL(BAD.[OUTLAY], '''') = ''F'') AS FoundTable
		   ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	       FROM
	        #FeesIssuedLastYearSAM3Table
	       WHERE
	       (
	       	 @StartRow IS NULL
	       	 OR
	       	 (
	       	 	[Row_Number] BETWEEN @StartRow AND @EndRow		
	       	 )
	       )

	      SELECT
	      	  (COUNT([Row_Number])) AS TotalRecords
	      FROM
		      #FeesIssuedLastYearSAM3Table'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = '
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #FeesIssuedLastYearSAM4Table
	      FROM
	     (SELECT RTRIM(ISNULL(MAT.[Code], ''''))      AS [Code],
               RTRIM(ISNULL(CON.[Name], ''''))        AS [Client],
               RTRIM(ISNULL(MAT.[Description], '''')) AS [Matter],
               ISNULL(TRN.[FeesBilled], 0) * 
               ISNULL(TRN.[DrCr], 1) * - 1            AS [Fee],
               RTRIM(ISNULL(TRN.[TransRef], ''''))    AS [Ref],
               RTRIM(ISNULL(TRN.[Narrative], ''''))   AS [Narrative],
               TRN.[TransDate]                        AS [Date]
          FROM [dbo].[Transactions] AS HED
               INNER JOIN [dbo].[Transactions] AS 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] IN (''L'', ''X'')
                      AND TRN.[FeeEarner] = ''' + @Handler + '''
               INNER JOIN [dbo].[KPIParameters] AS KPI
                       ON KPI.[Year] - 1 = HED.[PostingYear]
               LEFT OUTER JOIN [dbo].[matters] AS MAT
                            ON MAT.[Code] = HED.[MatterCode]
               LEFT OUTER JOIN [dbo].[Contacts] AS CON
                            ON CON.[Code] = MAT.[ClientCode]
         WHERE
		  (
	       RTRIM(LTRIM(@SearchText)) = ''''
	       OR
	       (
		   [MAT].[Code] LIKE ''%' + @SearchText + '%''
		   OR
		   [CON].[Name] LIKE ''%' + @SearchText + '%''
		   OR
		   [MAT].[Description] LIKE ''%' + @SearchText + '%''
		   OR
		   [TRN].[FeesBilled] LIKE ''%' + @SearchText + '%''
		   OR
		   [TRN].[DrCr] LIKE ''%' + @SearchText + '%''
		   OR
		   [TRN].[TransRef] LIKE ''%' + @SearchText + '%''
		   OR
		   [TRN].[Narrative] LIKE ''%' + @SearchText + '%''
		   OR
		   [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
	       )
		  )
		 AND HED.[RecType] = ''H'') AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #FeesIssuedLastYearSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #FeesIssuedLastYearSAM4Table'
    END

    EXECUTE sp_executesql @NCOMMAND, N'@SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
ELSE IF @Function='TimeDayBook'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END
	
    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#TimeDayBookTable
	FROM
	(SELECT ISNULL(TDB.[Matter], '')            AS [Code],
           RTRIM(ISNULL(CNT.[Name], ''))        AS [Client],
           RTRIM(ISNULL(MAT.[Description], '')) AS [Description],
           ISNULL(TDB.[Date], '')               AS [Date],
           RTRIM(ISNULL(TDB.[Comment], ''))     AS [Comment],
           ISNULL(TDB.[Time], 0)                AS [Time],
           ISNULL(TDB.[Charge], 0)              AS [Charge]
      FROM [dbo].[TimeDayBook] TDB
           LEFT OUTER JOIN [dbo].[matters] AS MAT
                        ON TDB.[Matter] = MAT.[Code]
           LEFT OUTER JOIN [dbo].[Contacts] AS CNT
                        ON MAT.[ClientCode] =CNT.[Code]
     WHERE
	   (
		[TDB].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[CNT].[Name] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
		OR
		[TDB].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TDB].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TDB].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TDB].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TDB.[FeeEarn] = @Handler
       AND TDB.[TimeOrCharge] = 'T'
       AND TDB.[Rec_irr] = 'C') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client' THEN [Client]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client'   THEN [Client]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #TimeDayBookTable
END
ELSE IF @Function='TimeDayBookforWeek'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

    SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#TimeDayBookForWeekTable
	FROM
	(SELECT ISNULL(TIE.[Matter],'')            AS [Code],
           RTRIM(ISNULL(CON.[Name],''))        AS [Client],
           RTRIM(ISNULL(MAT.[Description],'')) AS [Description],
           ISNULL(TIE.[Date],'')               AS [Date],
           RTRIM(ISNULL(TIE.[Comment],''))     AS [Comment],
           ISNULL(TIE.[Time],0)                AS [Time],
           ISNULL(TIE.[Charge],0)              AS [Charge]
      FROM [dbo].[TimeEntry] AS TIE
           LEFT OUTER JOIN [dbo].[matters] AS MAT
                        ON TIE.[Matter] = MAT.[Code]
           LEFT OUTER JOIN [dbo].[Contacts] AS CON
                        ON MAT.[ClientCode] = CON.[Code]
     WHERE
	 (
		[TIE].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[CON].[Name] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TIE.[FeeEarn] = @Handler
       AND TIE.[TimeOrCharge] = 'T'
       AND TIE.[Date] >= @MONDAY
       AND TIE.[Date] <= @GETDATE
       AND TIE.[Rec_irr] = 'C'
       AND ISNULL(TIE.[Task], '') <> 'WRI') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client' THEN [Client]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client'   THEN [Client]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #TimeDayBookForWeekTable
END
ELSE IF @Function='TimeDayBookforMonth'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

	SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#TimeDayBookForMonthTable
	FROM
	(SELECT ISNULL(TIE.[Matter], '')            AS [Code],
	       RTRIM(ISNULL(CON.[Name], ''))        AS [Client],
	       RTRIM(ISNULL(MAT.[Description], '')) AS [Description],
	       TIE.[Date]                           AS [Date],
	       RTRIM(ISNULL(TIE.[Comment], ''))     AS [Comment],
	       ISNULL(TIE.[Time], 0)                AS [Time],
	       ISNULL(TIE.[Charge], 0)              AS [Charge]
      FROM [dbo].[TimeEntry] AS TIE
           LEFT OUTER JOIN [dbo].[matters] AS MAT
                        ON TIE.[Matter] =MAT.[Code]
           LEFT OUTER JOIN [dbo].[Contacts] AS CON
                        ON MAT.[ClientCode] =CON.[Code]
     WHERE
	   (
		[TIE].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[CON].[Name] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TIE.[FeeEarn] = @Handler
       AND TIE.[TimeOrCharge] = 'T'
       AND TIE.[Rec_irr] = 'C'
       AND TIE.[Date] >= @STARTOFMONTH
       AND TIE.[Date] <= @MONTHTODATE
       AND ISNULL(TIE.[Task], '') <> 'WRI') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client' THEN [Client]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client'   THEN [Client]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #TimeDayBookForMonthTable
END
ELSE IF @Function='TimeDayBookforYear'
BEGIN
	IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

	SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#TimeDayBookForYearTable
	FROM
	(SELECT ISNULL(TIE.[Matter],'')            AS [Code],
	       RTRIM(ISNULL(CON.[Name],''))        AS [Client],
	       RTRIM(ISNULL(MAT.[Description],'')) AS [Description],
	       TIE.[Date]                          AS [Date],
	       RTRIM(ISNULL(TIE.[Comment], ''))    AS [Comment],
	       ISNULL(TIE.[Time], 0)               AS [Time],
	       ISNULL(TIE.[Charge], 0)             AS [Charge]
	  FROM [dbo].[TimeEntry] AS TIE
	       LEFT OUTER JOIN [dbo].[matters] AS MAT
	                    ON TIE.[Matter] = MAT.[Code]
	       LEFT OUTER JOIN [dbo].[Contacts] AS CON
	                    ON MAT.[ClientCode] = CON.[Code]
	 WHERE
	   (
		[TIE].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[CON].[Name] LIKE '%' + @SearchText + '%'
		OR
		[MAT].[Description] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TIE.[FeeEarn] = @Handler
	   AND TIE.[TimeOrCharge] = 'T'
	   AND TIE.[Rec_irr] = 'C'
	   AND TIE.[Date] >= @STARTOFYEAR
	   AND TIE.[Date] <= @MONTHTODATE
	   AND ISNULL(TIE.[Task], '') <> 'WRI') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client' THEN [Client]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Client'   THEN [Client]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Description'   THEN [Description]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #TimeDayBookForYearTable
END
ELSE IF @Function='AdminTimeDayBookforWeek'
BEGIN

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

	SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#AdminTimeDayBookforWeekTable
	FROM
	(SELECT ISNULL(TIE.[Matter],'')        AS [Code],
	       ISNULL(TIE.[Date],'')           AS [Date],
	       RTRIM(ISNULL(TIE.[Comment],'')) AS [Comment],
	       ISNULL(TIE.[Time],0)            AS [Time],
	       ISNULL(TIE.[Charge],0)          AS [Charge]
      FROM [dbo].[TimeEntry] AS TIE
     WHERE
	   (
		[TIE].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TIE.[FeeEarn] = @Handler 
       AND TIE.[TimeOrCharge] = 'T'
       AND TIE.[Date] >= @MONDAY
       AND TIE.[Date] <= @MONTHTODATE
       AND ISNULL(TIE.[TASK], '') <> 'WRI'
       AND TIE.[Matter] = '~') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #AdminTimeDayBookforWeekTable
END
ELSE IF @Function='AdminTimeDayBookforMonth'
BEGIN 
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

	SELECT
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#AdminTimeDayBookforMonthTable
	FROM
	(SELECT ISNULL(TIE.[Matter], '')         AS [Code],
	        ISNULL(TIE.[Date], '')           AS [Date],
	        RTRIM(ISNULL(TIE.[Comment], '')) AS [Comment],
	        ISNULL(TIE.[Time], 0)            AS [Time],
	        ISNULL(TIE.[Charge], 0)          AS [Charge]
     FROM [dbo].[TimeEntry] AS TIE
     WHERE
	   (
		[TIE].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TIE.[FeeEarn] = @Handler
       AND TIE.[TimeOrCharge] = 'T'
       AND TIE.[Date] >= @STARTOFMONTH
       AND TIE.[Date] <= @MONTHTODATE
       AND ISNULL(TIE.[Task], '') <> 'WRI'
       AND TIE.[Matter] = '~') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #AdminTimeDayBookforMonthTable
END
ELSE IF @Function='AdminTimeDayBookforYear'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

	SELECT
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#AdminTimeDayBookforYearTable
	FROM
	(SELECT ISNULL(TIE.[Matter], '')        AS [Code],
	       ISNULL(TIE.[Date], '')           AS [Date],
	       RTRIM(ISNULL(TIE.[Comment], '')) AS [Comment],
	       ISNULL(TIE.[Time], 0)            AS [Time],
	       ISNULL(TIE.[Charge], 0)          AS [Charge]
	  FROM [dbo].[TimeEntry] TIE
	 WHERE
	   (
		[TIE].[Matter] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Date] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Comment] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Time] LIKE '%' + @SearchText + '%'
		OR
		[TIE].[Charge] LIKE '%' + @SearchText + '%'
	   )
	   AND TIE.[FeeEarn] = @Handler
	   AND TIE.[TimeOrCharge] = 'T'
	   AND TIE.[Date] >= @STARTOFYEAR
	   AND TIE.[Date] <= @MONTHTODATE
	   AND ISNULL(TIE.[Task], '') <> 'WRI'
	   AND TIE.[Matter] = '~') AS FoundTable
	 ORDER BY
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Code'   THEN [Code]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Code'   THEN [Code]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Date'   THEN [Date]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Comment'   THEN [Comment]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
		   CASE @SortColumn 
		   	  WHEN 'Time'   THEN [Time]
		   END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Time'   THEN [Time]
	  	  END
	  END DESC,
	  CASE WHEN @SortDirection = 'ASC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge' THEN [Charge]
	  	  END
	  END,
	  CASE WHEN @SortDirection = 'DESC' THEN
	  	  CASE @SortColumn 
	  	  	  WHEN 'Charge'   THEN [Charge]
	  	  END
	  END DESC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
	    #AdminTimeDayBookforYearTable
END
ELSE IF @Function='OSFees'
BEGIN
    IF [dbo].[ISSAM4]() = 0
    BEGIN

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

      SET @NCOMMAND = N'
      SELECT 
		     IDENTITY(INT, 1,1) AS [Row_Number],
		     *
	  INTO
		     #OSFeesSAM3Table
	  FROM
	        (SELECT MAT.[Code],
             MAT.[Description], 
             DTL.[OSFEES] AS [OSFees]
      FROM   [dbo].[matters] MAT
             INNER JOIN [dbo].[DebtorsLedger] DTL
                     ON DTL.[MATTER] = MAT.[Code]
                    AND DTL.[OSValue] > 0
      WHERE
	    (
	      RTRIM(LTRIM(@SearchText)) = ''''
	      OR
	      (
		  [MAT].[Code] LIKE ''%' + @SearchText + '%''
		  OR
		  [MAT].[Description] LIKE ''%' + @SearchText + '%''
		  OR
		  [DTL].[OSFEES] LIKE ''%' + @SearchText + '%''
	      )
		)
	  AND
	      MAT.[FECode] = @Handler) AS FoundTable
	  ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	      *
	  FROM
	      #OSFeesSAM3Table
	  WHERE
	  (
	  	@StartRow IS NULL
	  	OR
	  	(
	  	  [Row_Number] BETWEEN @StartRow AND @EndRow		
	  	)
	  )

	  SELECT
	  	(COUNT([Row_Number])) AS TotalRecords
	  FROM
		#OSFeesSAM3Table'
    END
    ELSE
    BEGIN
	    IF(@SortColumn = '' OR @SortColumn = NULL)
	    BEGIN
	    	SET @SortColumn = 'Row_Number'
	    END
        IF(@SortDirection = '' OR @SortDirection = NULL)
	    BEGIN
	    	SET @SortDirection = 'ASC'
	    END

        SET @NCOMMAND = N'
        SELECT 
		     IDENTITY(INT, 1,1) AS [Row_Number],
		     *
	    INTO
		     #OSFeesSAM4Table
	    FROM
	        (SELECT MAT.[Code]                 AS [Code],
               ISNULL(MAT.[Description], '''') AS [Description],
               ISNULL(TRN.[FeesOS], 0)         AS [OSFees]
         FROM [dbo].[matters] AS MAT
               INNER JOIN [dbo].[Transactions] TRN
                       ON TRN.[MatterCode] = MAT.[Code]
         WHERE
		   (
	        RTRIM(LTRIM(@SearchText)) = ''''
	        OR
	        (
		    [MAT].[Code] LIKE ''%' + @SearchText + '%''
		    OR
		    [MAT].[Description] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[FeesOS] LIKE ''%' + @SearchText + '%''
	        )
		   )
		   AND TRN.[Posted] = ''Y''
           AND MAT.[FECode] = @Handler
           AND TRN.[CorrectionInd] = ''L''
           AND TRN.[DebtorsValueOS] > 0
           AND ((TRN.[XnType] = ''I'' AND TRN.[RecType] = ''H'')
           OR (TRN.[XnType] = ''J'' AND TRN.[RecType] = ''D''))) AS FoundTable
	     ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	         *
	     FROM
	         #OSFeesSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     	  [Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	     SELECT
	  	    (COUNT([Row_Number])) AS TotalRecords
	     FROM
		    #OSFeesSAM4Table'
    END

    EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @Handler = @Handler, @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
ELSE IF @Function='DebtorDays'
BEGIN
      IF(@SortColumn = '' OR @SortColumn = NULL)
	  BEGIN
	  	SET @SortColumn = 'Row_Number'
	  END
      IF(@SortDirection = '' OR @SortDirection = NULL)
	  BEGIN
	  	SET @SortDirection = 'ASC'
	  END

      IF [dbo].[ISSAM4]() = 0
        BEGIN
          SET @NCOMMAND = N'
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	      INTO
		    #DebtorDaysSAM3Table
	      FROM
	     (SELECT MAT.[Code],
               ISNULL(MAT.[Description], '''')                                 AS [Description],
               DTL.[DATE]                                                      AS [TransDate],
               ISNULL(CASE WHEN DTL.[DATE] IS NULL
                                    THEN 0
                               WHEN DTL.[DATE] > @GETDATE
                                    THEN 0
                               WHEN DTL.[OSVALUE] = 0
                                    THEN 0
                               ELSE DATEDIFF(Day, DTL.[DATE], @GETDATE) END, 0) AS [DebtorDays],
               ISNULL(CASE WHEN DTL.[DATE] IS NULL
                                THEN 0
                           WHEN DTL.[DATE] > @GETDATE
                                THEN 0
                           WHEN DTL.[OSVALUE] = 0
                                THEN 0
                           ELSE 1 END, 0)                                       AS [DebtorEntries]
          FROM [dbo].[matters] MAT
               INNER JOIN [dbo].[DebtorsLedger] DTL
                       ON DTL.[MATTER] = MAT.[Code]
                      AND DTL.[OSValue] > 0
          WHERE
		  (
	       RTRIM(LTRIM(@SearchText)) = ''''
	       OR
	       (
		   [MAT].[Code] LIKE ''%' + @SearchText + '%''
		   OR
		   [MAT].[Description] LIKE ''%' + @SearchText + '%''
		   OR
		   [DTL].[DATE] LIKE ''%' + @SearchText + '%''
		   OR
		   [DTL].[OSVALUE] LIKE ''%' + @SearchText + '%''
	       )
		  )
		  AND MAT.[FECode] = @Handler) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #DebtorDaysSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #DebtorDaysSAM3Table'
        END
      ELSE
      BEGIN
        SET @NCOMMAND = N'
       	SELECT 
		  IDENTITY(INT, 1,1) AS [Row_Number],
		  *
	    INTO
	      #DebtorDaysSAM4Table
	    FROM
	      (SELECT MAT.[Code],
               ISNULL(MAT.[Description], '''') AS [Description],
               TRN.[TransDate] AS [TransDate],
		       ISNULL(CASE WHEN TRN.[TransDate] IS NULL
                                THEN 0
                           WHEN TRN.[TransDate] > @GETDATE
                                THEN 0
                           WHEN TRN.[DebtorsValueOS] = 0
                                THEN 0
                           ELSE DATEDIFF(Day, TRN.[TransDate], @GETDATE) END, 0) AS [DebtorDays],
               ISNULL(CASE WHEN TRN.[TransDate] IS NULL
                                THEN 0
                           WHEN TRN.[TransDate] > @GETDATE
                                THEN 0
                           WHEN TRN.[DebtorsValueOS] = 0
                                THEN 0
                           ELSE 1 END, 0) AS [DebtorEntries]
          FROM [dbo].[matters] AS MAT
               INNER JOIN [dbo].[Transactions] TRN
                       ON MAT.[Code] = TRN.[MatterCode]
         WHERE
		   (
	        RTRIM(LTRIM(@SearchText)) = ''''
	        OR
	        (
		    [MAT].[Code] LIKE ''%' + @SearchText + '%''
		    OR
		    [MAT].[Description] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
		    OR
		    [TRN].[DebtorsValueOS] LIKE ''%' + @SearchText + '%''
	        )
		   )
		   AND TRN.[Posted] = ''Y''
           AND MAT.[FECode] = @Handler
           AND TRN.[CorrectionInd] = ''L''
           AND ((TRN.[XnType] = ''I'' AND TRN.[RecType] = ''H'')
             OR (TRN.[XnType] = ''J'' AND TRN.[RecType] = ''D''))
           AND TRN.[DebtorsValueOS] > 0) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #DebtorDaysSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #DebtorDaysSAM4Table'
      END

      EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @GETDATE DateTime, @SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @Handler = @Handler, @GETDATE = @GETDATE, @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END
ELSE IF @Function='DraftInvoices'
BEGIN
    IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
    IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

    IF [dbo].[ISSAM4]() = 0
    BEGIN
        SET @NCOMMAND = N'
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #DraftInvoiceSAM3Table
	    FROM
	     (SELECT MAT.[Code],
               MAT.[Description],
               BIH.[DATE] AS [Date],
              (ISNULL(BID.[Fee], 0) + 
               ISNULL(BID.[Outlay], 0) + 
               ISNULL(BID.[MiscOutlay], 0) + 
               ISNULL(BID.[VAT], 0))       * CASE WHEN BIH.[INVCR] = ''C'' THEN -1 ELSE 1 END AS [Total],
               ISNULL(BID.[Fee], 0)        * CASE WHEN BIH.[INVCR] = ''C'' THEN -1 ELSE 1 END AS [Fee],
               ISNULL(BID.[Outlay], 0)     * CASE WHEN BIH.[INVCR] = ''C'' THEN -1 ELSE 1 END AS [Outlay],
               ISNULL(BID.[MiscOutlay], 0) * CASE WHEN BIH.[INVCR] = ''C'' THEN -1 ELSE 1 END AS [MiscOutlay],
               ISNULL(BID.[VAT], 0)        * CASE WHEN BIH.[INVCR] = ''C'' THEN -1 ELSE 1 END AS [VAT]
          FROM [dbo].[matters] AS MAT
               INNER JOIN [dbo].[BillHeader] AS BIH
                       ON MAT.[Code] = BIH.[MATTER]
               LEFT OUTER JOIN (SELECT BID.[DRAFTNO],
                                       SUM(CASE WHEN BID.[TYPE] = ''F'' THEN BID.[NET] ELSE 0 END) AS [Fee],
                                       SUM(CASE WHEN BID.[TYPE] = ''O'' THEN BID.[NET] ELSE 0 END) AS [Outlay],
                                       SUM(CASE WHEN BID.[TYPE] = ''M'' THEN BID.[NET] ELSE 0 END) AS [MiscOutlay],
                                       SUM(BID.[VATVALUE]) AS [VAT]
                                  FROM [dbo].[BillDetails] AS BID
                                       GROUP BY BID.[DRAFTNO]) AS BID
                            ON BID.[DRAFTNO] = BIH.[DRAFTNO]
         WHERE
		   (
	        RTRIM(LTRIM(@SearchText)) = ''''
	        OR
	        (
		    [MAT].[Code] LIKE ''%' + @SearchText + '%''
		    OR
		    [MAT].[Description] LIKE ''%' + @SearchText + '%''
		    OR
		    [BIH].[DATE] LIKE ''%' + @SearchText + '%''
	        )
		   )
		   AND BIH.[BILLNO] = 0
           AND MAT.[FECode] = @Handler) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #DraftInvoiceSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #DraftInvoiceSAM3Table'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = N'
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #DraftInvoiceSAM4Table
	    FROM
	     (SELECT MAT.[Code],
               MAT.[Description],
               BH.[BillDate] AS [Date],
               (ISNULL(BD.[Fee], 0) +
                ISNULL(BD.[Outlay], 0) +
                ISNULL(BD.[MiscOutlay], 0) +
                ISNULL(BD.[VAT], 0))      * CASE WHEN BH.[Type] = ''C'' THEN -1 ELSE 1 END AS [Total],
                ISNULL(BD.[Fee], 0)        * CASE WHEN BH.[Type] = ''C'' THEN -1 ELSE 1 END AS [Fee],
                ISNULL(BD.[Outlay], 0)     * CASE WHEN BH.[Type] = ''C'' THEN -1 ELSE 1 END AS [Outlay],
                ISNULL(BD.[MiscOutlay], 0) * CASE WHEN BH.[Type] = ''C'' THEN -1 ELSE 1 END AS [MiscOutlay],
                ISNULL(BD.[VAT], 0)        * CASE WHEN BH.[Type] = ''C'' THEN -1 ELSE 1 END AS [VAT]
          FROM [dbo].[matters] AS MAT
               INNER JOIN [dbo].[Billhead] AS BH
                       ON MAT.[Code] = BH.[MatterCode]
               LEFT OUTER JOIN (SELECT BD.[BillID],
                                       SUM(CASE WHEN BD.[RecordType] = ''F'' THEN BD.[NetValue] ELSE 0 END) AS [Fee],
                                       SUM(CASE WHEN BD.[RecordType] = ''O'' THEN BD.[NetValue] ELSE 0 END) AS [Outlay],
                                       SUM(CASE WHEN BD.[RecordType] = ''M'' THEN BD.[NetValue] ELSE 0 END) AS [MiscOutlay],
                                       SUM(BD.[VatValue]) AS [VAT]
                                  FROM [dbo].[BillDetail] AS BD
                                       GROUP BY BD.[BillID]) AS BD
                            ON BH.[BillingID] = BD.[BillID]
         WHERE
		   (
	        RTRIM(LTRIM(@SearchText)) = ''''
	        OR
	        (
		    [MAT].[Code] LIKE ''%' + @SearchText + '%''
		    OR
		    [MAT].[Description] LIKE ''%' + @SearchText + '%''
		    OR
		    [BH].[BillDate] LIKE ''%' + @SearchText + '%''
	        )
		   )
		   AND BH.[BillStatus] <> ''Approved''
           AND MAT.[FECode] = @Handler) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #DraftInvoiceSAM4Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #DraftInvoiceSAM4Table'
    END

    EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @Handler = @Handler, @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow
END

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

CREATE PROCEDURE
       [dbo].[KEYHM_Dashboardmaxlimit]
      (@HANDLER NVARCHAR(10))--@HANDLER MUST be NVARCHAR as it's defined as such in [dbo].[UserSettings]
AS

/*******************************************************************************************************
*																									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_Dashboardmaxlimit]											   *
* Copied from			: [dbo].[Ky_NETDashboardmaxlimit]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

BEGIN
    SET NOCOUNT ON

    DECLARE @TIMEDAYBOOKLIMIT        DECIMAL(18, 2)
    DECLARE @TIMEDAYBOOKLIMITHR      VARCHAR(20)
    DECLARE @TIMEFORWEEK             DECIMAL(18, 2)
    DECLARE @TIMEFORWEEKHR           VARCHAR(20)
    DECLARE @TIMEFORMONTH            DECIMAL(18, 2)
    DECLARE @TIMEFORMONTHHR          VARCHAR(20)
    DECLARE @TIMEFORYEAR             DECIMAL(18, 2)
    DECLARE @TIMEFORYEARHR           VARCHAR(20)
    DECLARE @TIMEYTD                 DECIMAL(18, 2)
    DECLARE @TIMEYTDHR               VARCHAR(20)
    DECLARE @NCTIMEFORMONTH          DECIMAL(18, 2)
    DECLARE @NCTIMEFORMONTHHR        VARCHAR(20)
    DECLARE @NCTIMEFORYEAR           DECIMAL(18, 2)
    DECLARE @NCTIMEFORYEARHR         VARCHAR(20)
    DECLARE @FEESISSUEDCURMONTH      DECIMAL(18, 2)
    DECLARE @FEESISSUEDLASTMONTH     DECIMAL(18, 2)
    DECLARE @FEESISSUEDYTD           DECIMAL(18, 2)
    DECLARE @FEESISSUEDLASTYTD       DECIMAL(18, 2)
    DECLARE @FEESISSUEDLASTYEAR      DECIMAL(18, 2)
    DECLARE @OSINVOICELIMIT          DECIMAL(18, 2)
    DECLARE @CURRENTWIPLIMIT         DECIMAL(18, 2)
    DECLARE @DRAFTINVOICELIMIT       DECIMAL(18, 2)

    DECLARE @YEAR INT
    DECLARE @PERIOD INT

    -- Get the financial year and period from the KPI, if not there then control, if not there then use now.
    IF [dbo].[ISSAM4]() = 0
    BEGIN
        SELECT @YEAR = ISNULL(KPI.[Year], ISNULL(CON.[YEAR], YEAR(GETDATE())))
          FROM [dbo].[KPIParameters] AS KPI
               OUTER APPLY [dbo].[control] AS CON

        SELECT @PERIOD = ISNULL(KPI.[Period], ISNULL(CON.[CURPER], MONTH(GETDATE())))
          FROM [dbo].[KPIParameters] AS KPI
               OUTER APPLY [dbo].[control] AS CON
    END
    ELSE
    BEGIN
        SELECT @YEAR = ISNULL(KPI.[Year], ISNULL(CON.[NumValue], YEAR(GETDATE())))
          FROM [dbo].[KPIParameters] AS KPI
               OUTER APPLY (SELECT TOP 1 NUM.[NumValue]
                              FROM [dbo].[CtrlNum] AS NUM
                             WHERE NUM.[Code] = 'CurYear') AS CON

        SELECT @PERIOD = ISNULL(KPI.[Period], ISNULL(CON.[NumValue], MONTH(GETDATE())))
          FROM [dbo].[KPIParameters] AS KPI
               OUTER APPLY (SELECT TOP 1 NUM.[NumValue]
                              FROM [dbo].[CtrlNum] AS NUM
                             WHERE NUM.[Code] = 'CurPeriod') AS CON
    END

    -- This is very unwieldy but not much choice when converting time values stored as strings into time formats (7.5 -> 07:30)
    SELECT @TIMEDAYBOOKLIMIT = 60.0 * CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = '' THEN '0' ELSE US.[Value] END),
           @TIMEDAYBOOKLIMITHR = CONVERT(VARCHAR(5), DATEADD(SECOND, 3600.0 * CONVERT(DECIMAL(18, 2), CASE WHEN ISNULL(US.[Value], '') = '' THEN '0' ELSE US.[Value] END), 0), 108),
           @TIMEFORWEEK = 60.0 * CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = '' THEN '0' ELSE US.[Value] END) * 5.0,
           @TIMEFORWEEKHR = RIGHT('00' + CONVERT(VARCHAR, FLOOR(CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = '' THEN '0' ELSE US.[Value] END) * 5.0)), 2) +
                            ':' +
                            RIGHT('00' + LEFT(CONVERT(VARCHAR, CONVERT(INT, (60.0 * CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = '' THEN '0' ELSE US.[Value] END) * 5.0) % 60.0)), 2), 2)
      FROM [dbo].[UserSettings] AS US
     WHERE US.[Handler] = @HANDLER
       AND UPPER(RTRIM(US.[Key])) = 'TIMEDAYBOOKLIMIT'

    SELECT @OSINVOICELIMIT = CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = ''
                                                               THEN '0'
                                                          ELSE US.[Value] END)
      FROM [dbo].[UserSettings] AS US
     WHERE US.[Handler] = @HANDLER
       AND UPPER(RTRIM(US.[Key])) = 'OSINVOICELIMIT'

    SELECT @DRAFTINVOICELIMIT = CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = ''
                                                                  THEN '0'
                                                             ELSE US.[Value] END)
      FROM [dbo].[UserSettings] AS US
     WHERE US.[Handler] = @HANDLER
       AND UPPER(RTRIM(US.[Key])) = 'DRAFTINVOICELIMIT'

    SELECT @CURRENTWIPLIMIT = CONVERT(DECIMAL(18, 5), CASE WHEN ISNULL(US.[Value], '') = ''
                                                                THEN '0'
                                                           ELSE US.[Value] END)
      FROM [dbo].[UserSettings] AS US
     WHERE US.[Handler] = @HANDLER
       AND UPPER(RTRIM(US.[Key])) = 'CURRENTWIPLIMIT'

    SELECT @TIMEFORMONTH       = CASE WHEN FLOOR((SUM(ISNULL(BDG.[ChargableTimeBudget], 0))) * 60.0) < 10
                                           THEN RIGHT('00' + FLOOR((SUM(ISNULL(BDG.[ChargableTimeBudget], 0))) * 60.0), 2)
                                      ELSE FLOOR((SUM(ISNULL(BDG.[ChargableTimeBudget], 0))) * 60.0) END,
           @TIMEFORMONTHHR     = CONVERT(VARCHAR, CONVERT(INT, SUM(ISNULL(BDG.[ChargableTimeBudget], 0)))) +
                                 ':' +
                                 RIGHT('00' + LEFT(CONVERT(VARCHAR, CONVERT(INT, (SUM(ISNULL(BDG.[ChargableTimeBudget], 0)) * 60.0) % 60)), 2), 2),
           @NCTIMEFORMONTH     = FLOOR((SUM(ISNULL(BDG.[NonChargableTimeBudget], 0))) * 60.0),
           @NCTIMEFORMONTHHR   = CONVERT(VARCHAR, CONVERT(INT, SUM(ISNULL(BDG.[NonChargableTimeBudget], 0)))) +
                                 ':' +
                                 RIGHT('00' + LEFT(CONVERT(VARCHAR, CONVERT(INT, (SUM(ISNULL(BDG.[NonChargableTimeBudget], 0)) * 60.0) % 60)), 2), 2),
           @FEESISSUEDCURMONTH = SUM(ISNULL(BDG.[FeesBudget], 0))
      FROM [dbo].[HandlerBudgets] AS BDG
     WHERE BDG.[HANDLER] = @HANDLER
       AND BDG.[MONTH]   = @PERIOD
       AND BDG.[YEAR]    = @YEAR

    SELECT @FEESISSUEDLASTMONTH = FLOOR(SUM(ISNULL(BDG.[FeesBudget], 0)))
      FROM [dbo].[HandlerBudgets] AS BDG
     WHERE BDG.[Handler] = @HANDLER
       AND BDG.[Month]   = CASE WHEN @PERIOD - 1 = 0 THEN 12 ELSE @PERIOD END
       AND BDG.[Year]    = CASE WHEN @PERIOD - 1 = 0 THEN @YEAR - 1 ELSE @YEAR END

    SELECT @FEESISSUEDYTD = FLOOR(SUM(BDG.[FeesBudget])),
           @TIMEYTD       = SUM(ISNULL(BDG.[ChargableTimeBudget], 0)) * 60.0,
           @TIMEYTDHR     = CONVERT(VARCHAR, CONVERT(INT, SUM(ISNULL(BDG.[ChargableTimeBudget], 0)) * 60.0)) +
                            ':' +
                            RIGHT('00' + LEFT(CONVERT(VARCHAR, CONVERT(INT, (SUM(ISNULL(BDG.[ChargableTimeBudget], 0)) * 60.0) % 60)), 2), 2)
      FROM [dbo].[HandlerBudgets] AS BDG
     WHERE BDG.[Handler] = @HANDLER
       AND BDG.[Month]  <= @PERIOD
       AND BDG.[Year]    = @YEAR

    SELECT @TIMEFORYEAR     = FLOOR(SUM(ISNULL(BDG.[ChargableTimeBudget], 0)) * 60.0),
           @TIMEFORYEARHR   = CONVERT(VARCHAR, CONVERT(INT, SUM(ISNULL(BDG.[ChargableTimeBudget], 0)))) +
                              ':' +
                              RIGHT('00' + LEFT(CONVERT(VARCHAR, CONVERT(INT, (SUM(ISNULL(BDG.[ChargableTimeBudget], 0)) * 60.0) % 60)), 2), 2),
           @NCTIMEFORYEAR   = FLOOR(SUM(ISNULL(BDG.[NonChargableTimeBudget], 0)) * 60.0),
           @NCTIMEFORYEARHR = CONVERT(VARCHAR, CONVERT(INT, SUM(ISNULL(BDG.[NonChargableTimeBudget], 0)))) +
                              ':' +
                              RIGHT('00' + LEFT(CONVERT(VARCHAR, CONVERT(INT, (SUM(ISNULL(BDG.[NonChargableTimeBudget], 0)) * 60.0) % 60)), 2), 2)
      FROM [dbo].[HandlerBudgets] AS BDG
     WHERE BDG.[Handler] = @HANDLER
       AND BDG.[Year]    = @YEAR

    SELECT @FEESISSUEDLASTYTD = FLOOR(SUM(ISNULL(CASE WHEN BDG.[Month] <= @PERIOD THEN BDG.[FeesBudget] ELSE 0 END, 0))),
           @FEESISSUEDLASTYEAR = FLOOR(SUM(ISNULL(BDG.[FeesBudget], 0)))
      FROM [dbo].[HandlerBudgets] AS BDG
     WHERE BDG.[Handler] = @HANDLER
       AND BDG.[Year]    = @YEAR - 1

    SELECT ISNULL(@TIMEDAYBOOKLIMIT,0)          AS [TIMEDAYBOOKLIMIT],
           ISNULL(@TIMEFORWEEK ,0)              AS [TIMEFORWEEK],
           ISNULL(@TIMEFORMONTH ,0)             AS [TIMEFORMONTH],
           ISNULL(@TIMEFORYEAR, 0)              AS [TIMEFORYEAR],
           ISNULL(@NCTIMEFORMONTH, 0)           AS [NCTIMEFORMONTH],
           ISNULL(@NCTIMEFORYEAR, 0)            AS [NCTIMEFORYEAR],
           ISNULL(@TIMEYTD, 0)                  AS [TIMEYTD],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@FEESISSUEDCURMONTH, 0), 0), 1), '.00', '')  AS [FEESISSUEDCURMONTH],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@FEESISSUEDLASTMONTH, 0), 0), 1), '.00', '') AS [FEESISSUEDLASTMONTH],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@FEESISSUEDYTD, 0), 0), 1), '.00', '')       AS [FEESISSUEDYTD],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@FEESISSUEDLASTYTD, 0), 0), 1), '.00', '')   AS [FEESISSUEDLASTYTD],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@FEESISSUEDLASTYEAR, 0), 0), 1), '.00', '')  AS [FEESISSUEDLASTYEAR],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@OSINVOICELIMIT, 0), 0), 1), '.00', '')      AS [OSINVOICELIMIT],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@CURRENTWIPLIMIT, 0), 0), 1), '.00', '')     AS [CURRENTWIPLIMIT],
           REPLACE(CONVERT(VARCHAR, ROUND(ISNULL(@DRAFTINVOICELIMIT, 0), 0), 1), '.00', '')   AS [DRAFTINVOICELIMIT],
           ISNULL(@TIMEDAYBOOKLIMITHR, '00:00') AS [TIMEDAYBOOKLIMITHR],
           ISNULL(@TIMEFORWEEKHR, '00:00')      AS [TIMEFORWEEKHR],
           ISNULL(@TIMEFORMONTHHR, '00:00')     AS [TIMEFORMONTHHR],
           ISNULL(@TIMEFORYEARHR, '00:00')      AS [TIMEFORYEARHR],
           ISNULL(@NCTIMEFORMONTHHR, '00:00')   AS [NCTIMEFORMONTHHR],
           ISNULL(@NCTIMEFORYEARHR, '00:00')    AS [NCTIMEFORYEARHR],
           ISNULL(@TIMEYTDHR, '00:00')          AS [TIMEYTDHR]

    SET NOCOUNT OFF
END

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

CREATE PROCEDURE [dbo].[KEYHM_DeleteAction]  
(  
 @ACTIONID        INT,  
 @HANDLERCODE     VARCHAR(10)  
)  
  
/*******************************************************************************************************
* This procedure is used Delete an Action from the Case Diary.										   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_DeleteAction]								   					   *
* Copied from			: [dbo].[ky_NETAADelete]													   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-22	Vinodhan K		Created                                                                *
*******************************************************************************************************/
AS  
BEGIN  
  
  DECLARE @Error VARCHAR(200)  
  DECLARE @NCOMMAND nvarchar(MAX)  
    
  DECLARE @AllowUserToDeleteOthersAction BIT;  
  
  SET NOCOUNT ON  
  
    
 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 [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  
      DELETE DAT  
        FROM [dbo].[DiaryAttachments] DAT  
       WHERE DAT.[DiaryID] = @ACTIONID  
  
      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].[KEYHM_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].[KEYHM_UpdateActionAlarm] @ACTIONID  
            
      DELETE DIA  
        FROM [dbo].[diary] DIA  
       WHERE DIA.[ACTIONID] = @ACTIONID   
  
      SELECT 'True'  
    END  
  ELSE  
    BEGIN  
      SELECT @Error  
    END  
   
  SET NOCOUNT OFF  
  
END  
GO
IF [dbo].[ISSAM4]() = 0
BEGIN
    EXEC ('
IF OBJECT_ID(N''KEYHM_DeleteDraftBillOnly'',N''P'') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_DeleteDraftBillOnly]
END')

    EXEC ('
CREATE PROCEDURE 
       [dbo].[KEYHM_DeleteDraftBillOnly]
      (@ID              INT,
       @HANDLERCODE     VARCHAR(10))

/***************************************************************************************
* 																				       *
* Stored Procedure Name : KEYHM_DeleteDraftBillOnly								       *
* Copied From           : [ky_NETSPDeleteDraftBillOnly]							       *
* 																				       *
* Description:     This procedure is used to delete the Bill related details	       *
*                  for a draft bill. This procedure can be called from:			       *
*                  ky_NETAADelete												       *
*                  ky_NETSPDeleteDraftBill										       *
*                  The above procedures take care of the associated Action as	       *
*                  well as the Bill information. This procedure only looks at	       *
*                  the Bill information, and assumes that the Action is taken	       *
*                  care of. 													       *
*                  																       *
*                  Do NOT call this procedure on its own.						       *
* 																				       *
* Modification History: 2018-08-23   John       Split this proc in two: SAM3 and SAM4  *
*                       2020-02-05   Vinodhan   Created KEYHM_DeleteDraftBillOnly   
*					    2020-03-13	Rajesh P	from  ky_NETSPDeleteDraftBillOnly   
* 																				       *
* *************************************************************************************/
AS
BEGIN
    DECLARE @xml XML

    SET @xml = (SELECT BH.[MATTER],
                       BH.[DRAFTNO],
                       BH.[DATE],
                       BH.[USER],
                       BH.[ADDRESSEE],
                       BH.[INVCR],
                       BH.[BILLNO],
                       BH.[OURREF],
                       BH.[YOURREF],
                       BH.[TOTAL],
                       BH.[FEES],
                       BH.[OUTLAY],
                       BH.[TOTALVAT],
                       BH.[FEEVATCODE],
                       BH.[NET0],
                       BH.[RATE1],
                       BH.[NETRATE1],
                       BH.[VATRATE1],
                       BH.[RATE2],
                       BH.[NETRATE2],
                       BH.[VATRATE2],
                       BH.[RATE3],
                       BH.[NETRATE3],
                       BH.[VATRATE3],
                       BH.[RELEASED],
                       BH.[RETURNREASON],
                       BH.[MATTERDESCRIPTION],
                       BH.[TRANSFER],
                       BH.[WRITEDOWN],
                       BH.[WRITEBACKHOURS],
                       BH.[WRITEBACKVALUE],
                       BH.[ACTIONID],
                       BH.[OPENINVOICE],
                       BH.[BATCHNO],
                       BH.[FEMISCTOTAL],
                       BH.[CreditInvoiceNo],
                       BH.[ManualFeeBreakDown],
                       BH.[BillSent],
                       BH.[DefaultBillLayoutReportID]
                  FROM [dbo].[BillHeader] BH
                 WHERE BH.[DRAFTNO] = @ID 
                   FOR XML AUTO)

    INSERT
      INTO [dbo].[BillLogging]
          ([DATE],
           [Handler],
           [DRAFTNO],
           [Action])
    SELECT GETDATE(),
           @HANDLERCODE,
           BH.[DRAFTNO],
           ''Deleted FROM Action: '' + CONVERT(VARCHAR(MAX), @xml)
      FROM [dbo].[BillHeader] BH
     WHERE BH.[DRAFTNO] = @ID

    EXEC [dbo].[KEYHM_BGDelete] @ID, 0
    DELETE BIH  FROM [dbo].[BillHeader]       AS BIH  WHERE BIH.[DRAFTNO]  = @ID
    DELETE BID  FROM [dbo].[BillDetails]      AS BID  WHERE BID.[DRAFTNO]  = @ID
    DELETE BFBD FROM [dbo].[BillFeeBreakDown] AS BFBD WHERE BFBD.[DRAFTNO] = @ID
END')
END
ELSE
BEGIN
EXEC ('
IF OBJECT_ID(N''KEYHM_DeleteDraftBillOnly'',N''P'') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_DeleteDraftBillOnly]
END')

    EXEC ('
CREATE PROCEDURE 
       [dbo].[KEYHM_DeleteDraftBillOnly]
      (@ID              INT,
       @HANDLERCODE     VARCHAR(10))

/*****************************************************************************
 * 
 * [ky_NETSPDeleteDraftBillOnlySAM4]
 * This procedure is used to delete the Bill related details
 * for a draft bill. This procedure can be called from:
 *   KAAS_DeleteAction
 *   KAAS_DeleteDraftBill
 * The above procedures take care of the associated Action as
 * well as the Bill information. This procedure only looks at
 * the Bill information, and assumes that the Action is taken
 * care of. 
 *                  
 * Do NOT call this procedure on its own.
 * 
 * Suitable for SAM4 only
 *
 * 2018-08-23   John Ginnane   Created
 * 2018-11-23   John Ginnane   KEYD-5577 - Fixed time not being unmarked as "draft in progress"
 * 2019-10-22   John Ginnane   KEYD-6161 - Added document reproduction support
 * 
 * Modification History	:                                                                              *
 * 2020-03-13	Rajesh P	from  ky_NETSPDeleteDraftBillOnly        
 *****************************************************************************/
AS
BEGIN
    DECLARE @xml XML

    SET @xml = (SELECT BH.[BillingID],
                       BH.[MatterCode],
                       BH.[BillDescription],
                       BH.[Addressee],
                       BH.[FeCode],
                       BH.[InvoiceTo],
                       BH.[Address],
                       BH.[Ref],
                       BH.[Type],
                       BH.[OpenInvoice],
                       BH.[BillDate],
                       BH.[TimeWriteDownDate],
                       BH.[TransferToPay],
                       BH.[Message],
                       BH.[InvoiceNo],
                       BH.[CreateBy],
                       BH.[EntryDate],
                       BH.[BillStatus],
                       BH.[ReleasedBy],
                       BH.[ReleasedDate],
                       BH.[AccountsClearedBy],
                       BH.[AccountsClearedDate],
                       BH.[Billlayout],
                       BH.[Branch],
                       BH.[CreditInvoiceNo],
                       BH.[ProForma],
                       BH.[DefaultBillLayoutReportID]
                  FROM [dbo].[Billhead] BH
                 WHERE BH.[BillingID] = @ID 
                   FOR XML AUTO)

    INSERT
      INTO [dbo].[BillLogging]
          ([DATE],
           [Handler],
           [DRAFTNO],
           [Action])
    SELECT GETDATE(),
           @HANDLERCODE,
           BH.[BillingID],
           ''Deleted FROM Action: '' + CONVERT(VARCHAR(MAX), @xml)
      FROM [dbo].[Billhead] BH
     WHERE BH.[BillingID] = @ID

    EXEC [dbo].[KEYHM_BGDelete] @ID

    DELETE FROM [dbo].[Billhead]             WHERE [BillingID]   = @ID
    DELETE FROM [dbo].[BillDetail]           WHERE [BillID]      = @ID
    DELETE FROM [dbo].[BillingGuideFormated] WHERE [BillGuideNo] = @ID
    DELETE FROM [dbo].[BillingGuide]         WHERE [BillingNo]   = @ID
    DELETE FROM [dbo].[BillBreakdown]        WHERE [BillingNo]   = @ID
    DELETE FROM [dbo].[BillingLog]           WHERE [BillingId]   = @ID
    DELETE FROM [dbo].[BillCompMatter]       WHERE [BillingNo]   = @ID

    UPDATE TIE
       SET TIE.[BILLED] = 0
      FROM [dbo].[TimeEntry] AS TIE
     WHERE TIE.[BILLED] = @ID * - 1
       AND @ID <> 0
    
    UPDATE TRN
       SET TRN.[DraftNo] = 0
      FROM [dbo].[Transactions] AS TRN
     WHERE TRN.[DraftNo] = @ID * -1
       AND @ID <> 0

    UPDATE [PJT]
       SET [PJT].[InvoiceNo] = 0
      FROM [dbo].[PrintJobTracker] AS [PJT]
     WHERE [PJT].[InvoiceNo] = @ID * -1
       AND @ID <> 0

    SET NOCOUNT OFF
END')
END
GO

IF [dbo].[ISSAM4]() = 1
BEGIN
    EXEC ('
IF OBJECT_ID(N''KEYHM_DeleteDraftBillOnlySAM4'',N''P'') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_DeleteDraftBillOnlySAM4]
END')

    EXEC ('
CREATE PROCEDURE 
       [dbo].[KEYHM_DeleteDraftBillOnlySAM4]
      (@ID              INT,
       @HANDLERCODE     VARCHAR(10))

/*******************************************************************************************************
* This procedure is used to delete the Bill related details for a draft bill. 						   *
* This procedure can be called from:																   *
*     KEYHM_DeleteAction																				   *
*     KEYHM_DeleteDraftBillSAM4																		   *
* The above procedures take care of the associated Action as well as the Bill information.			   *
* This procedure only looks at the Bill information, and assumes that the Action is taken care of.     *              
*																									   *
* Do NOT call this procedure on its own. 															   *
* Suitable for SAM4 only																			   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_DeleteDraftBillOnlySAM4]					   					   *
* Copied from			: [dbo].[ky_NETSPDeleteDraftBillOnlySAM4]									   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-22	Vinodhan K		Created                                                                *
*******************************************************************************************************/
AS
BEGIN
    DECLARE @xml XML

    SET @xml = (SELECT BH.[BillingID],
                       BH.[MatterCode],
                       BH.[BillDescription],
                       BH.[Addressee],
                       BH.[FeCode],
                       BH.[InvoiceTo],
                       BH.[Address],
                       BH.[Ref],
                       BH.[Type],
                       BH.[OpenInvoice],
                       BH.[BillDate],
                       BH.[TimeWriteDownDate],
                       BH.[TransferToPay],
                       BH.[Message],
                       BH.[InvoiceNo],
                       BH.[CreateBy],
                       BH.[EntryDate],
                       BH.[BillStatus],
                       BH.[ReleasedBy],
                       BH.[ReleasedDate],
                       BH.[AccountsClearedBy],
                       BH.[AccountsClearedDate],
                       BH.[Billlayout],
                       BH.[Branch],
                       BH.[CreditInvoiceNo],
                       BH.[ProForma],
                       BH.[DefaultBillLayoutReportID]
                  FROM [dbo].[Billhead] BH
                 WHERE BH.[BillingID] = @ID 
                   FOR XML AUTO)

    INSERT
      INTO [dbo].[BillLogging]
          ([DATE],
           [Handler],
           [DRAFTNO],
           [Action])
    SELECT GETDATE(),
           @HANDLERCODE,
           BH.[BillingID],
           ''Deleted FROM Action: '' + CONVERT(VARCHAR(MAX), @xml)
      FROM [dbo].[Billhead] BH
     WHERE BH.[BillingID] = @ID

    EXEC [dbo].[ky_BGDeleteSAM4] @ID

    DELETE FROM [dbo].[Billhead]             WHERE [BillingID]   = @ID
    DELETE FROM [dbo].[BillDetail]           WHERE [BillID]      = @ID
    DELETE FROM [dbo].[BillingGuideFormated] WHERE [BillGuideNo] = @ID
    DELETE FROM [dbo].[BillingGuide]         WHERE [BillingNo]   = @ID
    DELETE FROM [dbo].[BillBreakdown]        WHERE [BillingNo]   = @ID
    DELETE FROM [dbo].[BillingLog]           WHERE [BillingId]   = @ID
    DELETE FROM [dbo].[BillCompMatter]       WHERE [BillingNo]   = @ID

    UPDATE TIE
       SET TIE.[BILLED] = 0
      FROM [dbo].[TimeEntry] AS TIE
     WHERE TIE.[BILLED] = @ID * - 1
    
    UPDATE TRN
       SET TRN.[DraftNo] = 0
      FROM [dbo].[Transactions] AS TRN
     WHERE TRN.[DraftNo] = @ID * -1

    SET NOCOUNT OFF
END')
END
GO
IF OBJECT_ID(N'[KEYHM_DeleteIntellisense]',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_DeleteIntellisense]
GO
CREATE PROCEDURE [KEYHM_DeleteIntellisense]      
(      
	@Handler			VARCHAR(6),
	@Id					INT
)      
      
AS      
/*******************************************************************************************************
* This procedure is used To Delete the Intellisense.												   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_DeleteIntellisense]											   *
* Copied from			: [dbo].[ky_NETDeleteIntellisense]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 
BEGIN      
SET NOCOUNT ON   

	DELETE FROM   
		Intellisense   
	WHERE   
		Id = @Id   
		
	SELECT   
		RTRIM(Id) AS Id,   
		RTRIM(Handler) AS Handler,   
		RTRIM(Narrative) AS Narrative  
	FROM   
		Intellisense  
	WHERE  
		Handler = @Handler   
	ORDER by Narrative  
	
SET NOCOUNT OFF      
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_DeleteMyDayBook'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_DeleteMyDayBook]
  END
GO

CREATE PROCEDURE [dbo].[KEYHM_DeleteMyDayBook]
@RecordID INT
AS
/*******************************************************************************************************
* Delete a time book from [dbo].[Timedaybook] for the selected record.								   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_DeleteMyDayBook]												   *
* Copied from			: [dbo].[ky_NETDeleteMyDayBook]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
  DELETE
      Timedaybook
  WHERE
      RECORDID=@RecordID
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_DuplicateDocFolderTree'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_DuplicateDocFolderTree]
  END
GO

 CREATE PROCEDURE
        [dbo].[KEYHM_DuplicateDocFolderTree]
       (@originalid                INT)
AS
/*******************************************************************************************************
* Duplicates a folder tree to a new root										                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_DuplicateDocFolderTree]						  				   *
* Copied from			: [dbo].[ky_NETSPDuplicateDocFolderTree]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/ 
BEGIN

  DECLARE @fromid INT

  SELECT TOP 1 @fromid = [DF].[id]
    FROM [dbo].[DocFolders] [DF]
   WHERE [DF].[id] = @originalid
     AND [DF].[parent] IS NULL

  DECLARE @MAX INT

  DECLARE @data TABLE
         ([seq]                       INT              IDENTITY(1, 1)    NOT NULL      PRIMARY KEY,
          [id]                        INT                                NOT NULL,
          [parent]                    INT                                NOT NULL,
          [foldername]                VARCHAR(500)                       NOT NULL,
          [foldericon]                INT                                NOT NULL,
          [newfolder]                 BIT                                NOT NULL,
          [deletefolder]              BIT                                NOT NULL)
  
  IF (@fromid IS NOT NULL)
    BEGIN        
      INSERT
        INTO @data
            ([id],
             [parent],
             [foldername],
             [foldericon],
             [newfolder],
             [deletefolder])
      SELECT SRC.[id],
             SRC.[parent],
             SRC.[foldername],
             SRC.[foldericon],
             1,
             0
        FROM [dbo].[KEYHM_TF_GetDocFolders3](@fromid, 1, 1) SRC
    END

  SELECT @MAX = ISNULL(MAX([DF].[id]), 0) FROM [dbo].[DocFolders] [DF]

  DECLARE @new TABLE
         ([seq]                       INT              IDENTITY(1, 1)    NOT NULL      PRIMARY KEY,
          [oldid]                     INT                                NOT NULL      UNIQUE NONCLUSTERED,
          [newid]                     INT                                NOT NULL)

  INSERT
    INTO @new
        ([oldid],
         [newid])
  SELECT [DT].[id],
         0
    FROM @data [DT]
   WHERE [DT].[newfolder] = 1

  UPDATE [nw]
     SET [nw].[newid] = @MAX + [nw].[seq]
    FROM @new [NW]

  SET IDENTITY_INSERT [dbo].[DocFolders] ON

  INSERT
    INTO [dbo].[DocFolders]
        ([id],
         [foldername],
         [parent],
         [foldericon])
  SELECT [nw].[newid]                                            AS [id],
         [dt].[foldername]                                       AS [foldername],
         CASE ISNULL([pr].[newid], 0)
              WHEN 0 THEN CASE ISNULL([dt].[parent], 0)
                               WHEN 0 THEN NULL
                               ELSE [dt].[parent] END     
              ELSE [pr].[newid] END                              AS [parent],
         [dt].[foldericon]                                       AS [foldericon]
    FROM @data [dt]
         INNER JOIN @new [nw]
                 ON [nw].[oldid] = [dt].[id]
         LEFT OUTER JOIN @new [pr]
                      ON [pr].[oldid] = [dt].[parent]

  SET IDENTITY_INSERT [dbo].[DocFolders] OFF

  SELECT @MAX = ISNULL(MAX([DF].[id]), 0) + 1
    FROM [dbo].[DocFolders] [DF]

  DBCC CHECKIDENT('DocFolders', RESEED, @MAX)

  DELETE [DF]
    FROM @data [dt]
         INNER JOIN [dbo].[DocFolders] [DF]
                 ON [DF].[id] = [dt].[id]
   WHERE [dt].[deletefolder] = 1

  UPDATE [DF]
     SET [DF].[foldername] = [dt].[foldername],
         [DF].[parent] = CASE ISNULL([dt].[parent], 0)
                              WHEN 0 THEN NULL
                         ELSE [dt].[parent] END,
         [DF].[foldericon] = [dt].[foldericon]
    FROM @data [dt]
         INNER JOIN [dbo].[DocFolders] [DF]
                 ON [DF].[id] = [dt].[id]
   WHERE [dt].[deletefolder] = 0
     AND [dt].[newfolder] = 0

  DECLARE @newid INT

  SELECT TOP 1
         @newid = ISNULL([nw].[newid], dt.[id])
    FROM @data [dt]
         LEFT OUTER JOIN @new [nw]
                      ON [nw].[oldid] = [dt].[id]

  SELECT @newid [id]
  RETURN @newid
END
GO
IF OBJECT_ID(N'KEYHM_FetchAccountSetting',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KEYHM_FetchAccountSetting]
GO

CREATE PROCEDURE [dbo].[KEYHM_FetchAccountSetting]      
AS      
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FetchAccountSetting]											   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-22	Vinodhan K		Created                                                                *
*******************************************************************************************************/
BEGIN
	SELECT NAME AS [Name]
	FROM [control]
END
GO

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

CREATE PROCEDURE [KEYHM_FetchAllDiary] (
	@ACTIONID INT,
	@LoggedInHandler VARCHAR(10) = NULL)  

/*******************************************************************************************************
* This procedure is used to fetch diary item by actionid.											   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FetchAllDiary]			                                       *
* Copied from			: NA										                                   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-16	Vinodhan K		Created                                                                *
* 2020-05-04    Arun V          DYSTARTTIME convertsion issue fixes, KEYHM-592                         *
********************************************************************************************************/   
AS  
BEGIN  
SET NOCOUNT ON  
  SELECT  
        RTRIM(ISNULL(D.[CASECODE], ''))                     AS CASECODE,
		dbo.KEYHM_FNConvertUTCDateToTargetTimeZone(D.[DATE], @LoggedInHandler)  AS [DATE],  
        RTRIM(ISNULL(D.[STATUS], 0))                        AS [STATUS],  
        RTRIM(ISNULL(D.[ACTIONCODE], ''))                   AS ACTIONCODE,  
        RTRIM(ISNULL(D.[ACTIONSTATUS], ''))                 AS ACTIONSTATUS,  
        RTRIM(ISNULL(D.[ACTIONTYPE], ''))                   AS ACTIONTYPE,  
        RTRIM(ISNULL(D.[PROCESSTYPE], ''))                  AS PROCESSTYPE,  
        RTRIM(ISNULL(D.[FNCODE], ''))                       AS FNCODE,  
        RTRIM(ISNULL(D.[TEAMCODE], ''))                     AS TEAMCODE,
		CAST(RTRIM(LTRIM(CAST(D.[TEXT1] AS nVARCHAR(max)))) AS TEXT) as text3,  
		ISNULL(D.[TEXT1], '')                               AS TEXT1,  
        ISNULL(D.[TEXT2], '')                               AS TEXT2,  
        RTRIM(ISNULL(D.[DELEGATEDFNR], ''))                 AS DELEGATEDFNR,  
        RTRIM(ISNULL(D.[DELEGATEDDATE], ''))                AS DELEGATEDDATE,  
        RTRIM(ISNULL(D.[DELEGATEDBACKDATE], ''))            AS DELEGATEDBACKDATE,  
        RTRIM(ISNULL(D.[DEFERRED], ''))                     AS DEFERRED,
		dbo.KEYHM_FNConvertUTCDateToTargetTimeZone(D.[DUEDATE], @LoggedInHandler)  AS [DUEDATE],  
        RTRIM(ISNULL(D.[IMAGENO], ''))                      AS IMAGENO,  
        RTRIM(ISNULL(D.[PUBLISH], ''))                      AS PUBLISH,  

		--UTC time to LoggedIn Handler Time Zone , in case Logged In Handler is empty default to GMT
		CONVERT(VARCHAR(10),dbo.KEYHM_FNConvertUTCDateToTargetTimeZone(
				DATEADD(day,  DATEDIFF(day, 0, GETDATE()), dbo.KEYHM_FN_ConvertClarionTimeToHHMM(D.[DYSTARTTIME]))
		, @LoggedInHandler), 108)	 AS [DYSTARTTIME], 

		--UTC time to LoggedIn Handler Time Zone , in case Logged In Handler is empty default to GMT
		CONVERT(VARCHAR(10),dbo.KEYHM_FNConvertUTCDateToTargetTimeZone(
				DATEADD(day,  DATEDIFF(day, 0, GETDATE()), dbo.KEYHM_FN_ConvertClarionTimeToHHMM(D.[DYENDTIME])),
		@LoggedInHandler), 108)	AS [DYENDTIME],

        RTRIM(D.[DYSTARTTIME])                              AS [DYSTARTTIME1],  
        RTRIM(D.[DYENDTIME])                                AS [DYENDTIME1],  
        --CONVERT(VARCHAR, DATEADD(ms, 10 * (ISNULL(D.DYSTARTTIME, 0) - 0), CONVERT(VARCHAR, GETDATE(), 112)), 108) AS DYSTARTTIME,      
        --CONVERT(VARCHAR, DATEADD(ms, 10 * (ISNULL(D.DYENDTIME, 0) - 0), CONVERT(VARCHAR, GETDATE(), 112)), 108) AS DYENDTIME,      
        --stuff( right(CONVERT(VARCHAR, DATEADD(ms, 10 * (DYSTARTTIME - 1), CONVERT(VARCHAR, GETDATE(), 108)), 109), 15 ), 7, 7, ' ' ) AS DYSTARTTIME,          
        --stuff( right(CONVERT(VARCHAR, DATEADD(ms, 10 * (DYENDTIME - 1), CONVERT(VARCHAR, getDate(), 108)), 109), 15 ), 7, 7, ' ' ) AS DYENDTIME,          
        RTRIM(ISNULL(D.[DURATION], 0))                      AS DURATION,  
        RTRIM(ISNULL(D.[ACTIONID], 0))                      AS ACTIONID,  
        RTRIM(ISNULL(D.[ORGINALACTIONID], 0))               AS ORGINALACTIONID,  
        RTRIM(ISNULL(D.[PRIORITY], ''))                     AS [PRIORITY],  
        RTRIM(ISNULL(D.[HIGHLIGHTED], ''))                  AS HIGHLIGHTED,  
        RTRIM(ISNULL(D.[MILESTEONETYPE], ''))               AS MILESTONETYPE,  
        RTRIM(ISNULL(D.[ATTACHMENTS], ''))                  AS ATTACHMENTS,  
        RTRIM(ISNULL(D.[PROCESSSTATUS], 0))                 AS PROCESSSTATUS,  
        RTRIM(ISNULL(D.[WORKPROCESS], 0))                   AS WORKPROCESS,  
        RTRIM(ISNULL(D.[BILLABLE], 0))                      AS BILLABLE,  
        RTRIM(ISNULL(D.[BILLDESCRIPTION], ''))				AS BILLDESCRIPTION,  
        RTRIM(ISNULL(D.[EMAILADDRESS], ''))                 AS EMAILADDRESS,  
        ISNULL(D.[ADDRESSTO], '')                           AS ADDRESSTO,  
        ISNULL(D.[CCTo], '')                                AS CCTo,  
        ISNULL(D.[BCCTo], '')                               AS BCCTo,  
        RTRIM(ISNULL(D.[EMAIL], ''))                        AS EMAIL,  
        ISNULL(D.[SUBJECT], '')                             AS [SUBJECT],  
        RTRIM(ISNULL([DELEGATIONSTATUS], 0))                AS DELEGATIONSTATUS,  
        RTRIM(ISNULL([DRAFTBILLNO], 0))                     AS DRAFTBILLNO,  
        RTRIM(ISNULL(D.[CHEQUEREQNO], 0))                   AS CHEQUEREQNO,  
        RTRIM(ISNULL(D.[TxmSent], 0))                       AS TxmSent,  
        RTRIM(ISNULL(D.[Location], ''))                     AS Location,  
        RTRIM(ISNULL(D.[HearingType], ''))                  AS HearingType,  
        RTRIM(ISNULL(D.[ForCopy], ''))                      AS ForCopy,  
        RTRIM(ISNULL(D.[TxmDate], ''))                      AS TxmDate,  
        RTRIM(ISNULL(D.[TxmSeqNo], 0))                      AS TxmSeqNo,  
        RTRIM(ISNULL(D.[Flag],0))                           AS Flag,  
        RTRIM(ISNULL(H.[RETIRED],''))                       AS Retired,  
        RTRIM(ISNULL(H.[NAME],''))                          AS [Name],  
        M.[Closed]                                          AS [Closed],  
        ISNULL(D.[KYC],'N')                                 AS KYC,  
        ISNULL(S.[Retired],'N')                             AS ActionRetired,  
        RTRIM(ISNULL(TA.[Arrangement],''))                  AS [Arrangement],  
        RTRIM(ISNULL(M.[ChargeArrangement],''))             AS [ChargeArrangement],
		RTRIM(ISNULL([TA].[DESC], ''))                      AS [ActionCodeDescription]
    FROM  
        [DIARY] D    
        LEFT JOIN [Handlers] H    ON D.[FNCODE] = H.[CODE]  
        LEFT JOIN [matters] M     ON D.[CASECODE] = M.[Code]  
        LEFT JOIN [StatusCodes] S ON D.[ACTIONSTATUS] = S.[CODE]   
        LEFT OUTER JOIN TemplateActions TA ON D.ACTIONCODE = TA.ACTIONCODE  
        LEFT OUTER JOIN Templates T ON T.[WKCODE] = TA.WKTCODE  
    WHERE  
        [ACTIONID] = @ACTIONID  
SET NOCOUNT OFF  
END  
GO
IF OBJECT_ID(N'KEYHM_FetchAllRecentMatterList',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KEYHM_FetchAllRecentMatterList]
GO

CREATE PROCEDURE      
       [dbo].[KEYHM_FetchAllRecentMatterList]      
      (@Search  NVARCHAR(MAX),
	   @PageNumber INT,
       @PageSize INT)
AS      
/*******************************************************************************************************
* Performs a matter search based on search criteria passed in in XML format through @Search.           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_FetchAllRecentMatterList]										   *
* Copied from			: [dbo].[ky_NETSPXMLMatterSearch2]											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-05-02    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN      
      
DECLARE @closed                 NCHAR(1)      
DECLARE @orderby                NVARCHAR(50)      
DECLARE @order                  NVARCHAR(4)      
DECLARE @howmany                INT      
DECLARE @handler                NVARCHAR(10)      
DECLARE @which                  INT      
DECLARE @BitWiseID              BIGINT      
DECLARE @searchtext             VARCHAR(MAX)      
DECLARE @searchonlycode         VARCHAR(3)      
DECLARE @departmentdesc         VARCHAR(50)      
DECLARE @department             VARCHAR(5)      
DECLARE @worktypedesc           VARCHAR(50)      
DECLARE @worktype               VARCHAR(5)      
DECLARE @filecolourdesc         VARCHAR(20)      
DECLARE @filecolour             VARCHAR(3)      
DECLARE @feecode                VARCHAR(10)      
      
DECLARE @includename            BIT      
DECLARE @includedescription     BIT      
DECLARE @includeaddress         BIT      
DECLARE @includeemail           BIT      
DECLARE @includecode            BIT      
DECLARE @includeoldref          BIT      
DECLARE @includeuser1           BIT      
      
DECLARE @andorname              VARCHAR(3)      
DECLARE @andornamevalue         VARCHAR(200)      
DECLARE @andordescription       VARCHAR(3)      
DECLARE @andordescriptionvalue  VARCHAR(200)      
DECLARE @andoraddress           VARCHAR(3)      
DECLARE @andoraddressvalue      VARCHAR(200)      
DECLARE @andorcode              VARCHAR(3)      
DECLARE @andorcodevalue         VARCHAR(200)      
DECLARE @andorfeecode           VARCHAR(3)      
DECLARE @andorfeecodevalue      VARCHAR(200)      
DECLARE @andoroldref            VARCHAR(3)      
DECLARE @andoroldrefvalue       VARCHAR(200)      
DECLARE @andordept              VARCHAR(3)      
DECLARE @andordeptvalue         VARCHAR(200)      
DECLARE @andoruser1             VARCHAR(3)      
DECLARE @andoruser1value        VARCHAR(200)      
DECLARE @andoruser2             VARCHAR(3)      
DECLARE @andoruser2value        VARCHAR(200)      
DECLARE @andoruser3             VARCHAR(3)      
DECLARE @andoruser3value        VARCHAR(200)      
DECLARE @andoryourref           VARCHAR(3)      
DECLARE @andoryourrefvalue      VARCHAR(200)      
DECLARE @andorwtype             VARCHAR(3)      
DECLARE @andorwtypevalue        VARCHAR(200)      
      
DECLARE @iSL INT      
    
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   
      
BEGIN TRY      
EXEC sp_xml_preparedocument @iSL OUTPUT, @Search      
END TRY      
BEGIN CATCH      
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<search/>'      
END CATCH      
      
SELECT @closed = CASE ISNULL(SRC.[closed], N'N')      
                      WHEN N'Y' THEN N'Y'   
                      WHEN N'B' THEN N'B'      
                      ELSE N'N' END,      
       @orderby = ISNULL(SRC.[orderby], N''),      
       @order = CASE ISNULL(SRC.[order], N'DESC')
                     WHEN N'DESC'      
                          THEN N'DESC'      
                     ELSE N'ASC' END,      
       @howmany = ISNULL(SRC.[howmany], 500),      
       @handler = ISNULL(SRC.[handler], N''),      
       @which = CASE ISNULL(SRC.[which], 0)      
                     WHEN 1 THEN 1 --My Matters      
                     WHEN 2 THEN 2 --Recent Matters      
                     ELSE 0 END,   --All Matters      
       @searchtext = ISNULL(SRC.[search], ''),      
       @searchonlycode = ISNULL(SRC.[searchonlycode], ''),      
       @departmentdesc = ISNULL(SRC.[dept], ''),      
       @worktypedesc = ISNULL(SRC.[wtype], ''),      
       @filecolourdesc = ISNULL(SRC.[colour], ''),      
       @feecode = ISNULL(SRC.[feecodefilter], ''),      
       @includeaddress = ISNULL(SRC.[includeaddress], 0),      
       @includeemail = ISNULL(SRC.[includeemail], 0),      
       @includecode = ISNULL(SRC.[includecode], 0),      
       @includedescription = ISNULL(SRC.[includedescription], 0),      
       @includename = ISNULL(SRC.[includename], 0),      
       @includeoldref = ISNULL(SRC.[includeoldref], 0),      
       @includeuser1 = ISNULL(SRC.[includeuser1], 0),      
       @andorname = ISNULL(SRC.[andorname], ''),      
       @andornamevalue = ISNULL(SRC.[andornamevalue], ''),      
       @andordescription = ISNULL(SRC.[andordescription], ''),      
       @andordescriptionvalue = ISNULL(SRC.[andordescriptionvalue], ''),      
       @andoraddress = ISNULL(SRC.[andoraddress], ''),      
       @andoraddressvalue = ISNULL(SRC.[andoraddressvalue], ''),      
       @andorcode = ISNULL(SRC.[andorcode], ''),      
       @andorcodevalue = ISNULL(SRC.[andorcodevalue], ''),      
       @andorfeecode = ISNULL(SRC.[andorfeecode], ''),      
       @andorfeecodevalue = ISNULL(SRC.[andorfeecodevalue], ''),      
       @andoroldref = ISNULL(SRC.[andoroldref], ''),      
       @andoroldrefvalue = ISNULL(SRC.[andoroldrefvalue], ''),      
       @andordept = ISNULL(SRC.[andordept], ''),      
       @andordeptvalue = ISNULL(SRC.[andordeptvalue], ''),      
       @andoruser1 = ISNULL(SRC.[andoruser1], ''),      
       @andoruser1value = ISNULL(SRC.[andoruser1value], ''),      
       @andoruser2 = ISNULL(SRC.[andoruser2], ''),      
       @andoruser2value = ISNULL(SRC.[andoruser2value], ''),      
       @andoruser3 = ISNULL(SRC.[andoruser3], ''),      
       @andoruser3value = ISNULL(SRC.[andoruser3value], ''),      
       @andoryourref = ISNULL(SRC.[andoryourref], ''),      
       @andoryourrefvalue = ISNULL(SRC.[andoryourrefvalue], ''),      
       @andorwtype = ISNULL(SRC.[andorwtype], ''),      
       @andorwtypevalue = ISNULL(SRC.[andorwtypevalue], '')      
  FROM OPENXML(@iSL, N'search')      
  WITH ([closed]                   NCHAR(1)        '@closed',      
        [orderby]                  NVARCHAR(50)    '@orderby',      
        [order]                    NVARCHAR(4)     '@order',      
        [howmany]                  INT             '@howmany',      
        [handler]                  NVARCHAR(10)    '@handler',      
        [which]                    INT             '@which',      
        [search]                   VARCHAR(MAX)    '@search',      
        [searchonlycode]           VARCHAR(3)      '@searchonlycode',      
        [dept]                     VARCHAR(50)     '@departmentfilter',      
        [wtype]                    VARCHAR(50)     '@worktypefilter',      
        [colour]                   VARCHAR(20)     '@filecolourfilter',      
        [feecodefilter]            VARCHAR(10)     '@feecodefilter',      
        [includeaddress]           BIT             'include/includefield[@name="address"]',      
        [includecode]              BIT             'include/includefield[@name="code"]',      
        [includedescription]       BIT             'include/includefield[@name="description"]',      
        [includename]              BIT             'include/includefield[@name="name"]',      
        [includeoldref]            BIT             'include/includefield[@name="oldref"]',      
        [includeuser1]             BIT             'include/includefield[@name="user1"]',      
        [includeemail]             BIT             'include/includefield[@name="email"]',      
        [andorname]                VARCHAR(3)      'andor/andorfield[@name="name"]/@andor',      
        [andornamevalue]           VARCHAR(100)    'andor/andorfield[@name="name"]/@search',      
        [andordescription]         VARCHAR(3)      'andor/andorfield[@name="description"]/@andor',      
        [andordescriptionvalue]    VARCHAR(100)    'andor/andorfield[@name="description"]/@search',      
        [andoraddress]             VARCHAR(3)      'andor/andorfield[@name="address"]/@andor',      
        [andoraddressvalue]        VARCHAR(100)    'andor/andorfield[@name="address"]/@search',      
        [andorcode]                VARCHAR(3)      'andor/andorfield[@name="code"]/@andor',      
        [andorcodevalue]           VARCHAR(100)    'andor/andorfield[@name="code"]/@search',      
        [andorfeecode]             VARCHAR(3)      'andor/andorfield[@name="feecode"]/@andor',      
        [andorfeecodevalue]        VARCHAR(100)    'andor/andorfield[@name="feecode"]/@search',      
        [andoroldref]              VARCHAR(3)      'andor/andorfield[@name="oldref"]/@andor',      
        [andoroldrefvalue]         VARCHAR(100)    'andor/andorfield[@name="oldref"]/@search',      
        [andordept]                VARCHAR(3)      'andor/andorfield[@name="dept"]/@andor',      
        [andordeptvalue]           VARCHAR(100)    'andor/andorfield[@name="dept"]/@search',      
        [andoruser1]               VARCHAR(3)      'andor/andorfield[@name="user1"]/@andor',      
        [andoruser1value]          VARCHAR(100)    'andor/andorfield[@name="user1"]/@search',      
        [andoruser2]               VARCHAR(3)      'andor/andorfield[@name="user2"]/@andor',      
        [andoruser2value]          VARCHAR(100)    'andor/andorfield[@name="user2"]/@search',      
        [andoruser3]               VARCHAR(3)      'andor/andorfield[@name="user3"]/@andor',      
        [andoruser3value]          VARCHAR(100)    'andor/andorfield[@name="user3"]/@search',      
        [andoryourref]             VARCHAR(3)      'andor/andorfield[@name="yourref"]/@andor',      
        [andoryourrefvalue]        VARCHAR(100)    'andor/andorfield[@name="yourref"]/@search',      
        [andorwtype]               VARCHAR(3)      'andor/andorfield[@name="wtype"]/@andor',      
        [andorwtypevalue]          VARCHAR(100)    'andor/andorfield[@name="wtype"]/@search') SRC      
      
IF @filecolourdesc <> ''      
  BEGIN      
    SELECT @filecolour = FC.[COLOURCODE]      
      FROM [dbo].[FileColours] FC WITH (NOLOCK)      
     WHERE FC.[COLOURDESC] = @filecolourdesc      
  END      
      
SET @filecolour = ISNULL(@filecolour, '')      
      
IF @departmentdesc <> ''      
  BEGIN      
    SELECT @department = DP.[CODE]      
      FROM [dbo].[Departments] DP WITH (NOLOCK)      
     WHERE DP.[DESCRIPTION] = @departmentdesc      
  END      
      
SET @department = ISNULL(@department, '')      
      
IF @worktypedesc <> ''      
  BEGIN      
    IF @worktypedesc LIKE 'Unknown Worktype: %'      
      BEGIN      
        SELECT @worktype = WT.[CODE]      
          FROM [dbo].[WorkTypes] WT WITH (NOLOCK)      
         WHERE 'Unknown Worktype: ' + WT.[CODE] = @worktypedesc      
            OR WT.[DESC] = @worktypedesc      
      END      
    ELSE      
      BEGIN      
        SELECT @worktype = WT.[CODE]      
          FROM [dbo].[WorkTypes] WT WITH (NOLOCK)      
         WHERE WT.[DESC] = @worktypedesc      
      END      
  END      
      
SET @worktype = ISNULL(@worktype, '')      
      
SET @feecode = ISNULL(@feecode, '')      
      
EXEC sp_xml_removedocument @iSL      
      
DECLARE @NCOMMAND NVARCHAR(MAX)      
DECLARE @HasWhere BIT      
      
SET @HasWhere = 0      
      
SET @handler = CASE WHEN RTRIM(ISNULL(@handler, '')) = '' THEN 'ADM' ELSE RTRIM(@handler) END      
      
SELECT @BitWiseID = HNG.[BitWiseID]      
  FROM HandlerNETGroupMembership HNG WITH (NOLOCK)      
 WHERE HNG.[HANDLER] = CONVERT(VARCHAR(10), @handler)      
      
SET @BitWiseID = ISNULL(@BitWiseID, [dbo].[KEYHM_FN_GetOldPermissions](RTRIM(ISNULL(@handler, ''))))      
      
IF (@handler = 'ADM')      
  BEGIN      
    SET @BitWiseID = CONVERT(BIGINT, -1)      
  END      
      
SET @NCOMMAND = N'      
  --SELECT ''How Many: '' + CONVERT(VARCHAR(10), @HowMany)      
  --SELECT ''Handler: '' + @Handler      
  --SELECT ''BitWise ID: '' + CONVERT(VARCHAR(10), @BitWiseID)      
      
DECLARE @Result TABLE      
       ([id]                    INT                       IDENTITY(1, 1) PRIMARY KEY CLUSTERED,     
        [Code]                  VARCHAR(20)               NOT NULL,     
        [Name]                  VARCHAR(256)              NOT NULL,      
        [Description]           VARCHAR(200)              NOT NULL)      
      
  INSERT      
    INTO @Result      
        ([Code],      
         [Name],      
         [Description])      
    
  SELECT      
         SM.[Code]                                                                        AS [Code],     
         SM.[Name]                                                                        AS [Name],      
         SM.[Description]                                                                 AS [Description]      
    FROM [dbo].[SearchMatters] SM WITH (NOLOCK)      
         CROSS APPLY (SELECT SUBSTRING(CONVERT(VARCHAR, DATEADD(minute, ISNULL(SUM(ISNULL(TDB.[time], 0)), 0), ''19000101''), 108), 1, 5) AS [TOTALTIME]      
                        FROM [dbo].[TimeDayBook] TDB WITH (NOLOCK)      
                       WHERE TDB.[FeeEarn] = @Handler      
                         AND TDB.[matter] = SM.[code]) TTT'      
      
SET @NCOMMAND = @NCOMMAND + N'      
         LEFT OUTER JOIN [dbo].[RecentMatterList] RML WITH (NOLOCK)      
                      ON RML.[FEE] = @handler      
                     AND RML.[MATTER] = SM.[Code]'      
      
IF (@BitWiseID = 0)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   WHERE (   SM.[Privileges] = 0      
          OR SM.[Privileges] = -1)'      
  END      
ELSE IF (@BitWiseID = -1)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   WHERE 1 = 1'      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   WHERE SM.[Privileges] & @BitWiseID <> 0'      
  END      
      
IF (@which = 1)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode] = @handler'      
  END      
      
IF (@closed = 'N')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Closed] = 0'      
  END      
      
IF (@closed = 'Y')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Closed] = 1'      
  END      
      
IF (@worktype <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[WType] = @WorkType'      
  END      
      
IF (@department <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Dept] = @department'      
  END      
      
IF (@filecolour <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FileColour] = @filecolour'      
  END      
      
IF (@feecode <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode] = @feecode'      
  END      
      
DECLARE @SearchIncludes NVARCHAR(MAX)      
      
SET @SearchIncludes = N''      
      
IF (@searchtext <> '')      
  BEGIN      
    IF SUBSTRING(@searchtext, 1, 1) <> '%'      
      BEGIN      
        SET @searchtext = '%' + @searchtext      
      END      
      
    IF SUBSTRING(@searchtext, LEN(@searchtext), 1) <> '%'      
      BEGIN      
        SET @searchtext = @searchtext + '%'      
      END      
      
    SET @searchtext = @searchtext COLLATE SQL_Latin1_General_Cp1251_CS_AS      
          
     IF (@includeaddress = 0)       
    AND (@includecode = 0)      
    AND (@includedescription = 0)      
    AND (@includename = 0)      
    AND (@includeoldref = 0)      
    AND (@includeuser1 = 0)      
    AND (@includeemail = 0)      
      BEGIN      
        -- This is the standard call - not from Advanced Matter Search, so we search in everything      
        IF @SearchIncludes <> N''      
          BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
          END      
      
        IF @searchonlycode <> 'yes'      
          BEGIN      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]         LIKE @searchtext      
          OR SM.[Code]                     LIKE @searchtext      
          OR SM.[User1]                    LIKE @searchtext      
          OR SM.[User2]                    LIKE @searchtext      
          OR SM.[User3]                    LIKE @searchtext      
          OR SM.[OldRef]                   LIKE @searchtext      
          OR SM.[YourRef]                  LIKE @searchtext      
          OR SM.[NCName]                   LIKE @searchtext      
          OR SM.[NCAddress]                LIKE @searchtext      
          OR SM.[Email]                    LIKE @searchtext      
          OR SM.[NCHandlerName]            LIKE @searchtext      
          OR SM.[NCPartnerName]            LIKE @searchtext      
          OR SM.[DeptDescription]          LIKE @searchtext      
          OR SM.[WTypeDescription]         LIKE @searchtext      
          OR SM.[FileColourDescription]    LIKE @searchtext      
          OR SM.[MatterStatusDescription]  LIKE @searchtext'      
          END      
        ELSE      
          BEGIN      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Code]                  LIKE @searchtext'      
          END      
      
      END      
    ELSE      
      BEGIN      
        IF (@includeaddress = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCAddress]             LIKE @searchtext'      
          END      
      
        IF (@includecode = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Code]                  LIKE @searchtext'      
          END      
      
        IF (@includedescription = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]         LIKE @searchtext'      
          END      
      
        IF (@includename = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCName]                LIKE @searchtext'      
          END      
      
        IF (@includeoldref = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[OldRef]                LIKE @searchtext'      
          END      
      
        IF (@includeuser1 = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[User1]                 LIKE @searchtext'      
          END      
      
        IF (@includeemail = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Email]                 LIKE @searchtext'      
          END      
      
      END      
                  
  END      
      
IF @andoraddress = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoraddressvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = '%' + @andoraddressvalue       
      END      
      
    IF SUBSTRING(@andoraddressvalue, LEN(@andoraddressvalue), 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = @andoraddressvalue + '%'      
      END      
      
    SET @andoraddressvalue = @andoraddressvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCAddress]					LIKE @andoraddressvalue'      
  END      
      
IF @andorcode = 'OR'      
  BEGIN      
    IF CHARINDEX('%', @andorcodevalue, 1) = 0      
      BEGIN      
        IF SUBSTRING(@andorcodevalue, 1, 1) <> '%'      
          BEGIN      
            SET @andorcodevalue = '%' + @andorcodevalue       
          END      
      
        IF SUBSTRING(@andorcodevalue, LEN(@andorcodevalue), 1) <> '%'      
          BEGIN      
            SET @andorcodevalue = @andorcodevalue + '%'      
          END      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[Code]							LIKE @andorcodevalue'      
  END      
      
IF @andordept = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[Dept]= @andordeptvalue'      
  END      
      
IF @andordescription = 'OR'      
  BEGIN      
    IF SUBSTRING(@andordescriptionvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = '%' + @andordescriptionvalue       
      END      
      
    IF SUBSTRING(@andordescriptionvalue, LEN(@andordescriptionvalue), 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = @andordescriptionvalue + '%'      
      END      
      
    SET @andordescriptionvalue = @andordescriptionvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]			LIKE @andordescriptionvalue'      
  END      
      
IF @andorfeecode = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[FECode] = @andorfeecodevalue'      
  END      
      
IF @andorname = 'OR'      
  BEGIN      
    IF SUBSTRING(@andornamevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andornamevalue = '%' + @andornamevalue       
      END      
      
    IF SUBSTRING(@andornamevalue, LEN(@andornamevalue), 1) <> '%'      
      BEGIN      
        SET @andornamevalue = @andornamevalue + '%'      
      END      
      
    SET @andornamevalue = @andornamevalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCName]							LIKE @andornamevalue'      
  END      
      
IF @andoroldref = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoroldrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = '%' + @andoroldrefvalue       
      END      
      
    IF SUBSTRING(@andoroldrefvalue, LEN(@andoroldrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = @andoroldrefvalue + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[OldRef]							LIKE @andoroldrefvalue'      
  END      
      
IF @andoruser1 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser1value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser1value = '%' + @andoruser1value       
      END      
      
   IF SUBSTRING(@andoruser1value, LEN(@andoruser1value), 1) <> '%'      
      BEGIN      
        SET @andoruser1value = @andoruser1value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User1]						  LIKE @andoruser1value'      
  END      
      
IF @andoruser2 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser2value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser2value = '%' + @andoruser2value       
      END      
      
    IF SUBSTRING(@andoruser2value, LEN(@andoruser2value), 1) <> '%'      
      BEGIN      
        SET @andoruser2value = @andoruser2value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User2]						   LIKE @andoruser2value'      
  END      
      
IF @andoruser3 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser3value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser3value = '%' + @andoruser3value       
      END      
      
    IF SUBSTRING(@andoruser3value, LEN(@andoruser3value), 1) <> '%'      
      BEGIN      
        SET @andoruser3value = @andoruser3value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User3]						   LIKE @andoruser3value'      
  END      
      
IF @andorwtype = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[WType] = @andorwtypevalue'      
  END      
      
IF @andoryourref = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoryourrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = '%' + @andoryourrefvalue       
      END      
      
    IF SUBSTRING(@andoryourrefvalue, LEN(@andoryourrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = @andoryourrefvalue + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[YourRef]							LIKE @andoryourrefvalue'      
  END      
      
--SELECT @SearchIncludes      
      
IF @SearchIncludes <> ''      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND (   ' + @SearchIncludes + N')'      
  END      
      
IF @andoraddress = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoraddressvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = '%' + @andoraddressvalue       
      END      
      
    IF SUBSTRING(@andoraddressvalue, LEN(@andoraddressvalue), 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = @andoraddressvalue + '%'      
      END      
      
    SET @andoraddressvalue = @andoraddressvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCAddress]             LIKE @andoraddressvalue'      
  END      
      
IF @andorcode = 'AND'      
  BEGIN      
    IF SUBSTRING(@andorcodevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andorcodevalue = '%' + @andorcodevalue       
      END      
      
    IF SUBSTRING(@andorcodevalue, LEN(@andorcodevalue), 1) <> '%'      
      BEGIN      
        SET @andorcodevalue = @andorcodevalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Code]                  LIKE @andorcodevalue'      
  END      
      
IF @andordept = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Dept]              = @andordeptvalue'      
  END      
      
IF @andordescription = 'AND'      
  BEGIN      
    IF SUBSTRING(@andordescriptionvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = '%' + @andordescriptionvalue       
      END      
      
    IF SUBSTRING(@andordescriptionvalue, LEN(@andordescriptionvalue), 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = @andordescriptionvalue + '%'      
      END      
      
    SET @andordescriptionvalue = @andordescriptionvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCDescription]         LIKE @andordescriptionvalue'      
  END      
      
IF @andorfeecode = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode]                = @andorfeecodevalue'      
  END      
      
IF @andorname = 'AND'      
  BEGIN      
    IF SUBSTRING(@andornamevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andornamevalue = '%' + @andornamevalue       
      END      
      
IF SUBSTRING(@andornamevalue, LEN(@andornamevalue), 1) <> '%'      
      BEGIN      
        SET @andornamevalue = @andornamevalue + '%'      
      END      
      
    SET @andornamevalue = @andornamevalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCName]                LIKE @andornamevalue'      
  END      
      
IF @andoroldref = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoroldrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = '%' + @andoroldrefvalue       
      END      
      
    IF SUBSTRING(@andoroldrefvalue, LEN(@andoroldrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = @andoroldrefvalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[OldRef]                LIKE @andoroldrefvalue'      
  END      
      
IF @andoruser1 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser1value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser1value = '%' + @andoruser1value       
      END      
      
    IF SUBSTRING(@andoruser1value, LEN(@andoruser1value), 1) <> '%'      
      BEGIN      
        SET @andoruser1value = @andoruser1value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User1]                 LIKE @andoruser1value'      
  END      
      
IF @andoruser2 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser2value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser2value = '%' + @andoruser2value       
      END      
      
    IF SUBSTRING(@andoruser2value, LEN(@andoruser2value), 1) <> '%'      
      BEGIN      
        SET @andoruser2value = @andoruser2value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User2]                 LIKE @andoruser2value'      
  END      
      
IF @andoruser3 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser3value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser3value = '%' + @andoruser3value       
      END      
      
    IF SUBSTRING(@andoruser3value, LEN(@andoruser3value), 1) <> '%'      
      BEGIN      
        SET @andoruser3value = @andoruser3value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User3]                 LIKE @andoruser3value'      
  END      
      
IF @andorwtype = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[WType]                 = @andorwtypevalue'      
  END      
      
IF @andoryourref = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoryourrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = '%' + @andoryourrefvalue       
      END      
      
    IF SUBSTRING(@andoryourrefvalue, LEN(@andoryourrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = @andoryourrefvalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[YourRef]               LIKE @andoryourrefvalue'      
  END      
      
--SELECT @orderby, @order      
      
SET @NCOMMAND = @NCOMMAND + N'      
ORDER BY ' + CASE @orderby      
                  WHEN N'description'      
                       THEN N'CASE WHEN SM.[Description] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Description] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Code'      
                       THEN N'CASE WHEN SM.[Code] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Code] ' + @order      
                  WHEN N'Name'      
                       THEN N'CASE WHEN SM.[Name] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Name] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Address'      
                       THEN N'CASE WHEN SM.[Address] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Address] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Email'      
                       THEN N'CASE WHEN SM.[Email] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Email] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'PhoneNumber'      
                       THEN N'CASE WHEN SM.[PhoneNumber] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[PhoneNumber] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'user1'      
                      THEN N'CASE WHEN SM.[User1] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User1] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'user2'      
                       THEN N'CASE WHEN SM.[User2] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User2] ' + @order + N',      
         SM.[Code] ' + @order      
    WHEN N'user3'      
                       THEN N'CASE WHEN SM.[User3] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User3] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'yourref'      
                       THEN N'CASE WHEN SM.[YourRef] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[YourRef] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'OldRef'      
                       THEN N'CASE WHEN SM.[OldRef] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[OldRef] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileNum'      
                       THEN N'CASE WHEN SM.[FileNum] = 0      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileNum] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'department'      
                       THEN N'CASE WHEN SM.[DeptDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[DeptDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Dept'      
                       THEN N'CASE WHEN SM.[DeptDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[DeptDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'worktype'      
                       THEN N'CASE WHEN SM.[WTypeDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[WTypeDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FeeCode'      
                       THEN N'CASE WHEN SM.[FECode] = ''''      
                   THEN 2      
              WHEN SM.[FECode] = ''ADM''      
                   THEN 1      
 ELSE 0 END,      
         SM.[FECode] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FeeEarner'      
                       THEN N'CASE WHEN SM.[HandlerName] = '''' AND SM.[FECode] = ''''      
                   THEN 3      
              WHEN SM.[HandlerName] = ''''      
                   THEN 2      
              WHEN SM.[HandlerName] = ''Admin''      
                   THEN 1      
              ELSE 0 END,      
         SM.[HandlerName] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileColour_Fld'      
                       THEN N'CASE WHEN SM.[FileColourDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileColourDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileColour'      
                       THEN N'CASE WHEN SM.[FileColourDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileColourDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'started'      
                       THEN N'SM.[Started] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'LastAccessed'      
                       THEN N'CASE WHEN RML.[DateField] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         RML.[DateField] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'closedate'      
                       THEN N'CASE WHEN SM.[CloseDate] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[CloseDate] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'orgcloseddate'      
                       THEN N'CASE WHEN SM.[orgcloseddate] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[orgcloseddate] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'casestatusdesc'      
                       THEN N'CASE WHEN SM.[MatterStatusDescription] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[MatterStatusDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  ELSE CASE WHEN @Which <> 2      
                                 THEN N'SM.[Code] ' + @order      
                            ELSE N'CASE WHEN RML.[DateField] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         RML.[DateField] DESC,      
         SM.[Code] ' + @order END END      
      
SET @NCOMMAND = @NCOMMAND + N'    
        
	SELECT * FROM(    
  		SELECT ROW_NUMBER() OVER(ORDER BY [RES].[id]) AS [RowNumber],      
		[RES].[Code],      
		[RES].[Name],      
		[RES].[Description]      
	FROM
		@Result [RES])AS MatterTable WHERE MatterTable.[RowNumber] BETWEEN @StartRow AND @EndRow ORDER BY MatterTable.[RowNumber] ASC     
      
	SELECT  
		COUNT([RES].[id]) AS [TotalRecord]  
	FROM  
		@Result [RES]'  
  
--SELECT @NCOMMAND      
      
EXECUTE sp_executesql @NCOMMAND,      
                      N'@HowMany               INT,      
                        @BitWiseID             BIGINT,      
                        @Handler               VARCHAR(10),      
                        @WorkType              VARCHAR(5),      
                        @department            VARCHAR(5),      
                        @filecolour            VARCHAR(3),      
                        @feecode               VARCHAR(10),      
                        @searchtext            VARCHAR(MAX),      
                        @andoraddressvalue     VARCHAR(200),      
                        @andorcodevalue        VARCHAR(200),      
                        @andordeptvalue        VARCHAR(200),      
                        @andordescriptionvalue VARCHAR(200),      
                        @andorfeecodevalue     VARCHAR(200),      
                        @andornamevalue        VARCHAR(200),      
                        @andoroldrefvalue      VARCHAR(200),      
                        @andoruser1value       VARCHAR(200),      
                        @andoruser2value       VARCHAR(200),      
                        @andoruser3value       VARCHAR(200),      
                        @andorwtypevalue       VARCHAR(200),      
                        @andoryourrefvalue     VARCHAR(200),    
			@StartRow      INT,    
			@EndRow          INT',      
                      @Howmany,      
                      @BitWiseID,      
                      @handler,      
                      @worktype,      
                      @department,      
                      @filecolour,      
                      @feecode,      
                      @searchtext,      
                      @andoraddressvalue,      
                      @andorcodevalue,      
                      @andordeptvalue,      
                      @andordescriptionvalue,      
                      @andorfeecodevalue,      
                      @andornamevalue,      
                      @andoroldrefvalue,      
                      @andoruser1value,      
                      @andoruser2value,      
                      @andoruser3value,      
                      @andorwtypevalue,      
                      @andoryourrefvalue,    
		      @StartRow,    
		      @EndRow    
END
GO
IF OBJECT_ID(N'KEYHM_FetchContactForEdit_KEYHM',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KEYHM_FetchContactForEdit_KEYHM]
GO

CREATE PROCEDURE  
       [dbo].[KEYHM_FetchContactForEdit_KEYHM]    
      (@Code     VARCHAR(20),    
       @Handler  VARCHAR(10),
	   @SearchText	 VARCHAR(4000))    
AS
  
/***************************************************************************************************************
* This stored procedure is used to FETCH CLIENT and OTHER details by Contact Code to update details            *
* for Keyhouse Mobile App                                                                                      *
*                                                                                                              *
* Stored Procedure Name: [dbo].[KEYHM_FetchContactForEdit_KEYHM]								                   *
* Copied from		   : [dbo].[ky_NETCONFetchContactForEdit]                                                  *
*                                                                                                              *
* Modification History:                                                                                        *
* 2019-04-26     Vinodhan K        Created                                                                     *
* 2019-07-01     Vinodhan K        Full name will be filled with Firstname and Surname if its empty or null    *  
 ***************************************************************************************************************/  
BEGIN  
SET NOCOUNT ON  
   
--Client Details    
SELECT [CON].[Code],    
       [CON].[Name],    
       [CON].[Address],    
       [CON].[Salut],    
       [CON].[Tel],    
       [CON].[Fax],    
       [CON].[Email],    
       [CON].[Principal],    
       [CON].[FE],    
       [CON].[Nation],    
       [CON].[Spouse],    
       CONVERT(VARCHAR(10), [CON].[DOB], 112)           AS [DOB],    
       CONVERT(VARCHAR(10), [CON].[SpouseDOB], 112)     AS [SpouseDOB],    
       [CON].[Introducer],    
       [CON].[IntroFE],    
       [CON].[Comments],    
       CASE WHEN ISNULL([CON].[Corporate], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [Corporate],    
       CONVERT(VARCHAR(10),    
               [CON].[DateOfMarriage],    
               112)                                     AS [DateOfMarriage],    
       CASE WHEN ISNULL([CON].[SpouseDead], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [IsDead],    
       CASE WHEN ISNULL([CON].[Separated], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [IsSeparated],    
       [CON].[HowSeparated],    
       [CON].[Partner],    
       CONVERT(VARCHAR(10), [CON].[PartnerSince], 112)  AS [PartnerSince],    
       [CON].[Occupation],    
       [CON].[OtherRef],    
       [CON].[ChargeArrangement],    
       [CON].[BillingMethod],    
       [CON].[Approved] AS [Approved],    
       [CON].[SpousePPS],    
       [CON].[ClientGroup],    
       [CON].[ClientVATNo],    
       CASE WHEN ISNULL([CON].[ChargeOutRateInd], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [ChargeOutRateInd],    
       [CON].[TaxType],    
       [CLT].[CLGRP],    
       [CLT].[ClLegalName]                              AS [ClLegalName],    
       [CLT].[CllegalAddr]                              AS [CllegalAddr],    
       [CLT].[CLTEL]                                    AS [CLTEL],    
       [CLT].[CLMobNo],    
       [CLT].[CLMartialCde],    
       [CLT].[CLOccupCDE],    
       [CLT].[CLEmployer],    
       [CLT].[CLContactCde],    
       [CLT].[DcoumentFolder]                           AS [DcoumentFolder],    
       [CON].[CompFrequency],    
       CASE WHEN ISNULL([CON].[InActive], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [IsDeceased],    
       CONVERT(VARCHAR(10), [CON].DateInActive, 112)    AS [DOD],    
       [CON].[RSINo]                                    AS [PPSNo],    
       CASE WHEN ISNULL([CON].[Statements], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [IsStatement],    
 CASE WHEN ISNULL([CON].[Inactive], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [InActive],    
       CONVERT(VARCHAR(10), [CON].[DateInactive], 112)  AS [Dateinactive],    
       CONVERT(VARCHAR(10), [CON].[LastAR], 112)        AS [LastAr],    
       [CON].[CRONumber],    
       [CON].[CompanyWebSite],    
       [CON].[OtherAddress],    
       [CON].[County],    
       [CON].[PostalCode],    
       [CON].[CompMatter],    
       [CON].[BankName],    
       [CON].[BankAddress],    
       [CON].[BankSortCode],    
       [CON].[BankAccNo],    
       [CON].[IBan],    
       [CON].[Bic],    
       [CON].[EnvelopeName],    
       [CON].[ChargeLevel]                              AS [ChargeLevel],    
       [CON].[WarningMsg]                               AS [WarningMessage],    
       ISNULL([CON].[DisallowNewMatter], 0)             AS [DisallowNewMatter],    
       ISNULL([MC].[Retired], 'N')                      AS [Retired],    
       [DXAddress]                                      AS [DXAddress],    
       [SecondaryEmail]                                 AS [SecondaryEmail],    
       REPLACE(ISNULL([FC].[Retired], 'N'),' ','N')     AS [FeeEarnerRetired],    
       [CON].[Password],    
       CASE WHEN ISNULL([CON].[RemoteAccess], 'N') = 'Y'    
                 THEN '1'    
            ELSE '0' END                                AS [RemoteAccess],    
       ISNULL([CON].[BankType], '')                     AS [BankType]    
  FROM [dbo].[matters] [MAT]    
       LEFT OUTER JOIN [dbo].[Contacts] [CON]    
                    ON [CON].[Code] = [MAT].[ClientCode]    
       LEFT OUTER JOIN [dbo].[client] [CLT]    
       LEFT OUTER JOIN [dbo].[MiscCodes] [MC]    
                    ON [MC].[CDECODE] = [CLT].[ClMartialCde]    
                    ON [CLT].[CLCODE] = [MAT].[ClientCode]    
       LEFT OUTER JOIN [dbo].[FeeEarnerCodes] [FC]    
                    ON [FC].[Code] = [CON].[FE]    
 WHERE [MAT].[Code] = @Code  
   
--Other Contacts  
DECLARE @ClientCode VARCHAR(20)  
    
SET @ClientCode = (SELECT TOP 1 [MAT].[ClientCode]    
                     FROM [dbo].[matters] [MAT]    
                    WHERE [MAT].[Code] = @Code)  
                       
SELECT [CC].[CLINITS]                                AS [Initials],
	   CASE
			WHEN
				ISNULL(CC.[CLNAMECON], '') = '' OR CC.[CLNAMECON] = ''
			THEN
				[CC].[FIRSTNAME] + ' ' + [CC].[SURNAME]
		ELSE
			[CC].[CLNAMECON]
		END											 AS [FullName],
       [CC].[HomePhone]                              AS [HomePhone],    
       [CC].[WorkPhone]                              AS [WorkPhone],    
       [CC].[Mobile]                                 AS [Mobile],    
       [CC].[FIRSTNAME]                              AS [FirstName],    
       [CC].[SURNAME]                                AS [Surname],    
       [CC].[CLSALUTE]                               AS [Salutation],    
       [CC].[PPSNo]                                  AS [PPSNumber],    
       [CC].[CLTITLE]                                AS [Title],    
       [CC].[Address],    
       [CC].[EmailAddress],    
       CONVERT(VARCHAR(11), [CC].[DOB], 106)         AS [DOB],    
       CONVERT(VARCHAR(11), [CC].[MarrigeDate], 106) AS [MarriageDate],    
       [CC].[Occupation],    
       [CC].[DateofDeath]                            AS [DateOfDeath],    
       [MC].[CDEDESC]                                AS [MaritalStatus],    
       [CC].[MartialStatus]                          AS [MStatus],    
       [CC].[FaxNumber],    
       [CC].[PostalCode],    
       [CC].[County],    
       [CC].[CLNUMCONTACT],    
       [CC].[DXREF]
  FROM [dbo].[ClientContacts] [CC]    
       LEFT OUTER JOIN [dbo].[MiscCodes] [MC]    
                    ON [MC].[CDECODE] = [CC].[MartialStatus]    
                   AND [MC].[CDETYPE] = 'MRS'    
 WHERE [CC].[CLCODE] = @ClientCode
	   AND (
			 @SearchText = ''
			 OR
			 ([CC].[CLNAMECON] LIKE '%' + @SearchText + '%')
			) 
    
SET NOCOUNT OFF    
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FetchDiaryAttachments'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_FetchDiaryAttachments]
  END
GO

CREATE PROCEDURE 
       [dbo].[KEYHM_FetchDiaryAttachments]
      (@DIARYID Integer,
	  @Handler VARCHAR(10))
/*******************************************************************************************************
* This procedure is used load the data for TaskAddAction page Attachment Grid.						   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FetchDiaryAttachments]										   *
* Copied from			: [dbo].[ky_NETCCFetchDiaryAttachments]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 
AS
BEGIN
SET NOCOUNT ON


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

  SELECT [DAT].[ActionID]                                                                   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].[DocumentDate], 20)                                         AS [DATEENTERED],
         RTRIM(ISNULL([DAT].[DOCCLASS], ''))                                               AS [DOCCLASS],
         CONVERT(VARCHAR, [DAT].[DiaryDate], 20)                                      AS [LASTACCESSDATE],         
         RTRIM(ISNULL([DAT].[SOURCE], ''))                                                 AS [Source],         
         [DV].[CurrentVersion]                                                             AS [CurrentVersion],
         RTRIM(ISNULL([DX].[IMDocID], ''))                                                 AS [IMDocID],
         [MAT].[uniqueid]                                                                  AS [UniqueId]
    FROM [dbo].[DiaryAttachmentSelector] [DAT]
         INNER JOIN [dbo].[diary] [DIA]
                    INNER JOIN [dbo].[matters] [MAT]
                            ON [MAT].[Code] = [DIA].[CASECODE]
                 ON [DIA].[ActionID] = [DAT].[ActionID]
         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].[ActionID] = @DIARYID
ORDER BY [DAT].[TRACKREFERENCE] DESC

SET NOCOUNT OFF
END

GO
  IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FetchDiaryByMatterCode'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_FetchDiaryByMatterCode]
  END
GO
CREATE PROCEDURE
       [dbo].[KEYHM_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,
	   @LoggedInHandler VARCHAR(10) = NULL )
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [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									                     *
 *************************************************************************************************************/
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

   --    -- 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.KEYHM_FNConvertUTCDateToTargetTimeZone([DIA].[DATE], @LoggedInHandler)							AS [DATE],
		CONVERT(VARCHAR(5),dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([DIA].[DATE], @LoggedInHandler), 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],
        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.KEYHM_FNConvertUTCDateToTargetTimeZone([DIA].[DUEDATE], @LoggedInHandler)	, 20)
			ELSE
				CONVERT(VARCHAR, dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([DIA].[DATE], @LoggedInHandler)	, 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
 ORDER BY [FND].[id]

End
GO

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

CREATE PROCEDURE 
       [dbo].[KEYHM_FetchDiaryDelegations]
      (@ACTIONID INT,
       @ASSIGNNO INT,
       @STATUS INT)
/*******************************************************************************************************
* This procedure is used load the data for TaskAddAction page Delegation Grid.                         *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FetchDiaryDelegations]                                           *
* Copied from			: [dbo].[ky_NETCCFetchDiaryDelegations]                                        *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
AS
BEGIN

SET NOCOUNT ON

DECLARE @BY VARCHAR(100)
DECLARE @FOR VARCHAR(100)

IF(@STATUS = 2)
  BEGIN
      SELECT D.[ACTIONID]                                                                                    AS [ACTIONID],
             RTRIM(ISNULL(D.[HANDLER], ''))                                                                  AS [HANDLER],
             RTRIM(ISNULL(D.[TEAM], ''))                                                                     AS [TEAM],
             D.[DATE]                                                                                        AS [DATE],
             CONVERT(VARCHAR(5),
                     [dbo].[ky_ConvertDateAndClarionTimeToDateTime]('19000101', D.[TIME]),
                     108)                                                                                    AS [TIME],
             D.[DATER]                                                                                       AS [DATER],
             CASE WHEN D.[TIMER] IS NULL
                       THEN ''
                  ELSE CONVERT(VARCHAR(5),
                               [dbo].[ky_ConvertDateAndClarionTimeToDateTime]('19000101', D.[TIMER]),
                               108) END                                                                      AS [TIMER],
             D.[DUEDATE]                                                                                     AS [DUEDATE],
             CONVERT(VARCHAR(5),
                     [dbo].[ky_ConvertDateAndClarionTimeToDateTime]('19000101', D.[DUETIME]),
                     108)                                                                                    AS [DUETIME],
             RTRIM(ISNULL(D.[REVIEW], ''))                                                                   AS [REVIEW],
             RTRIM(ISNULL(D.[STATUS], 0))                                                                    AS [STATUS],
             RTRIM(ISNULL(D.[OWNER], 'N'))                                                                   AS [OWNER],
             RTRIM(ISNULL(D.[DELEGATE], ''))                                                                 AS [DELEGATE],
             RTRIM(ISNULL(D.[DELEGATESTATUS], 0))                                                            AS [DELEGATESTATUS],
             RTRIM(ISNULL(D.[ACTIONTYPE], ''))                                                               AS [ACTIONTYPE],
             RTRIM(ISNULL(D.[ASSIGNNO], 0))                                                                  AS [ASSIGNNO],
             RTRIM(ISNULL(D.[FROMHANDLER], ''))                                                              AS [FROMHANDLER],
             RTRIM(ISNULL(D.[RETURNEDBY], ''))                                                               AS [RETURNEDBY],
             RTRIM(ISNULL(D.[DELTYPE], ''))                                                                  AS [DELTYPE],
             CASE WHEN ISNULL(D.[DelType], '') = 'Created'
                       THEN RTRIM(H.[NAME]) + '(' +  RTRIM(ISNULL(D.[HANDLER], '')) + ')'
                  WHEN ISNULL(D.[ReturnedBy], '') = ''
                       THEN RTRIM(GH.[NAME]) + '(' +  RTRIM(ISNULL(D.[FromHandler], '')) + ')'
                  ELSE RTRIM(FH.[NAME]) + '(' +  RTRIM(ISNULL(D.[ReturnedBy], '')) + ')' END                 AS [BY],
             RTRIM(ISNULL(H.[NAME], '')) + '(' +  RTRIM(D.[HANDLER]) + ')'                                   AS [FOR]
        FROM dbo.[DiaryDelegations] D
             LEFT OUTER JOIN [dbo].[Handlers] H 
                          ON H.[CODE] = D.[HANDLER]
             LEFT OUTER JOIN [dbo].[Handlers] FH
                          ON FH.[CODE] = D.[ReturnedBy]
             LEFT OUTER JOIN [dbo].[Handlers] GH
                          ON GH.[CODE] = D.[FromHandler]
       WHERE D.[ACTIONID] = @ACTIONID
    ORDER BY D.[AssignNo] DESC
  END
ELSE
  BEGIN
      SELECT D.[ACTIONID]                                                                                    AS [ACTIONID],
             RTRIM(ISNULL(D.[HANDLER], ''))                                                                  AS [HANDLER],
             RTRIM(ISNULL(D.[TEAM], ''))                                                                     AS [TEAM],
             D.[DATE]                                                                                        AS [DATE],
             CONVERT(VARCHAR(5),
                     [dbo].[ky_ConvertDateAndClarionTimeToDateTime]('19000101', D.[TIME]),
                     108)                                                                                    AS [TIME],
             D.[DATER]                                                                                       AS [DATER],
             CASE WHEN D.[TIMER] IS NULL
                       THEN ''
                  ELSE CONVERT(VARCHAR(5),
                               [dbo].[ky_ConvertDateAndClarionTimeToDateTime]('19000101', D.[TIMER]),
                               108) END                                                                      AS [TIMER],
             D.[DUEDATE]                                                                                     AS [DUEDATE],
             CONVERT(VARCHAR(5),
                     [dbo].[ky_ConvertDateAndClarionTimeToDateTime]('19000101', D.[DUETIME]),
                     108)                                                                                    AS [DUETIME],
             RTRIM(ISNULL(D.[REVIEW], ''))                                                                   AS [REVIEW],
             RTRIM(ISNULL(D.[STATUS], 0))                                                                    AS [STATUS],
             RTRIM(ISNULL(D.[OWNER], 'N'))                                                                   AS [OWNER],
             RTRIM(ISNULL(D.[DELEGATE], ''))                                                                 AS [DELEGATE],
             RTRIM(ISNULL(D.[DELEGATESTATUS], 0))                                                            AS [DELEGATESTATUS],
             RTRIM(ISNULL(D.[ACTIONTYPE], ''))                                                               AS [ACTIONTYPE],
             RTRIM(ISNULL(D.[ASSIGNNO], 0))                                                                  AS [ASSIGNNO],
             RTRIM(ISNULL(D.[FROMHANDLER], ''))                                                              AS [FROMHANDLER],
             RTRIM(ISNULL(D.[RETURNEDBY], ''))                                                               AS [RETURNEDBY],
             RTRIM(ISNULL(D.[DELTYPE], ''))                                                                  AS [DELTYPE],
             CASE WHEN ISNULL(D.[DelType], '') = 'Created'
                       THEN RTRIM(H.[NAME]) + '(' +  RTRIM(ISNULL(D.[HANDLER], '')) + ')'
                  WHEN ISNULL(D.[ReturnedBy], '') = ''
                       THEN RTRIM(GH.[NAME]) + '(' +  RTRIM(ISNULL(D.[FromHandler], '')) + ')'
                  ELSE RTRIM(FH.[NAME]) + '(' +  RTRIM(ISNULL(D.[ReturnedBy], '')) + ')' END                 AS [BY],
             RTRIM(ISNULL(H.[NAME], '')) + '(' +  RTRIM(D.[HANDLER]) + ')'                                   AS [FOR]
        FROM dbo.[DiaryDelegations] D
             LEFT OUTER JOIN [dbo].[Handlers] H 
                          ON H.[CODE] = D.[HANDLER]
             LEFT OUTER JOIN [dbo].[Handlers] FH
                          ON FH.[CODE] = D.[ReturnedBy]
             LEFT OUTER JOIN [dbo].[Handlers] GH
                          ON GH.[CODE] = D.[FromHandler]
       WHERE D.[AssignNo] = @ASSIGNNO
END

SET NOCOUNT OFF
END

GO
IF OBJECT_ID(N'[KEYHM_FetchIntellisense]',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_FetchIntellisense]
GO
CREATE PROCEDURE [KEYHM_FetchIntellisense]      
(      
	@Handler			VARCHAR(6)
)      
      
AS      
/*******************************************************************************************************
* This procedure is used To fetch the Intellisense.													   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FetchIntellisense]											   *
* Copied from			: [dbo].[ky_NETFetchIntellisense]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/
BEGIN      
	SET NOCOUNT ON   
	SELECT 
		RTRIM(Id) AS Id, 
		RTRIM(Handler) AS Handler, 
		RTRIM(Narrative) AS Narrative
	FROM 
		Intellisense
	WHERE
		Handler = @Handler 
		ORDER by Narrative 
	SET NOCOUNT OFF      
END
GO
IF OBJECT_ID(N'KEYHM_FetchMinutesPerUnit',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KEYHM_FetchMinutesPerUnit]
GO

CREATE PROCEDURE [dbo].[KEYHM_FetchMinutesPerUnit]     
AS      
/*******************************************************************************************************
*                                                                                                      *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_FetchMinutesPerUnit]					                           *
* Copied from			: [dbo].[ky_NETDashboardCaseAlert]			                                   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-22    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
	DECLARE @TUTNUMVALUE DECIMAL(17, 2) 
	SELECT @TUTNUMVALUE = CTN.[NumValue]  
	  FROM [dbo].[CtrlNum] CTN  
	 WHERE CTN.[Code] = 'TimeUnit'   
  
    SET @TUTNUMVALUE = CASE 
						WHEN ISNULL(@TUTNUMVALUE, 0) = 0 
							THEN 6 
						ELSE @TUTNUMVALUE 
					   END

	SELECT @TUTNUMVALUE AS [MinutesPerUnit]
END
GO
IF OBJECT_ID(N'KEYHM_FetchTimeEntry',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KEYHM_FetchTimeEntry]
GO

CREATE PROCEDURE [dbo].[KEYHM_FetchTimeEntry]
      (@CaseCode          VARCHAR(20))
AS
/*******************************************************************************************************
* This procedure is used to get net Action Code based on the given Action ID.						   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_FetchTimeEntry]												   *
* Copied from			: [dbo].[ky_NETTLFetchTimeEntry3]											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
* 2019-04-24    Vinodhan K        TimeInHours Format modified to be dispalyed as '00:00' format        *
* 2020-05-04    Arun V            Have corrected the Writeoff MInutes calculation issue. KEYHM-574     *
* 2020-05-04    Arun V            Have corrected the Writeoff Value TimeInCharge value make it as ABS, *
*                                 In UI, negative value is handled and added minus in Front END        *
*                                 KEYHM-574                                                            *
*******************************************************************************************************/           
BEGIN
SET NOCOUNT ON
DECLARE @IsSAM4 bit
DECLARE @TimeEntryTotalCharge         DECIMAL(19, 2)
DECLARE @TimeEntryTotalTime           INT
DECLARE @TotalCharge                  Decimal(19, 2)
DECLARE @TotalTime                    INT
DECLARE @TimeBal                      INT
DECLARE @ChargeBal                    DECIMAL(19, 2)
DECLARE @ChargeableBal                DECIMAL(19, 2)
DECLARE @NonChargeableBal             DECIMAL(19, 2)
DECLARE @NonChargeableTimeBal         INT
DECLARE @ChargeableTimeBal            INT
DECLARE @NCOMMAND                     NVARCHAR(MAX)
DECLARE @TotalFeesIssued              DECIMAL(19, 2)

SET @IsSAM4 = [dbo].[ISSAM4]()
 
SELECT TIE.[RecordID]                                                   AS [RecordID],
       RTRIM(ISNULL(HAN.[CODE], ''))                                    AS [HandlerCode],
       RTRIM(ISNULL(HAN.[NAME], ''))                                    AS [FEEEARN],
       TIE.[DATE]                                                       AS [DATE],
       [dbo].[KEYHM_FN_RemoveSpuriousWhitespace](TIE.[COMMENT], 200)     AS [COMMENT],
       CASE TIE.[TimeOrCharge]
            WHEN 'T' THEN 'Time'
            WHEN 'B' THEN 'Bill'
            WHEN 'C' THEN 'Charge' END                                  AS [TIMEORCHARGE],
       TIE.[TIME]                                                       AS [TIME],
	   CASE
			WHEN ([TIME] = 0) THEN ('00:00')
			WHEN ([Time] > 0) THEN 
			CASE
				WHEN
					LEN([TIME] / 60) < 2
				THEN
					'0' +  CAST([TIME] / 60 AS VARCHAR)
				ELSE
					CAST([TIME] / 60 AS VARCHAR)
			END
			+ ':' 
			+  SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(NVARCHAR(10), CONVERT(NVARCHAR(5), [TIME] - (60 * ([TIME] / 60))))), 2, 2)
			WHEN ([TIME] < 0) THEN
			CASE
				WHEN
					LEN([TIME] / 60) < 2
				THEN
					'0' +  CAST(ABS([TIME]) / 60 AS VARCHAR)
				ELSE
					CAST(ABS([TIME]) / 60 AS VARCHAR)
			END
			+ ':' +  SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(NVARCHAR(10), CONVERT(NVARCHAR(5), -[TIME] - (60 * (-[TIME] / 60))))), 2, 2)
	   END AS [TimeInHours],
       CASE TIE.[Rec_Irr]
            WHEN 'C' THEN 'Chargeable'
            WHEN 'N' THEN 'Non-Chargeable'
            WHEN '' THEN 'Chargeable' END                               AS [REC_IRR],
       ISNULL(TIE.[CHARGE], 0.00)                                       AS [CHARGE],
       ISNULL(TIE.[BILLEDAMOUNT], 0.00)                                 AS [BILLEDAMOUNT],
       ISNULL(TIE.[INVOICENO], 0)                                       AS [INVOICENO],
       CASE WHEN TC.[DESC] IS NULL
                 THEN TIE.[TASK]
            WHEN TC.[DESC] IS NOT NULL
                 THEN TC.[DESC]
            ELSE '' END                                                 AS [TASK],
       CASE WHEN ISNULL(TIE.[WriteOffID], 0) = 0
                 THEN ''
            ELSE CONVERT(VARCHAR(MAX), ISNULL(TIE.[WriteOffID], 0)) END AS [WriteOffID],
       TIE.[WriteOffDT]                                                 AS [WriteOffDT],
       ISNULL(TIE.[Rate], 0)                                            AS [Rate],
       ISNULL(TIE.[IncludeInBill], 0)                                   AS [IncludeInBill],
       CASE WHEN TIE.[TIMEORCHARGE] = 'B' 
              OR TIE.[IncludeInBill] = 2
              OR TIE.[Rec_Irr] <> 'C'
                 THEN 0
            WHEN @IsSAM4 = 1 AND ISNULL(TIE.[INVOICENO], 0) <> 0
                 THEN 0
            WHEN @IsSAM4 <> 1
                 THEN ISNULL(TIE.[CHARGE], 0) - ISNULL(TIE.[BILLEDAMOUNT], 0)
            ELSE ISNULL(TIE.[CHARGE], 0) END                            AS [WIP],
			TIE.[Task]													AS [TaskCode]
  FROM [dbo].[TimeEntry] TIE
       LEFT OUTER JOIN [dbo].[Matters] MAT
                    ON MAT.[Code] = TIE.[Matter]
       LEFT OUTER JOIN [dbo].[TasksCodes] TC
                    ON TC.[CODE] = TIE.[Task]
       LEFT OUTER JOIN [dbo].[Handlers] HAN
                    ON HAN.[CODE] = TIE.[FeeEarn]
 WHERE TIE.[Matter] = @CaseCode

-- Please see also: KEYHM_FN_MatterClosable. If you change any of these calculations,
--                                          ensure the ones in there are changed as well.
--                  KAAS_MatterClosable.  If you change any of these calculations,
--                                          ensure the ones in there are changed as well.
--                  KAAS_CaseSummaryPageLoad. 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),
       @NonChargeableBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
										       AND ISNULL(TIE.[Task], '') <> 'WRI'
                                           THEN ISNULL(TIE.[Charge], 0)
                                           ELSE 0 END), 0),
       @ChargeableBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') <> 'N'
										 AND ISNULL(TIE.[Task], '') <> 'WRI'
                                        THEN ISNULL(TIE.[Charge], 0)
                                        ELSE 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),
       @NonChargeableTimeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
												              AND ISNULL(TIE.[Task], '') <> 'WRI'
                                               THEN ISNULL(TIE.[TIME], 0)
         ELSE 0 END), 0),
       @ChargeableTimeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
											                 OR ISNULL(TIE.[Task], '') = 'WRI'
                                            THEN 0
                                            ELSE ISNULL(TIE.[TIME], 0) END), 0),
       @TotalTime = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                      OR ISNULL(TIE.[Task], '') = 'WRI'
                                         THEN 0
                                    ELSE ISNULL(TIE.[Time], 0) END), 0)
  FROM
       [dbo].[TimeEntry] TIE
 WHERE
       TIE.[Matter] = @CaseCode
       AND ((TIE.[TimeOrCharge] = 'T')
       OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun

-- PLEASE NOTE THAT THIS MUST BE IDENTICAL TO RESULT SET 10 IN KAAS_CaseSummaryPageLoad. 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 @TotalFeesIssued = ISNULL(SUM((CASE WHEN HED.[INVCR] = ''I''
                             THEN TRN.[VALUE]
                        ELSE TRN.[VALUE] * - 1 END)), 0)
  FROM [dbo].[BatchH] HED
       INNER JOIN [dbo].[BatchDetails] TRN
               ON TRN.[BATCHNO] = HED.[BATCHNO]
 WHERE HED.[MATTER] = @CaseCode
   AND HED.[POSTED] = ''Y''
   AND TRN.[TYPE] = ''I''
   AND TRN.[OUTLAY] = ''F'''
      END
    ELSE
      BEGIN
        SET @NCOMMAND = N'
SELECT @TotalFeesIssued = 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] = @CaseCode

--values imported from Axxia
SELECT @TotalFeesIssued = @TotalFeesIssued + 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] = @CaseCode
   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'
      END

EXECUTE sp_executesql @NCOMMAND, N'@CaseCode VARCHAR(20), @TotalFeesIssued DECIMAL(19, 2) OUTPUT', @CaseCode = @CaseCode, @TotalFeesIssued = @TotalFeesIssued OUTPUT

/*WIP Calculations*/
SELECT 
		CASE
			WHEN
				LEN(@TimeBal / 60) < 2
			THEN
				'0' +  CAST(@TimeBal / 60 AS VARCHAR)
			ELSE
				CAST(@TimeBal / 60 AS VARCHAR)
		END AS [WIPHrs],
       SUBSTRING(CONVERT(VARCHAR(3), 100 + @TimeBal - (60 * (@TimeBal / 60))), 2, 2) AS [WIPMins],
       @ChargeBal AS [WIPAmt]

/*Total Record Calculations*/
SELECT 
       CASE
			WHEN
				LEN(@TimeEntryTotalTime / 60) < 2
			THEN
				'0' +  CAST(@TimeEntryTotalTime / 60 AS VARCHAR)
			ELSE
				CAST(@TimeEntryTotalTime / 60 AS VARCHAR)
	   END                                                                                                                                                     AS [TotalHours],
       SUBSTRING(CONVERT(VARCHAR(3), 100 + @TimeEntryTotalTime - (60 * (@TimeEntryTotalTime / 60))), 2, 2)                                                     AS [TotalMins],
       @TimeEntryTotalCharge                                                                                                                                   AS [TotalAmt],
       CASE
			WHEN
				LEN(@NonChargeableTimeBal / 60) < 2
			THEN
				'0' +  CAST(@NonChargeableTimeBal / 60 AS VARCHAR)
			ELSE
				CAST(@NonChargeableTimeBal / 60 AS VARCHAR)
	   END                                                                                                                                                     AS [RecNonChargeableHrs],
       SUBSTRING(CONVERT(VARCHAR(3), 100 + @NonChargeableTimeBal - (60 * (@NonChargeableTimeBal / 60))), 2, 2)                                                 AS [RecNonChargeableMins],
       @NonChargeableBal                                                                                                                                      AS [RecNonChargeableAmt],
	   CASE
			WHEN
				LEN(@ChargeableTimeBal / 60) < 2
			THEN
				'0' +  CAST(@ChargeableTimeBal / 60 AS VARCHAR)
			ELSE
				CAST(@ChargeableTimeBal / 60 AS VARCHAR)
	   END                                                                                                                                                     AS [RecChargeableHrs],
       SUBSTRING(CONVERT(VARCHAR(3), 100 + @ChargeableTimeBal - (60 * (@ChargeableTimeBal / 60))), 2, 2)                                                       AS [RecChargeableMins],
       @ChargeableBal                                                                                                                                          AS [RecChargeableAmt],
       CASE
			WHEN
				LEN((@ChargeableTimeBal + @NonChargeableTimeBal) / 60) < 2
			THEN
				'0' +  CAST((@ChargeableTimeBal + @NonChargeableTimeBal) / 60 AS VARCHAR)
			ELSE
				CAST((@ChargeableTimeBal + @NonChargeableTimeBal) / 60 AS VARCHAR)
	   END                                                                                                                                                     AS [RecTotalHrs],
       SUBSTRING(CONVERT(VARCHAR(3), 100 + (@ChargeableTimeBal + @NonChargeableTimeBal) - (60 * ((@ChargeableTimeBal + @NonChargeableTimeBal) / 60))), 2, 2)   AS [RecTotalMins],
       @ChargeableBal + @NonChargeableBal                                                                                                                      AS [RecTotalAmt],
       @TotalFeesIssued                                                                                                                                        AS [TotalBilled],
	   @TotalFeesIssued - (@ChargeableBal + @NonChargeableBal)                                                                                                 AS [ProfitLoss] -- Current Profit/Loss = TotalBilled - RecTotalAmt;

/*Write Off Calculations*/
SELECT
       CASE
		WHEN TIES.[WriteOffTime] > 0
		THEN '-'
		ELSE ''
	   END
	   +
	   CASE
			WHEN
				LEN(TIES.[WriteOffTime] / 60) < 2
			THEN
				'0' +  CAST(TIES.[WriteOffTime] / 60 AS VARCHAR)
			ELSE
				CAST(TIES.[WriteOffTime] / 60 AS VARCHAR)
	   END                                                                      AS [WOHrs],
	   CONVERT(VARCHAR(5), (TIES.[WriteOffTime] % 60)*-1)   AS [WOMins],
       ---TIES.[WriteOffTime] / 60 AS [WOHrs],
       ---TIES.[WriteOffTime] % 60 AS [WOMins],
       TIES.[WriteOffValue]                                                     As [WOAmt]
  FROM (SELECT ISNULL(SUM(CONVERT(DECIMAL(18, 2), ISNULL(TIE.[Charge], 0))), 0) AS [WriteOffValue],
               ISNULL(SUM(ISNULL(TIE.[Time], 0)), 0) AS [WriteOffTime]
          FROM [dbo].[matters] MAT
                 INNER JOIN [dbo].[TimeEntry] TIE
                         ON TIE.[MATTER] = MAT.[Code]
          WHERE TIE.[MATTER] = @CaseCode
             AND ((TIE.[TimeOrCharge] = 'T')
             OR (TIE.[TimeOrCharge] = 'C'))
             AND TIE.[Task] = 'WRI') TIES

/*Total Billed Amount Calculations */ ------ Commented out as reversed KEYD-3657
--IF @IsSAM4 = 0
--  SELECT ISNULL(SUM(ISNULL([TIE].[BilledAmount], 0)), 0) AS [TotalBill]
--    FROM [dbo].[TimeEntry] [TIE]
--   WHERE [TIE].[Matter] = @CaseCode
--ELSE
--  SELECT @TotalFeesIssued AS [TotalBill]
--    FROM [dbo].[TimeEntry] [TIE]
--   WHERE [TIE].[Matter] = @CaseCode

DECLARE @DraftBillValue DECIMAL(18, 2)    
          
SET @IsSAM4 = [dbo].[ISSAM4]()          
          
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] = @CaseCode          
     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] = @CaseCode          
     AND HED.[BillStatus] <> ''Approved''          
     AND ISNULL(HED.[ProForma], '''') = ''Y'''          
  END          
EXECUTE sp_executesql @NCOMMAND, N'@CaseCode VARCHAR(20),@DraftBillValue DECIMAL(18, 2) OUTPUT', @CaseCode = @CaseCode, @DraftBillValue=@DraftBillValue OUTPUT          
          
DECLARE @Section68    VARCHAR(10)          
DECLARE @IsApproved   VARCHAR(10)          
DECLARE @CSTimeBal      INT          
DECLARE @CSChargeBal    DECIMAL(19, 2)          
DECLARE @CSTotalCharge  Decimal(19, 2)          
DECLARE @CSTotalTime    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]  = @CaseCode          
          
DECLARE @LDIADATE DATETIME          
DECLARE @LDIAACTIONTYPE VARCHAR(1)          
DECLARE @LDIATEXT1 VARCHAR(MAX)          
DECLARE @LDIAFNCODE VARCHAR(10)      
DECLARE @LDIAFNNAME VARCHAR(50)      
          
  SELECT TOP 1          
         @LDIADATE = LDIA.[DATE],          
         @LDIAACTIONTYPE = LDIA.[ACTIONTYPE],          
         @LDIATEXT1 = LDIA.[TEXT1],          
         @LDIAFNCODE = LDIA.[FNCODE],      
   @LDIAFNNAME = [FEC].[Name]       
    FROM [dbo].[diary] LDIA      
 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]      
 ON LDIA.FNCODE = [FEC].[CODE]           
   WHERE LDIA.[CASECODE] = @CaseCode          
ORDER BY LDIA.[DATE] DESC          
          
DECLARE @MDIADATE DATETIME          
DECLARE @MDIAACTIONTYPE VARCHAR(1)          
DECLARE @MDIATEXT1 VARCHAR(MAX)          
DECLARE @MDIAFNCODE VARCHAR(10)      
DECLARE @MDIAFNNAME VARCHAR(50)          
          
  SELECT TOP 1          
         @MDIADATE= MDIA.[DATE],          
         @MDIAACTIONTYPE = MDIA.[ACTIONTYPE],          
         @MDIATEXT1 = MDIA.[TEXT1],          
         @MDIAFNCODE = MDIA.[FNCODE],      
   @MDIAFNNAME = [FEC].[Name]      
    FROM [dbo].[diary] MDIA      
 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]      
 ON MDIA.FNCODE = [FEC].[CODE]      
   WHERE MDIA.[CASECODE] = @CaseCode          
     AND MDIA.[HIGHLIGHTED] = 'Y'          
ORDER BY MDIA.[DATE] DESC          
          
DECLARE @NDIADATE DATETIME          
DECLARE @NDIAACTIONTYPE VARCHAR(1)          
DECLARE @NDIATEXT1 VARCHAR(MAX)          
DECLARE @NDIAFNCODE VARCHAR(10)      
DECLARE @NDIAFNNAME VARCHAR(50)      
          
  SELECT TOP 1          
         @NDIADATE = NDIA.[DATE],          
         @NDIAACTIONTYPE = NDIA.[ACTIONTYPE],          
         @NDIATEXT1 = NDIA.[TEXT1],          
         @NDIAFNCODE = NDIA.[FNCODE],      
   @NDIAFNNAME = [FEC].[Name]       
    FROM dbo.[diary] NDIA          
    INNER JOIN [dbo].[FeeEarnerCodes] [FEC]      
 ON NDIA.FNCODE = [FEC].[CODE]      
 WHERE NDIA.[CASECODE] = @CaseCode      
     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] = @CaseCode          
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] = @CaseCode'          
  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] = @CaseCode          
           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'@CaseCode VARCHAR(20), @TIEDATE DATETIME OUTPUT', @CaseCode = @CaseCode, @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 @LastTimeEntryFEName    VARCHAR(50)      
DECLARE @CSTimeEntryTotalCharge         DECIMAL(19, 2)          
DECLARE @CSTimeEntryTotalTime           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],      
   @LastTimeEntryFEName  = [FEC].[Name]        
    FROM [dbo].[TimeEntry] TIE      
 INNER JOIN [dbo].[FeeEarnerCodes] [FEC]      
     ON [TIE].[FeeEarn] = [FEC].[CODE]      
   WHERE TIE.[Matter] = @CaseCode          
     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: KAAS_FN_MatterClosable. If you change any of these calculations,          
--                                          ensure the ones in there are changed as well.          
--                  KAAS_MatterClosable.  If you change any of these calculations,          
--                                          ensure the ones in there are changed as well.          
          
SELECT @CSTimeEntryTotalCharge = ISNULL(SUM(ISNULL(TIE.[Charge], 0)), 0),          
       @CSTimeEntryTotalTime = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0),          
       @CSTotalCharge = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'          
                                      THEN 0          
                                 ELSE ISNULL(TIE.[Charge], 0) END), 0),          
       @CSChargeBal = 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),          
       @CSTimeBal = 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),          
       @CSTotalTime = 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] = @CaseCode          
   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: KAAS_FN_MatterClosable. 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] = @CaseCode          
   AND TRN.[Posted] = ''Y''          
   AND TRN.[RecType] <> ''V''          
   AND TRN.[CorrectionInd] = ''L'''          
EXECUTE sp_executesql @NCOMMAND,          
                      N'@CaseCode 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',          
                      @CaseCode      = @CaseCode,          
                      @DebtBal       = @DebtBal OUTPUT,          
					  @DebtBalDate   = @DebtBalDate OUTPUT,          
                      @OutlayBal     = @OutlayBal OUTPUT,          
                      @OutlayBalDate = @OutlayBalDate OUTPUT,          
                      @ClientCurrent = @ClientCurrent OUTPUT,          
                      @ClientDeposit = @ClientDeposit OUTPUT          
  END    
    
--Result Set 1          
--WIP          
  SELECT TIES.[FeeEarn]                                                                          AS [FeeEarn],          
         TIES.[NAME]                                                                             AS [Name],          
         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 [FETotalHours],          
         TIES.[Charge]                                                                           AS [FECharge],          
         TIES.[ChargeBal]                                                                        AS [FEChargeBal],          
         CASE
			WHEN
				LEN(TIES.[WIPTOTALTIME] / 60) < 2
			THEN
				'0' +  CAST(TIES.[WIPTOTALTIME] / 60 AS VARCHAR)
			ELSE
				CAST(TIES.[WIPTOTALTIME] / 60 AS VARCHAR)
	     END
         + ':'          
         + SUBSTRING(CONVERT(VARCHAR(3), 100 + (TIES.[WIPTOTALTIME] % 60)), 2, 2)                AS [FEWIPHours]          
    FROM (  SELECT TIE.[FeeEarn]                                                                 AS [FeeEarn],          
                   HAN.[NAME]																	 AS [NAME],          
                   ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)                                         AS [TOTALTIME],          
                   SUM(CONVERT(DECIMAL(18, 2),          
                               ISNULL(TIE.[Charge],          
                                      0)))                                                       AS [Charge],          
                   SUM(CONVERT(DECIMAL(18, 2),          
                               CASE WHEN @IsSAM4 = 1          
                                     AND TIE.[InvoiceNo] <> 0          
                                         THEN 0          
                                    WHEN @IsSAM4 = 0          
                                         THEN   ISNULL(TIE.[Charge],          
                                                       0)          
                                              - ISNULL(TIE.[BilledAmount],          
                                                       0)          
                                    ELSE ISNULL(TIE.[Charge],          
                                                0) END))                                          AS [ChargeBal],          
                   CONVERT(INT,          
                           FLOOR(CONVERT(DECIMAL(18, 2), ISNULL(SUM(CASE WHEN @IsSAM4 = 1          
                                                                          AND [TIE].[InvoiceNo] <> 0          
                                                                              THEN 0          
                                                                         WHEN [TIE].[Charge] - [TIE].[BilledAmount] = 0          
																			  THEN 0          
                                                                         ELSE TIE.[TIME]
																	 END)          
                                                                , 0))          
                                 *          
                                 CASE WHEN SUM(CONVERT(DECIMAL(18, 2),          
                                                       CASE WHEN @IsSAM4 = 1          
                                                             AND [TIE].[InvoiceNo] <> 0          
                                                                 THEN 0          
                                                            WHEN [TIE].[Charge] - [TIE].[BilledAmount] = 0          
                                                                 THEN 0          
                                      ELSE TIE.[Charge] END)) = 0          
                                           THEN 0          
                                      ELSE SUM(CONVERT(DECIMAL(18, 2),          
                                                       CASE WHEN @IsSAM4 = 1          
                                                             AND TIE.[InvoiceNo] <> 0          
                                                                 THEN 0          
                                                            WHEN @IsSAM4 = 0          
                                                                 THEN   ISNULL(TIE.[Charge],          
                                                                               0)          
                                                                      - ISNULL(TIE.[BilledAmount],          
                                                                               0)          
                                                            ELSE ISNULL(TIE.[Charge],          
                                                                        0) 
														END))          
                                           /          
			 SUM(CONVERT(DECIMAL(18, 2),    
                                                       CASE WHEN @IsSAM4 = 1          
                                                             AND [TIE].[InvoiceNo] <> 0          
                                                                 THEN 0          
                                                            WHEN [TIE].[Charge] - [TIE].[BilledAmount] = 0          
																 THEN 0          
                                                            ELSE TIE.[Charge] 
														END)) 
								END))           AS [WIPTOTALTIME]          
              FROM [dbo].[matters] MAT          
                   INNER JOIN [dbo].[TimeEntry] TIE          
                           ON TIE.[MATTER] = MAT.[Code]          
                   INNER JOIN [dbo].[Handlers] HAN          
                           ON HAN.[CODE] = TIE.[FeeEarn]          
             WHERE TIE.[MATTER] = @CaseCode          
               AND TIE.[DATE] < GETDATE()          
               AND ((TIE.[TimeOrCharge] = 'T')          
                OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun          
               AND TIE.[REC_IRR] <> 'N'          
          GROUP BY TIE.[FEEEARN],          
                   HAN.[NAME]) TIES          
ORDER BY TIES.[ChargeBal] DESC,          
         TIES.[TOTALTIME] DESC          
    
--Result Set 4          
--Activity to Date          
  SELECT TIES.[Activity],          
            CASE WHEN TIES.[TOTALTIME] < 0          
                      THEN '-'          
                 ELSE '' END          
         +
		 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 + (ABS(TIES.[TOTALTIME]) % 60)), 2, 2)              AS [ActivityToDateTime],          
         TIES.[Value]                                                                            AS [ActivityToDateValue]          
    FROM (  SELECT TIE.[TASK]                                                    AS [Task],          
                   CASE WHEN TSC.[DESC] IS NULL          
                             THEN 'Task Code: ' + ISNULL(TIE.[TASK], '')          
                        ELSE RTRIM(ISNULL(TSC.[DESC],'')) END                    AS [Activity],          
                   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          
                   LEFT OUTER JOIN [dbo].[TasksCodes] TSC          
                            ON TSC.[CODE] = TIE.[Task]          
							ON TIE.[MATTER] = MAT.[Code]          
             WHERE TIE.[MATTER] = @CaseCode          
               AND TIE.[DATE] < GETDATE()          
               AND ((TIE.[TimeOrCharge] = 'T')          
				OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun          
               AND TIE.[REC_IRR] <> 'N'          
               AND TIE.[Task] <> 'WRI'          
          GROUP BY TIE.[TASK],          
                   CASE WHEN TSC.[DESC] IS NULL          
                             THEN 'Task Code: ' + ISNULL(TIE.[TASK], '')          
                        ELSE RTRIM(ISNULL(TSC.[DESC],'')) END) TIES          
ORDER BY TIES.[Value] DESC,          
         TIES.[TOTALTIME] DESC     
    
--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] = @CaseCode          
             AND (   (TIE.[TimeOrCharge] = 'T')          
              OR (TIE.[TimeOrCharge] = 'C'))          
             AND TIE.[TASK] <> 'WRI') TIES    
    
--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],          
       @CSTimeBal																	  AS [TimeBal],          
         CASE
			WHEN
				LEN(@CSTimeBal / 60) < 2
			THEN
				'0' +  CAST(@CSTimeBal / 60 AS VARCHAR)
			ELSE
				CAST(@CSTimeBal / 60 AS VARCHAR)
	     END
       + ':'          
       + SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(INT, @CSTimeBal) % 60), 2, 2)    AS [TimeBalHours],          
       @CSChargeBal                                                                   AS [ChargeBal],          
         CASE
			WHEN
				LEN(@CSTotalTime / 60) < 2
			THEN
				'0' +  CAST(@CSTotalTime / 60 AS VARCHAR)
			ELSE
				CAST(@CSTotalTime / 60 AS VARCHAR)
	     END
       + ':'          
       + SUBSTRING(CONVERT(VARCHAR(3), 100 + CONVERT(INT, @CSTotalTime) % 60), 2, 2)  AS [TotalHours],          
       @CSTotalCharge                                                                 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],      
	   RTRIM(ISNULL(@LDIAFNNAME, ''))												  AS [LastActionFEName],          
       @MDIADATE                                                                      AS [LastMilestoneDate],          
       RTRIM(ISNULL(@MDIAActionType, ''))                                             AS [LastMilestoneType],          
       RTRIM(ISNULL(@MDIATEXT1, ''))                                                  AS [LastMilestoneText],          
       RTRIM(ISNULL(@MDIAFNCODE, ''))                                                 AS [LastMilestoneFE],          
       RTRIM(ISNULL(@MDIAFNNAME, ''))												  AS [LastMilestoneFEName],      
       @NDIADATE																	  AS [NextActionDate],          
       RTRIM(ISNULL(@NDIAActionType, ''))                                             AS [NextActionType],          
       RTRIM(ISNULL(@NDIATEXT1, ''))                                                  AS [NextActionText],          
       RTRIM(ISNULL(@NDIAFNCODE, ''))                                                 AS [NextActionFE],      
       RTRIM(ISNULL(@NDIAFNNAME, ''))                                                 AS [NextActionFEName],         
       @LastTimeEntryDate                                                             AS [LastTimeEntryDate],          
       @LastTimeEntryTime                                                             AS [LastTimeEntryTime],          
       @LastTimeEntryRate                                                             AS [LastTimeEntryRate],          
       @LastTimeEntryCharge                                                           AS [LastTimeEntryCharge],          
       @LastTimeEntryTask															  AS [LastTimeEntrytask],          
       @LastTimeEntryComment                                                          AS [LastTimeEntryComment],          
       @LastTimeEntryFE                                                               AS [LastTimeEntryFE],      
       @LastTimeEntryFEName                                                           AS [LastTimeEntryFEName],      
       @CSTimeEntryTotalCharge                                                        AS [TimeEntryTotalCharge],          
       @CSTimeEntryTotalTime                                                          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] = @CaseCode

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

GO

CREATE PROCEDURE [dbo].[KEYHM_FlagGetDetails]
(
	@CalledFrom INT=0
)  
AS    

/*******************************************************************************************************
* This Procedure is used to Action Flag Details                                                        *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_FlagGetDetails]				  								   *
* Copied from			: [dbo].[Ky_NETFlagGetDetails]												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-22    Vinodhan K        Created                                                              *
 *******************************************************************************************************/

BEGIN    
	SET NOCOUNT ON   
	IF (@CalledFrom =1)
		SELECT [ActionFlagID],
			   RTRIM(ISNULL([Description],'')) as [Description],
			   [IsActive]   
		  FROM [dbo].[ActionFlag]     
	  ORDER BY [ActionFlagID]    
	ELSE
		SELECT [ActionFlagID],
			   RTRIM(ISNULL([Description],'')) as [Description]    
		  FROM [dbo].[ActionFlag]     
		 WHERE [IsActive] = 1
	  ORDER BY [ActionFlagID]    
	SET NOCOUNT OFF    
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FNConvertDateToUTC'
      AND SO.[type] = 'FN')
  BEGIN
    DROP FUNCTION [dbo].[KEYHM_FNConvertDateToUTC]
  END
GO

DECLARE @Compatible BIT

SET @Compatible = CASE WHEN ServerProperty('EngineEdition') = 5
                            THEN 1
                       WHEN @@VERSION LIKE '%SQL Server 2008%'
                            THEN 0
                       WHEN @@VERSION LIKE '%SQL Server 2012%'
                            THEN 0
                       WHEN @@VERSION LIKE '%SQL Server 2014%'
                            THEN 0
                       ELSE 1 END

IF @Compatible = 1
  BEGIN
    EXEC ('CREATE FUNCTION 
	[dbo].[KEYHM_FNConvertDateToUTC]
	( 
		@Date		DATETIME,
		@Handler	NVARCHAR(10)
	)
RETURNS DATETIME
AS
/*******************************************************************************************************
* This function is used to convert local time to UTC				                                   *
*                                                                                                      *
* Function	: KEYHM_FNGetDateForTimeZone																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-10-29	Arun V		Created				                                                   *
*******************************************************************************************************/ 
BEGIN
	RETURN
	(
			SELECT  @Date AT TIME ZONE dbo.KEYHM_FNGetHandlerTimeZone(@Handler) AT TIME ZONE ''UTC''			
	)
End')
  END
ELSE
  BEGIN
    EXEC ('CREATE FUNCTION [dbo].[KEYHM_FNConvertDateToUTC]
( 
	@Date		DATETIME,
	@Handler	NVARCHAR(10)
)
RETURNS DATETIME
AS
/*******************************************************************************************************
* This function is used to convert local time to UTC	                            				   *
*                                                                                                      *
* Function	: KEYHM_FNConvertDateToUTC																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-10-29	Arun V		Created					                                                   *
*******************************************************************************************************/ 
BEGIN
	RETURN
	(
			SELECT @Date
	)
End')
  END

GO


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

DECLARE @Compatible BIT

SET @Compatible = CASE WHEN ServerProperty('EngineEdition') = 5
                            THEN 1
                       WHEN @@VERSION LIKE '%SQL Server 2008%'
                            THEN 0
                       WHEN @@VERSION LIKE '%SQL Server 2012%'
                            THEN 0
                       WHEN @@VERSION LIKE '%SQL Server 2014%'
                            THEN 0
                       ELSE 1 END

IF @Compatible = 1
  BEGIN
    EXEC ('CREATE FUNCTION 
	[dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]
	( 
		@Date		DATETIME,
		@Handler	NVARCHAR(10)
	)
RETURNS DATETIME
AS
/*******************************************************************************************************
* This function is used to convert local time to specified zone time. default is GMT				   *
*                                                                                                      *
* Function	: KEYHM_FNGetDateForTimeZone																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-07-03	Rajesh P		Created				                                                   *
*******************************************************************************************************/ 
BEGIN
	RETURN
	(
			SELECT CONVERT(DATETIME,CONVERT(DATETIMEOFFSET, @Date) AT TIME ZONE (SELECT dbo.KEYHM_FNGetHandlerTimeZone(@Handler)))
	)
End')
  END
ELSE
  BEGIN
    EXEC ('CREATE FUNCTION [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]
( 
	@Date		DATETIME,
	@Handler	NVARCHAR(10)
)
RETURNS DATETIME
AS
/*******************************************************************************************************
* This function is used to convert local time to specified zone time. default is GMT				   *
*                                                                                                      *
* Function	: KEYHM_FNGetDateForTimeZone																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-07-03	Rajesh P		Created				                                                   *
*******************************************************************************************************/ 
BEGIN
	RETURN
	(
			SELECT @Date
	)
End')
  END

GO


IF OBJECT_ID('KEYHM_FNGetHandlerTimeZone',N'FN') IS NOT NULL
	DROP FUNCTION KEYHM_FNGetHandlerTimeZone
GO
CREATE FUNCTION [dbo].[KEYHM_FNGetHandlerTimeZone](
	@Handler VARCHAR(10)
)
RETURNS NVARCHAR(50)
AS
/*******************************************************************************************************
* This function is used to get the handler time zone, for now its default to GMT standard Time		   *
*                                                                                                      *
* Function	: KEYHM_FNGetDateForTimeZone																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-07-03	Rajesh P		Created				                                                   *
* 2019-09-24	Arun V			Handler Code added to get used based time zone, default to GMT         *
*******************************************************************************************************/ 
BEGIN
	DECLARE @HandlerTimeZone NVARCHAR(50)
	
	SELECT 
		@HandlerTimeZone = [Value] 
	FROM 
		UserSettings 
	WHERE 
		[Handler] = @Handler AND 
		[Key] = 'TimeZone'
	
	SELECT 
		@HandlerTimeZone = ISNULL(@HandlerTimeZone, 'GMT Standard Time')

	RETURN @HandlerTimeZone
End
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FN_ConvertClarionTimeToHHMM'
      AND SO.[type] = 'FN')
  BEGIN
    DROP FUNCTION [dbo].[KEYHM_FN_ConvertClarionTimeToHHMM]
  END
GO

create function
       [dbo].[KEYHM_FN_ConvertClarionTimeToHHMM]
      (@ClarionTime INT)
returns VARCHAR(5)
AS
/**************************************************************************************
 *
 * converts an integer value between 1 and 8640000, representing a Clarion Time Value
 * in 1/100 of a Second since Midnight to a Time representation in HH:MM format
 *
 * Stored Procedure name : KEYHM_FN_ConvertClarionTimeToHHMM
 * Copied From           : ky_NETFNConvertClarionTimeToHHMM
 *
 * This function prevents Cardinality Estimate Warnings when used in SELECT statements
 *
 **************************************************************************************/
BEGIN

DECLARE @HHMM   VARCHAR(5)
DECLARE @HOUR   INT
DECLARE @MINUTE INT

IF @ClarionTime IS NULL
  BEGIN
    SET @HHMM = ''
  END
ELSE IF @ClarionTime < 1
  BEGIN
    SET @HHMM = ''
  END
ELSE IF @ClarionTime > 8640000
  BEGIN
    SET @HHMM = ''
  END
ELSE
  BEGIN
    SET @ClarionTime = @ClarionTime - 1

    SET @HOUR = FLOOR(@ClarionTime / 360000)

    SET @ClarionTime = @ClarionTime - (@HOUR * 360000)

    SET @MINUTE = FLOOR(@ClarionTime / 6000)

    SET @HHMM = SUBSTRING(CONVERT(VARCHAR(3), 100 + @HOUR), 2, 2) + ':' + SUBSTRING(CONVERT(VARCHAR(3), 100 + @MINUTE), 2, 2)
  END

RETURN @HHMM

END

GO
IF EXISTS
  (SELECT *
     FROM SYS.[objects] SO
    WHERE SO.[name] = 'KEYHM_FN_DateDiffVerbose'
      AND SO.[type] = 'FN')
BEGIN
  DROP FUNCTION [dbo].[KEYHM_FN_DateDiffVerbose]
END
GO

CREATE FUNCTION
       [dbo].[KEYHM_FN_DateDiffVerbose]
      (@FromDate      DATETIME,
       @ToDate        DATETIME)
RETURNS VARCHAR(200)
AS
/*******************************************************************************************************
* Fetch Attachment list by diary number												                   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_DateDiffVerbose]			                                   *
* Copied from			: [dbo].[ky_NETFNDateDiffVerbose]				                               *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-16	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

BEGIN
  DECLARE @OUTPUT VARCHAR(200)

  IF @FromDate IS NULL
    BEGIN
      RETURN ''
    END

  IF @ToDate IS NULL
    BEGIN
      RETURN ''
    END

  IF (@FromDate >= @ToDate)
    BEGIN
      RETURN ''
    END

  DECLARE @Work DATETIME
  DECLARE @YEARS INT

  SET @YEARS = DATEDIFF(YEAR, @FromDate, @ToDate)

  SET @Work = DATEADD(YEAR, @YEARS, @FromDate)

  IF (@Work > @ToDate)
    BEGIN
      SET @YEARS = @YEARS - 1
    END

  SET @OUTPUT = ''

  IF @YEARS = 1
    BEGIN
      IF @OUTPUT <> ''
        BEGIN
          SET @OUTPUT = @OUTPUT + ', '
        END
      
      SET @OUTPUT = @OUTPUT + '1 Year'
    END

  IF @YEARS > 1
    BEGIN
      IF @OUTPUT <> ''
        BEGIN
          SET @OUTPUT = @OUTPUT + ', '
        END
      
      SET @OUTPUT = @OUTPUT + CONVERT(VARCHAR(10), @YEARS) + ' Years'
    END

  SET @FromDate = DATEADD(YEAR, @YEARS, @FromDate)

  DECLARE @MONTHS INT

  SET @MONTHS = DATEDIFF(MONTH, @FromDate, @ToDate)

  SET @Work = DATEADD(MONTH, @MONTHS, @FromDate)

  IF (@Work > @ToDate)
    BEGIN
      SET @MONTHS = @MONTHS - 1
    END

  IF @MONTHS = 1
    BEGIN
      IF @OUTPUT <> ''
        BEGIN
          SET @OUTPUT = @OUTPUT + ', '
        END
      
      SET @OUTPUT = @OUTPUT + '1 Month'
    END

  IF @MONTHS > 1
    BEGIN
      IF @OUTPUT <> ''
        BEGIN
          SET @OUTPUT = @OUTPUT + ', '
        END
      
      SET @OUTPUT = @OUTPUT + CONVERT(VARCHAR(10), @MONTHS) + ' Months'
    END

  SET @FromDate = DATEADD(MONTH, @MONTHS, @FromDate)

  DECLARE @DAYS INT

  SET @DAYS = DATEDIFF(DAY, @FromDate, @ToDate)

  IF @DAYS = 1
    BEGIN
      IF @OUTPUT <> ''
        BEGIN
          SET @OUTPUT = @OUTPUT + ' and '
        END
      
      SET @OUTPUT = @OUTPUT + '1 Day'
    END

  IF @DAYS > 1
    BEGIN
      IF @OUTPUT <> ''
        BEGIN
          SET @OUTPUT = @OUTPUT + ' and '
        END
      
      SET @OUTPUT = @OUTPUT + CONVERT(VARCHAR(10), @DAYS) + ' Days'
    END

  RETURN @OUTPUT

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

CREATE FUNCTION
       [dbo].[KEYHM_FN_GetDefaultRate]
      (@MATTER  VARCHAR(20),
       @FEEEARN VARCHAR(10),
       @NCCCODE VARCHAR(10),
       @TASK    VARCHAR(6))
RETURNS DECIMAL(18, 2)
AS
/*******************************************************************************************************
* Calculates the default Rate for a FeeEarner/Matter												   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_GetDefaultRate]											   *
* Copied from			: [dbo].[ky_NETFNGetDefaultRate]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-24	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
  DECLARE @CLIENT VARCHAR(10)
  DECLARE @MatterChargeLevel INT

  DECLARE @MCRRATE DECIMAL(18, 2)
  DECLARE @MCRRATE2 DECIMAL(18, 2)
  DECLARE @CCRRATE DECIMAL(18, 2)
  DECLARE @CCRRATE2 DECIMAL(18, 2)
  DECLARE @HDLRATE DECIMAL(10, 2)
  DECLARE @TASKCODE VARCHAR(10)
  DECLARE @CHARGEFACTOR DECIMAL(4, 2)
  DECLARE @ACTUALRATE DECIMAL(18, 2)

  SELECT @CLIENT = RTRIM(ISNULL(MAT.[ClientCode], '')),
         @MatterChargeLevel = ISNULL(MAT.[ChargeLevel], 3),
         @TASKCODE = CASE RTrim(IsNull(@MATTER, ''))
                          WHEN '' THEN RTRIM(ISNULL(@NCCCODE, ''))
                          ELSE RTRIM(ISNULL(@TASK, '')) END
    FROM [dbo].[matters] MAT
   WHERE MAT.[Code] = @MATTER

  SELECT @MCRRATE = MCOR.[Rate]
    FROM [dbo].[MatterChargeOutRates] MCOR
   WHERE MCOR.[FeCode] = @FEEEARN
     AND MCOR.[MatterCode] = @MATTER

  SELECT @MCRRATE2 = MCORG.[Rate]
    FROM [dbo].[Handlers] HANG
         INNER JOIN [dbo].[MatterChargeOutRates] MCORG
                 ON MCORG.[FeCode] = HANG.[ChargeGroup]
                AND MCORG.[MatterCode] = @MATTER
   WHERE HANG.[CODE] = @FEEEARN

  SET @MCRRATE2 = ISNULL(@MCRRATE2, 0)
  SET @MCRRATE = ISNULL(@MCRRATE, @MCRRATE2)

  SELECT @CCRRATE = CCOR.[Rate]
    FROM [dbo].[ClientChargeOutRates] CCOR
   WHERE CCOR.[FeCode] = @FEEEARN
     AND CCOR.[ClientCode] = @CLIENT

  SELECT @CCRRATE2 = CCORG.[Rate]
    FROM [dbo].[Handlers] HANG2
         INNER JOIN [dbo].[ClientChargeOutRates] CCORG
                 ON CCORG.[FeCode] = HANG2.[ChargeGroup]
                AND CCORG.[ClientCode] = @CLIENT
   WHERE HANG2.[CODE] = @FEEEARN

  SET @CCRRATE2 = ISNULL(@CCRRATE2, 0)
  SET @CCRRATE = ISNULL(@CCRRATE, @CCRRATE2)

  SELECT @HDLRATE = CASE IsNull(@MatterChargeLevel, 3)
                         WHEN 1 THEN IsNull(HDL.[RATE1], 0)
                         WHEN 2 THEN IsNull(HDL.[RATE2], 0)
                         WHEN 3 THEN IsNull(HDL.[RATE3], 0)
                         WHEN 4 THEN IsNull(HDL.[RATE4], 0)
                         WHEN 5 THEN IsNull(HDL.[RATE5], 0)
                         ELSE IsNull(HDL.[RATE], 0) END
    FROM [dbo].[Handlers] HDL
   WHERE HDL.[CODE] = @FEEEARN

  SET @HDLRATE = ISNULL(@HDLRATE, 0)

  SELECT @CHARGEFACTOR = CASE IsNull(TAC.[ChargeLevel], 'C')
                              WHEN 'A' THEN 0.33
                              WHEN 'B' THEN 0.67
                              WHEN 'C' THEN 1.00
                              WHEN 'D' THEN 1.33
                              WHEN 'E' THEN 1.67
                              ELSE 1.00 END
    FROM [dbo].[TasksCodes] TAC
   WHERE TAC.[CODE] = @TASKCODE

  SET @CHARGEFACTOR = ISNULL(@CHARGEFACTOR, 1)

  SELECT @ACTUALRATE = Case When IsNull(MAT.[ChargeOutRateInd], 'N') = 'Y'
                                 THEN @MCRRATE
                            When IsNull(CON.[ChargeOutRateInd], 'N') = 'Y'
                                 THEN @CCRRATE
                            ELSE @CHARGEFACTOR * @HDLRATE END
    FROM [dbo].[matters] MAT
         INNER JOIN [dbo].[contacts] CON
                 ON CON.[Code] = MAT.[ClientCode]
   WHERE MAT.[code] = @MATTER

  SET @ACTUALRATE = ISNULL(@ACTUALRATE, @CHARGEFACTOR * @HDLRATE)

  RETURN @ACTUALRATE
END
GO
IF OBJECT_ID(N'KEYHM_FN_GetDocFolders',N'TF')IS NOT NULL
	DROP FUNCTION KEYHM_FN_GetDocFolders
GO
CREATE FUNCTION [dbo].[KEYHM_FN_GetDocFolders]
       (@MatterCode    VARCHAR(20),
	    @parentid         INT,
        @fulltree         BIT,
        @includeparent    BIT)
 RETURNS
		@DocFolders TABLE
       ([seq]                 INT              IDENTITY (1, 1)       NOT NULL PRIMARY KEY,
        [id]                  INT                                    NOT NULL,
        [parent]              INT                                    NOT NULL,
        [foldername]          VARCHAR(500)                           NOT NULL,
        [foldericon]          INT                                    NOT NULL,
		[folderimage]		  VARBINARY(MAX),
        [foldershared]        BIT                                    NOT NULL,
        [folderisours]        BIT                                    NOT NULL,
        [documentcount]       INT                                    NOT NULL)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * Stored Procedure Name: [dbo].[KEYHM_FN_GetDocFolders]                                                      *
 * Copied from   : [dbo].[ky_NETTFGetDocFolders4]                                                            *
 *                                                                                                           *
 *                                                                                                           *
 * Retrieve a document folder tree                                                                           *
 * @parentid       - the ID of the root folder                                                               *
 * @fulltree       - get the complete tree for @parentid                                                     *
 *                   0 - get only the first level child nodes                                                *
 *                   1 - get all child nodes                                                                 *
 * @includeparent  - include the parent node itself                                                          *
 *                   0 - the top level returned are the child nodes                                          *
 *                   1 - the top level returned is the parent node                                           *
 *                                                                                                           *
 * Modification History:                                                                                     *
 * 2018-12-06    Arun.V        Created to return file count                                                  *
 * 2019-04-26    Vinodhan.K    Added folderimage field                                                       *
 * 2019-08-16    Arun V        Changed [docfoldercount] to update the files count,                           *
 *************************************************************************************************************/
BEGIN
Declare @DocFoldersX  Table
         ([seq]                 INT            IDENTITY (0, 1)         NOT NULL PRIMARY KEY,
          [id]                  INT                                    NOT NULL,
          [parent]              INT                                    NOT NULL,
          [foldername]          VARCHAR(500)                           NOT NULL,
          [foldericon]          INT                                    NOT NULL,
		  [folderimage]		  VARBINARY(MAX),    
          [foldershared]        BIT                                    NOT NULL,
          [folderisours]        BIT                                    NOT NULL,
          [docfoldercount]      INT                                    NOT NULL,
		  [Iteration]			INT									   NULL)


  DECLARE @AllFilesCount INT =0  

  IF(@includeparent =1)
  BEGIN
		SET @AllFilesCount = (SELECT count(*) FROM DiaryAttachments where CASECODE = @MatterCode)
		INSERT    
			INTO @DocFolders    
              ([id],    
               [parent],    
               [foldername],    
               [foldericon],
			   [folderimage],
               [foldershared],    
               [folderisours],    
               [documentcount])    
			SELECT 0,    
               -1,  -- To avoid recusrive loop in WebApi  
               'All',    
               0,
			   NULL,    
               0,    
               0,    
               @AllFilesCount
	END		

  IF ISNULL(@parentid, 0) = 0
    BEGIN
      INSERT
          INTO @DocFoldersX
              ([id],
               [parent],
               [foldername],
               [foldericon],
			   [folderimage],    
               [foldershared],
               [folderisours],
               [docfoldercount],
			   Iteration)
        SELECT [DF].[id],
               0,
               [DF].[foldername],
               [DF].[foldericon],
			    [DFU].[image], 
               0,
               1,
               0,
			   0
          FROM [dbo].[DocFolders] [DF]
		  LEFT JOIN [dbo].[DocFolderUploadedImages] [DFU]  
		  ON [DF].[foldericon] = [DFU].[id]    
         WHERE [DF].[parent] IS NULL
      ORDER BY [DF].[foldername],
               [DF].[id]
    END
  ELSE
    BEGIN
      IF @includeparent = 1
        BEGIN
            INSERT
              INTO @DocFoldersX
                  ([id],
                   [parent],
                   [foldername],
                   [foldericon],
				     [folderimage],    
                   [foldershared],
                   [folderisours],
                   [docfoldercount],
				   Iteration)
            SELECT [DF].[id],
                   ISNULL([DF].[parent], 0),
                   [DF].[foldername],
                   [DF].[foldericon],
				   [DFU].[image], 
                   0,
                   1,
                   0,
				   0
              FROM [dbo].[DocFolders] [DF]
			  	  LEFT JOIN [dbo].[DocFolderUploadedImages] [DFU]  
			  ON [DF].[foldericon] = [DFU].[id]  
             WHERE [DF].[id] = @parentid
          ORDER BY [DF].[foldername],
                   [DF].[id]
        END
      ELSE
        BEGIN
            INSERT
              INTO @DocFoldersX
                  ([id],
                   [parent],
                   [foldername],
                   [foldericon],
				   [folderimage],    
                   [foldershared],
                   [folderisours],
                   [docfoldercount],
				   Iteration)
            SELECT [DF].[id],
                   ISNULL([DF].[parent], 0),
                   [DF].[foldername],
                   [DF].[foldericon],
				   [DFU].[image],   
                   0,
                   1,
                   0,
				   0
              FROM [dbo].[DocFolders] [DF]
			  LEFT JOIN [dbo].[DocFolderUploadedImages] [DFU]  
			  ON [DF].[foldericon] = [DFU].[id]    
             WHERE [DF].[parent] = @parentid
          ORDER BY [DF].[foldername],
                   [DF].[id]
        END
    END


  UPDATE [DFX]
     SET [DFX].[foldershared] = [FSDF].[Shared],
         [DFX].[folderisours] = [IO].[IsOurs]
    FROM @DocFoldersX [DFX]
         INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                    CROSS APPLY (SELECT CASE WHEN COUNT(CASE WHEN ISNULL([FSS].[CollabDocFolderID], 0) = 0
                                                                  THEN 1
                                                             ELSE NULL END) = 0
                                                  THEN 0
                                             ELSE 1 END AS [IsOurs]
                                   FROM [dbo].[FileSharingMapping] [FSM]
                                        INNER JOIN [dbo].[FileSharingServers] [FSS]
         ON [FSS].[id] = [FSM].[FileSharingServersID]
                                  WHERE [FSM].[FileSharingDocFoldersID] = [FSDF].[DocFolderID]) [IO]
                 ON [FSDF].[DocFolderID] = [DFX].[id]

  
  DECLARE @ITEM INT=0

  
	WHILE EXISTS(SELECT NULL FROM [dbo].[DocFolders] [DF]
			  INNER JOIN @DocFoldersX DocFoldersX ON DF.parent=DocFoldersX.Id And Iteration=@Item)
    BEGIN

			INSERT
              INTO @DocFoldersX
                  ([id]
                  ,[parent]        
				  ,[foldername]    
				  ,[foldericon]    
				  ,[folderimage]	
				  ,[foldershared]  
				  ,[folderisours]  
				  ,[docfoldercount]
				  ,Iteration)
              SELECT [DF].[id],
                   ISNULL(DocFoldersX.ID, 0) [parent],
                   DF.[foldername],
                   [DF].[foldericon],
				   [DFU].[image],   
                   0 [foldershared],
                   1 [folderisours],
                   0 [docfoldercount], --INTO #DocFoldersX_Itr
				   @ITEM + 1 [Iteration]
              FROM [dbo].[DocFolders] [DF]
			  INNER JOIN @DocFoldersX DocFoldersX ON DF.parent=DocFoldersX.Id
			  LEFT JOIN [dbo].[DocFolderUploadedImages] [DFU]  
			  ON [DF].[foldericon] = [DFU].[id]    
             WHERE DocFoldersX.Iteration=@ITEM
			  ORDER BY [DF].[foldername],
					   [DF].[id]


			 SET @ITEM=@ITEM+1 
         
    END

  UPDATE [DF]
     SET [DF].[docfoldercount] = [TTD].[TOTAL]
    FROM @DocFoldersX  [DF]
         CROSS APPLY (SELECT COUNT(1) AS [TOTAL]
                        FROM [dbo].[DocFolderDocuments] [DFD]
                       WHERE [DFD].[DocFolderID] = [DF].[id]) [TTD]
	WHERE
	[DF].[Parent] <> -1

	Insert into @DocFolders([id],[parent],[foldername],[foldericon],[folderimage],[foldershared],[folderisours],[documentcount])
	select [id],[parent],[foldername],[foldericon],[folderimage],[foldershared],[folderisours],[docfoldercount]
    from 
	@DocFoldersX 
	Order by Foldername,
	Case when parent =0 then Id else parent end

  RETURN
END
GO

IF OBJECT_ID(N'[KEYHM_FN_GETFILEPATH]',N'FN')IS NOT NULL
    DROP FUNCTION [KEYHM_FN_GETFILEPATH]
GO


CREATE FUNCTION
       [dbo].[KEYHM_FN_GETFILEPATH]
	   (@DOCUMENT        VARCHAR(500),
	   @FPATH              VARCHAR(500))
RETURNS VARCHAR(255)
AS
/*******************************************************************************************************
* This function is used to restrict file not exceed 255 character.									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_GETFILEPATH]												   *
* Copied from			: [dbo].[ky_NETFNGETFILEPATH]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
    DECLARE @LEN INT
    DECLARE @RPATH VARCHAR(2000)
    SET @RPATH =  SUBSTRING(@FPATH,LEN(@FPATH)-CHARINDEX ('\',REVERSE(@FPATH))+2,LEN(@FPATH))
    SET @FPATH =  REPLACE(@FPATH,@RPATH,@DOCUMENT  )
    SET @LEN = CHARINDEX ('_',REVERSE(@DOCUMENT))
    IF( @LEN = 0)
    BEGIN
        SET @RPATH = @FPATH
    END
    ELSE
    BEGIN
        SET @RPATH = REPLACE(@FPATH,SUBSTRING(@DOCUMENT,0,LEN(@DOCUMENT)-CHARINDEX ('_',REVERSE(@DOCUMENT))+1)  ,'')
    END
    IF(LEN(@FPATH) > 255)
    BEGIN
        IF(LEN(@RPATH) < 255)
        BEGIN
            DECLARE @PLENGTH INT
            SET @PLENGTH = 255 - LEN(@RPATH )
            DECLARE @FNAME VARCHAR(200) -- PINO 2015-04-20
      SET @FNAME = SUBSTRING(@DOCUMENT,0,LEN(@DOCUMENT)-CHARINDEX ('_',REVERSE(@DOCUMENT))+1) --PINO 2015-04-20
            SET @RPATH =  SUBSTRING(@FNAME,0,@PLENGTH)
            SET @FPATH = REPLACE(@FPATH, @FNAME, @RPATH)
            RETURN @FPATH
        END
        ELSE IF(LEN(@RPATH) = 255)
        BEGIN
            RETURN  @RPATH
        END
        ELSE
        BEGIN
            RETURN 'NOCHANGE'
        END
    END
    ELSE
    BEGIN
        RETURN @FPATH
    END
 RETURN 'NOCHANGE'
END
GO


IF EXISTS
  (SELECT *
     FROM SYS.[objects] SO
    WHERE SO.[name] = 'KEYHM_FN_GetOldPermissions'
      AND SO.[type] = 'FN')
BEGIN
  DROP FUNCTION [dbo].[KEYHM_FN_GetOldPermissions]
END
GO

 CREATE FUNCTION
        [dbo].[KEYHM_FN_GetOldPermissions]
       (@HANDLER VARCHAR(10))
RETURNS BIGINT
AS

/*******************************************************************************************************
*																								       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_FN_GetOldPermissions]											   *
* Copied from			: [dbo].[ky_NETFNGetOldPermissions]			                                   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-26    Vinodhan K        Created                                                              *
 *******************************************************************************************************/

BEGIN

DECLARE @PERMISSIONS BIGINT

DECLARE @LOGONS TABLE
       ([CODE]        VARCHAR(10),
        [LOGON]       VARCHAR(10),
        [NAME]        varchar(50),
        [OPE_NUMBER]  int)

DECLARE @LOGONS2 TABLE
       ([CODE]        VARCHAR(10),
        [LOGON]       VARCHAR(10),
        [NAME]        varchar(50),
        [OPE_NUMBER]  int)

  /* To aid uniformity, all queries have the same form. In this first one it should not be necessary to join to @LOGONs but
     doing so is harmless and it makes this query look the same as all the others.

     The Outer Apply links to DS1, DS2, DS3 and DS4 check that the DSSW21 entry has not already been matched to a handler.

     If this is so, it tries to match the DSSW21 record to a handler with an exact name match.

     */
  INSERT
    INTO @LOGONS2
        ([CODE],
         [LOGON],
         [NAME],
         [OPE_NUMBER])
  SELECT MTC.[CODE],
         MTC.[LOGON],
         MTC.[NAME],
         MTC.[MATCH]
    FROM (select HAN.[CODE],
                 HAN.[LOGON],
                 HAN.[NAME],
                 CASE WHEN DS1.[OPE_NUMBER] IS NOT NULL
                           THEN DS1.[OPE_NUMBER]
                      ELSE DS2.[OPE_NUMBER] END AS [Match]
            from [dbo].[Handlers] HAN
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE RTrim(HAN.[NAME]) LIKE RTrim(DS.[OPE_FIRSTNAME]) + '%' + RTRIM(DS.[OPE_SURNAME])) DS1
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE RTrim(HAN.[NAME]) LIKE RTrim(DS.[OPE_SURNAME]) + '%' + RTRIM(DS.[OPE_FIRSTNAME])) DS2
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE Soundex(RTrim(HAN.[NAME])) = SOUNDEX(RTrim(DS.[OPE_SURNAME]) + ' ' + RTRIM(DS.[OPE_FIRSTNAME]))) DS3
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE Soundex(RTrim(HAN.[NAME])) = SOUNDEX(RTrim(DS.[OPE_FIRSTNAME]) + ' ' + RTRIM(DS.[OPE_SURNAME]))) DS4
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                                     LEFT OUTER JOIN [dbo].[Handlers] HN
                                                  ON HN.[NAME] LIKE RTrim(DS.[OPE_FIRSTNAME]) + '%' + RTRIM(DS.[OPE_SURNAME])
                                                  OR HN.[NAME] LIKE RTrim(DS.[OPE_SURNAME]) + '%' + RTRIM(DS.[OPE_FIRSTNAME])
                               WHERE DS1.[OPE_NUMBER] IS NULL
                                 AND DS2.[OPE_NUMBER] IS NULL
                                 AND DS3.[OPE_NUMBER] IS NULL
                                 AND DS4.[OPE_NUMBER] IS NULL
                                 AND HN.[CODE] IS NULL
                                 AND (   RTrim(HAN.[NAME]) LIKE '%' + RTrim(DS.[OPE_FIRSTNAME]) + '%'
                                      OR RTrim(HAN.[NAME]) LIKE '%' + RTrim(DS.[OPE_SURNAME]) + '%')) DS5
          WHERE HAN.[CODE] = @HANDLER
            AND RTRIM(ISNULL(HAN.[Logon], '')) <> '') MTC
         LEFT OUTER JOIN @LOGONS LO
                      ON LO.[OPE_NUMBER] = MTC.[Match]
   WHERE MTC.[Match] IS NOT NULL
     AND LO.[OPE_NUMBER] IS NULL

  -- This eliminates duplicate matches. If there are more than one handler matching a DSSW21 entry, we can't be sure which one it is,
  -- and we will ignore the match. We only include the ones that have exactly ONE match
  INSERT
    INTO @LOGONS
        ([CODE],
         [LOGON],
         [NAME],
         [OPE_NUMBER])
  SELECT LO.[CODE],
         LO.[LOGON],
         LO.[NAME],
         LO.[OPE_NUMBER]
    FROM (  SELECT OPE_NUMBER
              from @LOGONS2
          GROUP BY OPE_NUMBER
            HAVING COUNT(1) = 1) MH
         INNER JOIN @LOGONS2 LO
                 ON LO.[OPE_NUMBER] = MH.[OPE_NUMBER]

  DELETE @LOGONS2

  /* The Outer Apply links to DS1, DS2, DS3 and DS4 check that the DSSW21 entry has not already been matched to a handler.

     If this is so, it tries to match the DSSW21 record to a handler with an exact name match.

     */
  INSERT
    INTO @LOGONS2
        ([CODE],
         [LOGON],
         [NAME],
         [OPE_NUMBER])
  SELECT MTC.[CODE],
         MTC.[LOGON],
         MTC.[NAME],
         MTC.[MATCH]
    FROM (select HAN.[CODE],
                 HAN.[LOGON],
                 HAN.[NAME],
                 CASE WHEN DS1.[OPE_NUMBER] IS NOT NULL
                           THEN DS1.[OPE_NUMBER]
                      WHEN DS2.[OPE_NUMBER] IS NOT NULL
                           THEN DS2.[OPE_NUMBER]
                      WHEN DS3.[OPE_NUMBER] IS NOT NULL
                           THEN DS3.[OPE_NUMBER]
                      ELSE DS4.[OPE_NUMBER] END AS [Match]
            from [dbo].[Handlers] HAN
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE RTrim(HAN.[NAME]) LIKE RTrim(DS.[OPE_FIRSTNAME]) + '%' + RTRIM(DS.[OPE_SURNAME])) DS1
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE RTrim(HAN.[NAME]) LIKE RTrim(DS.[OPE_SURNAME]) + '%' + RTRIM(DS.[OPE_FIRSTNAME])) DS2
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE Soundex(RTrim(HAN.[NAME])) = SOUNDEX(RTrim(DS.[OPE_SURNAME]) + ' ' + RTRIM(DS.[OPE_FIRSTNAME]))) DS3
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE Soundex(RTrim(HAN.[NAME])) = SOUNDEX(RTrim(DS.[OPE_FIRSTNAME]) + ' ' + RTRIM(DS.[OPE_SURNAME]))) DS4
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                                     LEFT OUTER JOIN [dbo].[Handlers] HN
                                                  ON HN.[NAME] LIKE RTrim(DS.[OPE_FIRSTNAME]) + '%' + RTRIM(DS.[OPE_SURNAME])
                                                  OR HN.[NAME] LIKE RTrim(DS.[OPE_SURNAME]) + '%' + RTRIM(DS.[OPE_FIRSTNAME])
                               WHERE DS1.[OPE_NUMBER] IS NULL
                                 AND DS2.[OPE_NUMBER] IS NULL
                                 AND DS3.[OPE_NUMBER] IS NULL
                                 AND DS4.[OPE_NUMBER] IS NULL
                                 AND HN.[CODE] IS NULL
                                 AND (   RTrim(HAN.[NAME]) LIKE '%' + RTrim(DS.[OPE_FIRSTNAME]) + '%'
                                      OR RTrim(HAN.[NAME]) LIKE '%' + RTrim(DS.[OPE_SURNAME]) + '%')) DS5
          WHERE HAN.[CODE] = @HANDLER
            AND RTRIM(ISNULL(HAN.[Logon], '')) <> '') MTC
         LEFT OUTER JOIN @LOGONS LO
                      ON LO.[OPE_NUMBER] = MTC.[Match]
   WHERE MTC.[Match] IS NOT NULL
     AND LO.[OPE_NUMBER] IS NULL

  INSERT
    INTO @LOGONS
        ([CODE],
         [LOGON],
         [NAME],
         [OPE_NUMBER])
  SELECT LO.[CODE],
         LO.[LOGON],
         LO.[NAME],
         LO.[OPE_NUMBER]
    FROM (  SELECT OPE_NUMBER
              from @LOGONS2
          GROUP BY OPE_NUMBER
            HAVING COUNT(1) = 1) MH
         INNER JOIN @LOGONS2 LO
                 ON LO.[OPE_NUMBER] = MH.[OPE_NUMBER]

  DELETE @LOGONS2

  INSERT
    INTO @LOGONS2
        ([CODE],
         [LOGON],
         [NAME],
         [OPE_NUMBER])
  SELECT MTC.[CODE],
         MTC.[LOGON],
         MTC.[NAME],
         MTC.[MATCH]
    FROM (select HAN.[CODE],
                 HAN.[LOGON],
                 HAN.[NAME],
                 CASE WHEN DS1.[OPE_NUMBER] IS NOT NULL
                           THEN DS1.[OPE_NUMBER]
                      WHEN DS2.[OPE_NUMBER] IS NOT NULL
                           THEN DS2.[OPE_NUMBER]
                      WHEN DS3.[OPE_NUMBER] IS NOT NULL
                           THEN DS3.[OPE_NUMBER]
                      WHEN DS4.[OPE_NUMBER] IS NOT NULL
                           THEN DS4.[OPE_NUMBER]
                      ELSE DS5.[OPE_NUMBER] END AS [Match]
            from [dbo].[Handlers] HAN
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE RTrim(HAN.[NAME]) LIKE RTrim(DS.[OPE_FIRSTNAME]) + '%' + RTRIM(DS.[OPE_SURNAME])) DS1
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE RTrim(HAN.[NAME]) LIKE RTrim(DS.[OPE_SURNAME]) + '%' + RTRIM(DS.[OPE_FIRSTNAME])) DS2
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE Soundex(RTrim(HAN.[NAME])) = SOUNDEX(RTrim(DS.[OPE_SURNAME]) + ' ' + RTRIM(DS.[OPE_FIRSTNAME]))) DS3
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                               WHERE Soundex(RTrim(HAN.[NAME])) = SOUNDEX(RTrim(DS.[OPE_FIRSTNAME]) + ' ' + RTRIM(DS.[OPE_SURNAME]))) DS4
                 OUTER APPLY (SELECT TOP 1 DS.[OPE_NUMBER]
                                FROM [dbo].[DSSW21] DS
                                     LEFT OUTER JOIN [dbo].[Handlers] HN
                                                  ON HN.[NAME] LIKE RTrim(DS.[OPE_FIRSTNAME]) + '%' + RTRIM(DS.[OPE_SURNAME])
                                                  OR HN.[NAME] LIKE RTrim(DS.[OPE_SURNAME]) + '%' + RTRIM(DS.[OPE_FIRSTNAME])
                               WHERE DS1.[OPE_NUMBER] IS NULL
                                 AND DS2.[OPE_NUMBER] IS NULL
                                 AND DS3.[OPE_NUMBER] IS NULL
                                 AND DS4.[OPE_NUMBER] IS NULL
                                 AND HN.[CODE] IS NULL
                                 AND (   RTrim(HAN.[NAME]) LIKE '%' + RTrim(DS.[OPE_FIRSTNAME]) + '%'
                                      OR RTrim(HAN.[NAME]) LIKE '%' + RTrim(DS.[OPE_SURNAME]) + '%')) DS5
          WHERE HAN.[CODE] = @HANDLER
            AND RTRIM(ISNULL(HAN.[Logon], '')) <> '') MTC
         LEFT OUTER JOIN @LOGONS LO
                      ON LO.[OPE_NUMBER] = MTC.[Match]
   WHERE MTC.[Match] IS NOT NULL
     AND LO.[OPE_NUMBER] IS NULL

  INSERT
    INTO @LOGONS
        ([CODE],
         [LOGON],
         [NAME],
         [OPE_NUMBER])
  SELECT LO.[CODE],
         LO.[LOGON],
         LO.[NAME],
         LO.[OPE_NUMBER]
    FROM (  SELECT OPE_NUMBER
              from @LOGONS2
          GROUP BY OPE_NUMBER
            HAVING COUNT(1) = 1) MH
         INNER JOIN @LOGONS2 LO
                 ON LO.[OPE_NUMBER] = MH.[OPE_NUMBER]

  DELETE @LOGONS2

  SELECT @PERMISSIONS = CONVERT(BIGINT, ISNULL(JP.[JPER_Permissions], 0))
    from [dbo].[Handlers] HAN
         LEFT OUTER JOIN @LOGONS LO
                         INNER JOIN [dbo].[DSSW21] DS
                                 ON DS.[OPE_NUMBER] = LO.[OPE_NUMBER]
                      ON LO.[CODE] = HAN.[CODE]
         LEFT OUTER JOIN JPermissions JP
                      ON JP.[JPER_UserNumber] = LO.[OPE_NUMBER]
   WHERE LO.[OPE_NUMBER] IS NOT NULL
  ORDER BY LO.[OPE_NUMBER]

  SET @PERMISSIONS = ISNULL(@PERMISSIONS, 0)

  RETURN @PERMISSIONS
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FN_GetUNCPathFromFile'
      AND SO.[type] = 'FN')
  BEGIN
    DROP FUNCTION [dbo].[KEYHM_FN_GetUNCPathFromFile]
  END
GO

CREATE FUNCTION
       [dbo].[KEYHM_FN_GetUNCPathFromFile]
      (@strFileName     varchar(max))
RETURNS varchar(max)
AS
/************************************************************************
 *
 * Get the UNC Location of a file (provided the drive is stored in
 * the UNCAlias table)
 *
 * Modification History
 * 2015-10-20 Pino Carafa Imported into Framework
 * 2019-12-26 Arun V Copied from Ky_GetUNCPathFromFile
 ************************************************************************/
BEGIN

    DECLARE @strUNCFileName varchar(max)

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

    IF (SUBSTRING(@strUNCFileName, 2, 1) = ':')
      BEGIN
        SELECT @strUNCFileName = ISNULL(MAX(UNC.[UNC]) + SUBSTRING(@strUNCFileName, 3, LEN(@strUNCFileName) - 2), @strUNCFileName)
          FROM [dbo].[UNCAlias] UNC
         WHERE SUBSTRING(@strUNCFileName, 1, 1) = UNC.[Drive]

        SET @strUNCFileName = LEFT(@strUNCFileName, 2) + REPLACE(RIGHT(@strUNCFileName, LEN(@strUNCFileName) - 2), '\\', '\')
      END

    RETURN @strUNCFileName
END

GO
IF EXISTS
  (SELECT *
     FROM SYS.[objects] SO
    WHERE SO.[name] = 'KEYHM_FN_MatterClosable'
      AND SO.[type] = 'TF')
BEGIN
  DROP FUNCTION [dbo].[KEYHM_FN_MatterClosable]  
END
GO

/*******************************************************************************************************
* Get the parameters to establish whether a matter can be closed at this point.						   *
* Please note that Bal, Rec, Diary and Undertakings should prevent a matter from closing, while		   *
* Time and Charge should lead to a warning and the user can decide to close the matter anyway.         *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_MatterClosable]						   					   *
* Copied from			: [dbo].[ky_NETFNMatterClosable]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-24	Vinodhan K		Created                                                                *
*******************************************************************************************************/
GO

IF [dbo].[ISSAM4]() = 1
  BEGIN
    EXEC ('
CREATE FUNCTION
       [dbo].[KEYHM_FN_MatterClosable]
      (@MATTER VARCHAR(20))
RETURNS @Closables TABLE
       ([AlreadyClosed]                          int,
        [HasOutstandingBal]                      int,
        [HasOutstandingTimeBal]                  int,
        [HasOutstandingChargeBal]                int,
        [HasOutstandingRec]                      int,
        [HasOutstandingDiary]                    int,
        [HasOutstandingUndertakings]             int)
AS

BEGIN

DECLARE @AlreadyClosed INT
DECLARE @HasOutstandingRec INT
DECLARE @HasOutstandingBal INT
DECLARE @HasOutstandingTimeBal INT
DECLARE @HasOutstandingChargeBal INT
DECLARE @HasOutstandingDiary INT
DECLARE @HasOutstandingUndertakings INT
DECLARE @Year INT

DECLARE @IsSAM4 bit

SET @IsSAM4 = 1

-- Please see also: ky_NETCaseSummaryPageLoad. 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.
DECLARE @TimeBal      INT
DECLARE @ChargeBal    DECIMAL(19, 2)
DECLARE @TotalCharge  Decimal(19, 2)
DECLARE @TotalTime    INT
DECLARE @TimeEntryTotalCharge         DECIMAL(19, 2)
DECLARE @TimeEntryTotalTime           INT

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] = @MATTER
   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)

DECLARE @NCOMMAND NVARCHAR(MAX)
-- To ensure SAM3 will retrieve these from [dbo].[matters]
SET @DebtBal = 0 
SET @OutlayBal = 0
SET @ClientCurrent = 0
SET @ClientDeposit = 0

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] = @MATTER
   AND TRN.[Posted] = ''Y''
   AND TRN.[RecType] <> ''V''
   AND TRN.[CorrectionInd] = ''L''

SELECT @AlreadyClosed = CASE WHEN MAT.[Closed] = ''Y'' THEN 1 ELSE 0 END,
       @HasOutstandingBal = CASE WHEN @DebtBal <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[DebtBal], 0) <> 0
                                      THEN 1
                                 WHEN @OutlayBal <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[OutlayBal], 0) <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[ClientBal], 0) <> 0 --No need to check @ClientCurBal + @ClientDepBal
                                      THEN 1
                                 WHEN @ClientCurrent <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[ClientCurBal], 0) <> 0
                                      THEN 1
                                 WHEN @ClientDeposit <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[ClientDepBal], 0) <> 0
                                      THEN 1
                                 ELSE 0 END,
       @HasOutstandingTimeBal = CASE WHEN @TimeBal <> 0 THEN 1 ELSE 0 END,
       @HasOutstandingChargeBal = CASE WHEN @ChargeBal <> 0 THEN 1 ELSE 0 END
  FROM [dbo].[matters] MAT
 WHERE MAT.[Code] = @MATTER

SET @AlreadyClosed = ISNULL(@AlreadyClosed, 0)
SET @HasOutstandingBal = ISNULL(@HasOutstandingBal, 0)
SET @HasOutstandingTimeBal = ISNULL(@HasOutstandingTimeBal, 0)
SET @HasOutstandingChargeBal = ISNULL(@HasOutstandingChargeBal, 0)

SELECT @YEAR = ISNULL(CONVERT(INT, CTL.[NumValue]), DATEPART(YEAR, GetDate()))
  FROM [dbo].[CtrlNum] CTL
 WHERE CTL.[Code] = ''CurYear''

IF (@YEAR IS NULL)
  BEGIN
    SET @YEAR = DATEPART(YEAR, GetDate())
  END

SELECT @HasOutstandingRec = CASE COUNT(1) WHEN 0 THEN 0 ELSE 1 END
  FROM [dbo].[Transactions] TRN
 WHERE TRN.[MatterCode] = @MATTER
   AND TRN.[Posted] = ''Y''
   AND TRN.[RecType] <> ''V''
   AND (   TRN.[CorrectionInd] = ''L''
        OR TRN.[CorrectionInd] = ''C'')
   AND TRN.[PostingYear] = @YEAR
   AND TRN.[Reconciliation] <= 0
    
SET @HasOutstandingRec = ISNULL(@HasOutstandingRec, 0)

SELECT @HasOutstandingDiary = CASE WHEN COUNT(1) = 0 THEN 0 ELSE 1 END
  FROM [dbo].[diary] DIA
 WHERE DIA.[CASECODE] = @MATTER
   AND DIA.[STATUS] <> 1

SELECT @HasOutstandingUndertakings = CASE WHEN COUNT(1) = 0 THEN 0 ELSE 1 END
  FROM [dbo].[Undertakings] UND
 WHERE UND.[MATTER] = @MATTER
   AND UND.[DISCHARGEDATE] IS NULL

INSERT
  INTO @Closables
      ([AlreadyClosed],
       [HasOutstandingBal],
       [HasOutstandingTimeBal],
       [HasOutstandingChargeBal],
       [HasOutstandingRec],
       [HasOutstandingDiary],
       [HasOutstandingUndertakings])
SELECT @AlreadyClosed                       AS [AlreadyClosed],
       @HasOutstandingBal                   AS [HasOutstandingBal],
       @HasOutstandingTimeBal               AS [HasOutstandingTimeBal],
       @HasOutstandingChargeBal             AS [HasOutstandingChargeBal],
       @HasOutstandingRec                   AS [HasOutstandingRec],
       @HasOutstandingDiary                 AS [HasOutstandingDiary],
       @HasOutstandingUndertakings          AS [HasOutstandingUndertakings]

RETURN
END')
  END
ELSE
  BEGIN
    EXEC ('
CREATE FUNCTION
       [dbo].[KEYHM_FN_MatterClosable]
      (@MATTER VARCHAR(20))
RETURNS @Closables TABLE
       ([AlreadyClosed]                          int,
        [HasOutstandingBal]                      int,
        [HasOutstandingTimeBal]                  int,
        [HasOutstandingChargeBal]                int,
        [HasOutstandingRec]                      int,
        [HasOutstandingDiary]                    int,
        [HasOutstandingUndertakings]             int)
AS
/***********************************************************************************************
 *
 * KEYHM_FN_MatterClosable get the parameters to establish whether a matter can be
 *                        closed at this point. Please note that Bal, Rec, Diary and
 *                        Undertakings should prevent a matter from closing, while
 *                        Time and Charge should lead to a warning and the user can
 *                        decide to close the matter anyway.
 *
 * Modifications: 2015-02-18  Pino  Change calculations to accomodate SAM4, using
 *                                  original calculations from ky_NETSPCaseSummaryPageLoad
 *                                  Added warning that if any of these calculations are to be
 *                                  changed here, then the corresponding calculations in other
 *                                  procedure(s) must be changed accordingly.
 *                2015-03-04  Pino  No functional change but added reference to 
 *                                  ky_NETTLFetchTimeEntry in comment below.
 *
 *                2015-10-29  Pino Carafa
 *                                  Include calculation for @HasOutstandingRec
 *
 *
 ***********************************************************************************************/
BEGIN

DECLARE @AlreadyClosed INT
DECLARE @HasOutstandingRec INT
DECLARE @HasOutstandingBal INT
DECLARE @HasOutstandingTimeBal INT
DECLARE @HasOutstandingChargeBal INT
DECLARE @HasOutstandingDiary INT
DECLARE @HasOutstandingUndertakings INT
DECLARE @Year INT

DECLARE @IsSAM4 bit

SET @IsSAM4 = 0

-- Please see also: ky_NETCaseSummaryPageLoad. 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.
DECLARE @TimeBal      INT
DECLARE @ChargeBal    DECIMAL(19, 2)
DECLARE @TotalCharge  Decimal(19, 2)
DECLARE @TotalTime    INT
DECLARE @TimeEntryTotalCharge         DECIMAL(19, 2)
DECLARE @TimeEntryTotalTime           INT

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] = @MATTER
   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)

DECLARE @NCOMMAND NVARCHAR(MAX)
-- To ensure SAM3 will retrieve these from [dbo].[matters]
SET @DebtBal = 0 
SET @OutlayBal = 0
SET @ClientCurrent = 0
SET @ClientDeposit = 0

SELECT @AlreadyClosed = CASE WHEN MAT.[Closed] = ''Y'' THEN 1 ELSE 0 END,
       @HasOutstandingBal = CASE WHEN @DebtBal <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[DebtBal], 0) <> 0
                                      THEN 1
                                 WHEN @OutlayBal <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[OutlayBal], 0) <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[ClientBal], 0) <> 0 --No need to check @ClientCurBal + @ClientDepBal
                                      THEN 1
                                 WHEN @ClientCurrent <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[ClientCurBal], 0) <> 0
                                      THEN 1
                                 WHEN @ClientDeposit <> 0
                                      THEN 1
                                 WHEN ISNULL(MAT.[ClientDepBal], 0) <> 0
                                      THEN 1
                                 ELSE 0 END,
       @HasOutstandingTimeBal = CASE WHEN @TimeBal <> 0 THEN 1 ELSE 0 END,
       @HasOutstandingChargeBal = CASE WHEN @ChargeBal <> 0 THEN 1 ELSE 0 END
  FROM [dbo].[matters] MAT
 WHERE MAT.[Code] = @MATTER

SET @AlreadyClosed = ISNULL(@AlreadyClosed, 0)
SET @HasOutstandingBal = ISNULL(@HasOutstandingBal, 0)
SET @HasOutstandingTimeBal = ISNULL(@HasOutstandingTimeBal, 0)
SET @HasOutstandingChargeBal = ISNULL(@HasOutstandingChargeBal, 0)

SELECT @YEAR = ISNULL(CTL.[YEAR], DATEPART(YEAR, GetDate()))
  FROM [dbo].[Control] CTL

IF (@YEAR IS NULL)
  BEGIN
    SET @YEAR = DATEPART(YEAR, GetDate())
  END
  
SELECT @HasOutstandingRec = CASE COUNT(1) WHEN 0 THEN 0 ELSE 1 END
  FROM [dbo].[MatterLedger] MAL
       INNER JOIN [dbo].[BatchH] BH
                  INNER JOIN [dbo].[BankRecHistory] BHS
                          ON BHS.[BANKAC] = BH.[CODE]
               ON BH.[BATCHNO] = MAL.[BATCHNO]
              AND BH.[RECNO] <= 0
              AND BH.[TYPE] IN (''P'', ''R'', ''T'')
  WHERE MAL.[MATTER] = @MATTER
    AND MAL.[YEAR] = @YEAR
    AND MAL.[REF] <> ''EUROADJ''
    
SET @HasOutstandingRec = ISNULL(@HasOutstandingRec, 0)

SELECT @HasOutstandingDiary = CASE WHEN COUNT(1) = 0 THEN 0 ELSE 1 END
  FROM [dbo].[diary] DIA
 WHERE DIA.[CASECODE] = @MATTER
   AND DIA.[STATUS] <> 1

SELECT @HasOutstandingUndertakings = CASE WHEN COUNT(1) = 0 THEN 0 ELSE 1 END
  FROM [dbo].[Undertakings] UND
 WHERE UND.[MATTER] = @MATTER
   AND UND.[DISCHARGEDATE] IS NULL

INSERT
  INTO @Closables
      ([AlreadyClosed],
       [HasOutstandingBal],
       [HasOutstandingTimeBal],
       [HasOutstandingChargeBal],
       [HasOutstandingRec],
       [HasOutstandingDiary],
       [HasOutstandingUndertakings])
SELECT @AlreadyClosed                       AS [AlreadyClosed],
       @HasOutstandingBal                   AS [HasOutstandingBal],
       @HasOutstandingTimeBal               AS [HasOutstandingTimeBal],
       @HasOutstandingChargeBal             AS [HasOutstandingChargeBal],
       @HasOutstandingRec                   AS [HasOutstandingRec],
       @HasOutstandingDiary                 AS [HasOutstandingDiary],
       @HasOutstandingUndertakings          AS [HasOutstandingUndertakings]

RETURN
END')
  END

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

CREATE FUNCTION
       [dbo].[KEYHM_FN_MatterHeaderDetails]
      (@matter VARCHAR(20))
RETURNS @MD TABLE
       ([CODE]              VARCHAR(20),
        [ClientCode]        VARCHAR(10),
        [MatterNo]          VARCHAR(10),
        [YourRef]           VARCHAR(100),
        [DESCRIPTION]       VARCHAR(300),
        [FECode]            VARCHAR(10),
        [FEName]            VARCHAR(100),
        [Name]              VARCHAR(256),
        [TelNo]             VARCHAR(50),
        [Address]           VARCHAR(2000),
        [Closed]            CHAR(1),
        [TOOLTIP]           VARCHAR(1000),
        [IsChildcare]       CHAR(1),
        [User1]             VARCHAR(100),
        [User2]             VARCHAR(100),
        [User3]             VARCHAR(100),
        [Partner]           VARCHAR(10),
        [PartnerName]       VARCHAR(100),
        [CompBillingMatter] VARCHAR(20),
        [MatterUniqueID]    INT)
AS
/*******************************************************************************************************
* Returns the details for the current matter, to be displayed in the                                   *
* Client/Case section of the software, ledgers, etc.                                                   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_MatterHeaderDetails]										   *
* Copied from			: [dbo].[ky_NETTFMatterHeaderDetails]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 
BEGIN

INSERT
  INTO @MD
      ([CODE],
       [ClientCode],
       [MatterNo],
       [YourRef],
       [DESCRIPTION],
       [FECode],
       [FEName],
       [Name],
       [TelNo],
       [Address],
       [Closed],
       [TOOLTIP],
       [IsChildcare],
       [User1],
       [User2],
       [User3],
       [Partner],
       [PartnerName],
       [CompBillingMatter],
       [MatterUniqueID])
SELECT RTRIM(ISNULL([MAT].[Code], ''))                             AS [Code],
       RTRIM(ISNULL([MAT].[ClientCode], ''))                       AS [ClientCode],
       RTRIM(ISNULL([MAT].[Matter], ''))                           AS [MatterNo],
       RTRIM(ISNULL([MAT].[YourRef], ''))                          AS [YourRef],
       RTRIM(ISNULL([MAT].[Description], ''))                      AS [Description],
       RTRIM(ISNULL([MAT].[FECode], ''))                           AS [FECode],
       RTRIM(ISNULL([HAN].[NAME], ''))                             AS [FEName],
       RTRIM(ISNULL([CT].[Name], ''))                              AS [Name],
       RTRIM(ISNULL([CT].[Tel], ''))                               AS [TelNo],
       RTRIM(ISNULL([CT].[Address], ''))                           AS [Address],
       CASE WHEN RTRIM(ISNULL(MAT.[Closed], 'N')) = 'Y'
                 THEN 'Y'
            ELSE 'N' END                                           AS [Closed],
         RTRIM(ISNULL([CL].[CLNAME], ''))
       + CHAR(13)
       + 'W:' + RTRIM(ISNULL([CL].[CLTEL], ' Nil '))
       + CHAR(13)
       + 'M:' + RTRIM(ISNULL([CL].[CLMOBNO], ' Nil '))             AS [TOOLTIP],
       CASE WHEN [WKT].[CODE] IS NULL
                 THEN 'N'
            WHEN [WKT].[ChildCare] IS NULL
                 THEN 'N'
            WHEN [WKT].[ChildCare] = 'Y'
                 THEN 'Y'
            ELSE 'N' END                                           AS [IsChildcare],
       ISNULL([MAT].[User1], '')                                   AS [User1],
       ISNULL([MAT].[User2], '')                                   AS [User2],
       ISNULL([MAT].[User3], '')                                   AS [User3],
       ISNULL([MAT].[Partner], '')                                 AS [Partner],
       ISNULL([PRT].[NAME], '')                                    AS [PartnerName],
       RTRIM(ISNULL([MAT].[CompBillingMatter], ''))                AS [CompBillingMatter],
       [MAT].[UniqueID]                                            AS [MatterUniqueID]
  FROM [dbo].[matters] [MAT]
       LEFT OUTER JOIN [dbo].[Contacts] [CT]
                       INNER JOIN [dbo].[CLIENT] [CL]
                               ON [CL].[CLCODE] =[CT].[Code]
                    ON [CT].[Code] = [MAT].[ClientCode]
       LEFT OUTER JOIN [dbo].[Handlers] [HAN]
                    ON [HAN].[CODE] = [MAT].[FECode]
       LEFT OUTER JOIN [dbo].[WorkTypes] [WKT]
                    ON [WKT].[CODE] = MAT.[WType]
       LEFT OUTER JOIN [dbo].[Handlers] AS [PRT]
                    ON [PRT].[CODE] = [MAT].[Partner]
 WHERE [MAT].[Code] = @matter

RETURN
END

GO
IF EXISTS
  (SELECT *
     FROM SYS.[objects] SO
    WHERE SO.[name] = 'KEYHM_FN_RemoveSpuriousWhitespace'
      AND SO.[type] = 'FN')
BEGIN
  DROP FUNCTION [dbo].[KEYHM_FN_RemoveSpuriousWhitespace]
END
GO

CREATE FUNCTION
       [dbo].[KEYHM_FN_RemoveSpuriousWhitespace]
      (@original VARCHAR(MAX),
       @maxlen   INT)
RETURNS VARCHAR(5000)
AS
/*******************************************************************************************************
* Removes newlines, line feeds, non-breaking spaces and multiple spaces from the input				   *
*   string in order to produce an output format suitable for display in list.                          *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_RemoveSpuriousWhitespace]			                           *
* Copied from			: [dbo].[ky_RemoveSpuriousWhitespace2]				                           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-05-31	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
  DECLARE @len int

  SET @original = ISNULL(@original, '')
  IF LEN(@original) > (2 * @maxlen)
    BEGIN
      SET @original = SUBSTRING(@original, 1, (2 * @maxlen))
    END

  SET @original = REPLACE(@original, char(10), ' ')
  SET @original = REPLACE(@original, char(13), ' ')
  SET @original = REPLACE(@original, char(160), ' ')

  SET @original = RTRIM(@original)
  
  SET @len = 0
    WHILE (@len <> LEN(@original))
      BEGIN
        SET @len = LEN(@original)
        SET @original = REPLACE(@original, '  ', ' ')
      END

  RETURN SUBSTRING(@original, 1, @maxlen)
  
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FN_SplitString'
      AND SO.[type] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[KEYHM_FN_SplitString]
  END
GO

CREATE FUNCTION KEYHM_FN_SplitString
(    
      @Input NVARCHAR(MAX),
      @Character CHAR(1)
)
RETURNS @Output TABLE (
      Item NVARCHAR(1000)
)
AS
/*******************************************************************************************************
* Splits a string on the character specifed (like ',').												   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_FN_SplitString]												   *
* Copied from			: [dbo].[ky_NETFNSplitString]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-13	Vinodhan K		Created                                                                *
*******************************************************************************************************/
BEGIN
      DECLARE @StartIndex INT, @EndIndex INT
 
      SET @StartIndex = 1
      IF SUBSTRING(@Input, LEN(@Input) - 1, LEN(@Input)) <> @Character
      BEGIN
            SET @Input = @Input + @Character
      END
 
      WHILE CHARINDEX(@Character, @Input) > 0
      BEGIN
            SET @EndIndex = CHARINDEX(@Character, @Input)
           
            INSERT INTO @Output(Item)
            SELECT SUBSTRING(@Input, @StartIndex, @EndIndex - 1)
           
            SET @Input = SUBSTRING(@Input, @EndIndex + 1, LEN(@Input))
      END
 
      RETURN
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_FN_UserCanPostTime'
      AND SO.[type] = 'FN')
  BEGIN
    DROP FUNCTION [dbo].[KEYHM_FN_UserCanPostTime]
  END
GO

CREATE FUNCTION
       [dbo].[KEYHM_FN_UserCanPostTime]
      (@MATTER   VARCHAR(20),
       @HANDLER  VARCHAR(20),
       @RECORDID INT)
RETURNS INT
AS
/*******************************************************************************************************
 *  This function will check if a																	   *
 *  given user can post time a given matter.														   *
 *																									   *
 *  Return Bit Mask:																				   *
 *      0 - User can post																			   *
 *      1 - Matter doesn't exist																	   *
 *      2 - Matter is closed																		   *
 *      4 - Matter charge list enabled but user not present											   *
 *      8 - Client charge list enabled but user not present											   *
 *      16 - Task not specified																		   *
 *      32 - Client is not approved for anti-money laundering (KEYD-4890)							   *
 *																									   *
 *  Flag Bit Mask:																					   *
 *      1 - Matter charge out rate list is enabled													   *
 *      2 - Client charge out rate list is enabled													   *
 *      4 - User is in Matter charge out rate list													   *
 *      8 - User is in Client charge out rate list													   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_FN_UserCanPostTime]											   *
* Copied from			: [dbo].[ky_NETFNUserCanPostTime]											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
    DECLARE @RETURN      INT -- BitWise value where bits are mapped to errors
    DECLARE @FLAG        INT -- BitWise value for charge out rates
    DECLARE @CHECK       BIT -- Checks if a setting is enabled or not
    DECLARE @CHARGEGROUP VARCHAR(10) -- Charge group of @HANDLER

    SET @RETURN = 0
    SET @FLAG = 0

    SET @MATTER = ISNULL(@MATTER, '')
    SET @HANDLER = ISNULL(@HANDLER, '')

    SELECT @CHARGEGROUP = ISNULL(HAN.[ChargeGroup], '')
      FROM [dbo].[Handlers] AS HAN
     WHERE HAN.[CODE] = @HANDLER

    IF @MATTER <> '~'
    BEGIN
        -- Check if the matter code contains a '/'
        -- If it doesn't then it's probably because the matter is blank
        SET @MATTER = ISNULL(NULLIF(@MATTER, ''), '/')

        IF NOT EXISTS(SELECT * FROM [dbo].[matters] WHERE [Code] = @MATTER)
            SET @RETURN = @RETURN | 1 -- Matter doesn't exist

        IF EXISTS(SELECT * FROM [dbo].[matters] WHERE [Code] = @MATTER AND [Closed] = 'Y')
            SET @RETURN = @RETURN | 2 -- Matter is closed

        SET @CHECK = ISNULL((SELECT CONVERT(BIT, ISNULL([KeyValue], 'False'))
                               FROM [dbo].[Settings]
                              WHERE [KeyName] = 'ChargeOutRateCheck'), 0)

        IF @CHECK = 1
        BEGIN
            /*
                Below is where the charge out rate indicators are handled. There's a hierarchy
                for how a user's rate is calculated and that same hierarchy will be applied here.
                The handler may be in a charge group and this is treated the same as a handler code.

                                  No                          No
            Matter rate active? +-----> Client rate active? +-----> User can't post
                    +                           +
                    |                           |
                    | Yes                       | Yes
                    |                           |
                    v            No             v            No
            Is handler in list? +--+    Is handler in list? +--+
                    +              |            +              |
                    |              |            |              |
                    | Yes          |            | Yes          |
                    |              |            |              |
                    v              |            v              |
              User can post        |      User can post        |
                                   |                           |
                                   v                           v
                            User can't post             User can't post
            */

            SELECT @FLAG = @FLAG |
                           CASE WHEN ISNULL(MAT.[ChargeOutRateInd], 'N') = 'Y'
                                     THEN 1
                                ELSE 0 END
              FROM [dbo].[matters] AS MAT
             WHERE MAT.[Code] = @MATTER

            SELECT @FLAG = @FLAG |
                           CASE WHEN ISNULL(CNT.[ChargeOutRateInd], 'N') = 'Y'
                                     THEN 2
                                ELSE 0 END
              FROM [dbo].[Contacts] AS CNT
             WHERE CNT.[Code] = SUBSTRING(@MATTER, 1, CHARINDEX('/', @MATTER) - 1)

            IF EXISTS
              (SELECT *
                 FROM [dbo].[MatterChargeOutRates] AS MCR
                WHERE MCR.[MatterCode] = @MATTER
                 AND (MCR.[FeCode] = @HANDLER
                   OR MCR.[FeCode] = @CHARGEGROUP))
              BEGIN
                SET @FLAG = @FLAG | 4
              END

            IF EXISTS
              (SELECT *
                 FROM [dbo].[ClientChargeOutRates] AS CCR
                WHERE CCR.[ClientCode] = SUBSTRING(@MATTER, 1, CHARINDEX('/', @MATTER) - 1)
                 AND (CCR.[FeCode] = @HANDLER
                   OR CCR.[FeCode] = @CHARGEGROUP))
              BEGIN
                SET @FLAG = @FLAG | 8
              END

            -- If matter list is enabled and user is not in the list
            IF @FLAG & 1 > 0 AND @FLAG & 4 = 0
                SET @RETURN = @RETURN | 4

            -- If client list is enabled, matter list is disabled and user is not in the list
            IF @FLAG & 2 > 0 AND @FLAG & 8 = 0 AND @FLAG & 1 = 0
                SET @RETURN = @RETURN | 8
        END
    END

    IF @RECORDID IS NOT NULL
    BEGIN
        IF (SELECT TOP 1 CASE WHEN TDB.[Matter] = '~'
                                   THEN ISNULL(TDB.[NCCCode], '')
                              ELSE ISNULL(TDB.[Task], '')
                         END
              FROM [dbo].[TimeDayBook] AS TDB
             WHERE TDB.[RecordID] = @RECORDID) = ''
            SET @RETURN = @RETURN | 16
    END

    -- Check if AML is required and if the contact is approved
    IF RTRIM(ISNULL(@MATTER, '')) NOT IN ('', '~', '/')
      BEGIN
        IF ISNULL((SELECT TOP 1 [KeyValue] FROM [dbo].[Settings] WHERE [KeyName] = 'AMLRequiredForTime'), '') = '1' AND
           ISNULL((SELECT TOP 1 CONVERT(VARCHAR(10), ISNULL(CNT.[Approved], 0))
                     FROM [dbo].[Contacts] AS CNT
                          INNER JOIN [dbo].[matters] AS MAT
                                  ON CNT.[Code] = MAT.[ClientCode]
                    WHERE MAT.[Code] = @MATTER
                      AND ISNULL(CNT.[Approved], 0) = 1), '') <> '1'
        BEGIN
          SELECT @RETURN = @RETURN | 32
        END
      END

    RETURN @RETURN
END

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

CREATE PROCEDURE
       [dbo].[KEYHM_GetAdestRate]
      (@MatterCode VARCHAR(20),
       @ChargeCode VARCHAR(3))
AS
/*******************************************************************************************************
* This procedure is used to get default value from charging matrix for SAM4							   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetAdestRate]											           *
* Copied from			: [dbo].[ky_NETGetAdestRate]										           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-05-23	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN

DECLARE @ChargeArrangement VARCHAR(3)
DECLARE @MatDebt DECIMAL(18, 2)
DECLARE @MatRate DECIMAL(13, 2)

SELECT @ChargeArrangement = RTRIM(ISNULL([MAT].[ChargeArrangement], ISNULL([CNT].[ChargeArrangement], ''))),
       @MatDebt = ISNULL([MAT].[OriginalDebt], 0) + ISNULL([MAT].[DebtInterest], 0) - ISNULL([MAT].[DebtCollected], 0)
  FROM [dbo].[matters] [MAT]
       LEFT OUTER JOIN [dbo].[Contacts] [CNT]
                    ON [CNT].[Code] = [MAT].[ClientCode]
 WHERE [MAT].[Code] = @MatterCode

SELECT @MatRate = CASE WHEN [CMX].[BAND1LIMIT] >= @MatDebt
                            THEN [CMX].[BAND1RATE]
                       WHEN [CMX].[BAND2LIMIT] >= @MatDebt
                            THEN [CMX].[BAND2RATE]
                       WHEN [CMX].[BAND3LIMIT] >= @MatDebt
                            THEN [CMX].[BAND3RATE]
                       WHEN [CMX].[BAND4LIMIT] >= @MatDebt
                            THEN [CMX].[BAND4RATE]
                       WHEN [CMX].[BAND5LIMIT] >= @MatDebt
                            THEN [CMX].[BAND5RATE]
                       WHEN [CMX].[BAND6LIMIT] >= @MatDebt
                            THEN [CMX].[BAND6RATE]
                       WHEN [CMX].[BAND7LIMIT] >= @MatDebt
                            THEN [CMX].[BAND7RATE]
                       ELSE [CMX].[BAND8RATE] END
  FROM [dbo].[ChargingMatrix] [CMX]
 WHERE [CMX].[ARRANGEMENTCODE] = @ChargeArrangement
   AND [CMX].[CHARGECODE] = @ChargeCode

SELECT ISNULL(@MatRate, CONVERT(DECIMAL(13, 2), 0)) AS Rate

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

Create Procedure
       [dbo].[KEYHM_GetAzureDATInfo]
      (@TrackReference INT,
       @Version        INT)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KEYHM_GetAzureDATInfo]                                                                           *
 *                                                                                                           *
 * 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                                                                                                                        *
 *************************************************************************************************************/
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'KEYHM_GetCaseAssociateContacts', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetCaseAssociateContacts]
END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetCaseAssociateContacts]  
(  
 @NameCode VARCHAR(20)  
)  
AS    
/*******************************************************************************************************
* This sp is used to Fetch Data for Case Associate Contacts WebApi				                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetCaseAssociateContacts]						  				   *
* Copied from			: [dbo].[ky_NETFetchCaseAssociateEditLoadData]								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/    
BEGIN    
  DECLARE @AssCont VARCHAR(100)    
    
  SET NOCOUNT ON    
    
    
  SELECT RTRIM(ISNULL(CAC.[NAMECODE], ''))                                 AS [NameCode],    
         RTRIM(ISNULL(CAST(CAC.[KEYID] AS VARCHAR(20)), ''))               AS [KeyId],    
         RTRIM(ISNULL(CAC.[NAME], ''))                                     AS [Name],    
         RTRIM(ISNULL(CAC.[SALUTATION], ''))                               AS [Salutation],    
         RTRIM(ISNULL(CAC.[JOBTITLE], ''))                                 AS [JobTitle],    
         RTRIM(ISNULL(CAC.[ADDRESS], ''))                                  AS [Address],    
         RTRIM(ISNULL(CAC.[PHONE], ''))                                    AS [Phone],    
         RTRIM(ISNULL(CAC.[FAX], ''))                                      AS [Fax],    
         RTRIM(ISNULL(CAC.[MOBILE], ''))                                   AS [Mobile],    
         RTRIM(ISNULL(CAC.[EMAIL], ''))                                    AS [Email],    
         RTRIM(ISNULL(CAC.[RELATIONSHIP], ''))                             AS [Relationship],    
         RTRIM(ISNULL(CAC.[NOTES], ''))                                    AS [Notes]    
    FROM [dbo].[CaseAssociatesContacts] CAC    
   WHERE CAC.[NAMECODE] = @NameCode    
    
    
  SET NOCOUNT OFF    
END    
GO
IF OBJECT_ID(N'KEYHM_GetCaseAssociates', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetCaseAssociates]
END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetCaseAssociates]
(  
 @CaseCode    VARCHAR(20),    
 @Retired     VARCHAR(1) = 'N',
 @EmailSearch NVARCHAR(500) = NULL
)  
AS    
/*******************************************************************************************************
* This procedure is used to return Case Associate from WebApi					                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetCaseAssociates]							  				   *
* Copied from			: [dbo].[ky_NETCaseAssociateLoadMainGrid]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
* 2019-07-12    Ramesh K          Modified to implement the email search for OWA                       *
 *******************************************************************************************************/   
BEGIN    
    
SET NOCOUNT ON    

	SET @EmailSearch = LTRIM(RTRIM(@EmailSearch));

	IF @EmailSearch = ''
	BEGIN
		SET @EmailSearch = NULL;
	END
	
    
	  SELECT CCN.[CASECODE]								AS [CaseCode],  
			 RTRIM(CCN.[CONTYPE])						AS [ConType],    
			 CCN.[CONNUM]								AS [ConNum],  
			 CCN.[NAMECODE]								AS [CaseContactsNameCode],  
			 CCN.[SOLCODE]								AS [CaseContactsSolCode],  
			 CCN.[SOLREF]								AS [CaseContactsSolRef],  
			 CCN.[INSCODE]								AS [CaseContactsInsCode],  
			 CCN.[ASSIGNEDCONTACT]						AS [AssignedContact],  
			 CCN.[CONNUM]								AS [CaseContactsSeq],  
			 CASE WHEN (RTRIM(ISNULL(CCN.[ForCopy],'0')) = '1'  OR  RTRIM(ISNULL(CCN.[ForCopy],'0')) = 'Y' )  
				  THEN 'True'    
				  ELSE 'False'  
			 END										AS [CaseContactsForCopy],  
			 ISNULL(CCN.[IsAssociateOtherSide],'False') AS [CaseContactsIsAssociateOtherSide],    
			 ISNULL(CCN.Retired,'N')					AS [CaseContactsRetired],        
			 CAC.[NAMECODE]								AS [CaseAssociatesContactsNameCode],  
			 CAC.[KEYID]								AS [CaseAssociatesContactsKeyId],  
			 CAC.[NAME]									AS [CaseAssociatesContactsName],  
			 CAC.[PHONE]								AS [CaseAssociatesContactsPhone],  
			 CAC.[EMAIL]								AS [CaseAssociatesContactsEmail1],    
			 CAC.[NAME]									AS [AssignedContactName],    
			 CAC.[PHONE]								AS [AssignedContactPhone],           							         
			 AST.[CODE]									AS [AssociateTypeCode],  
			 AST.[DESCRIPTION]							AS [AssociateTypeDescription],           							         
			 CAN.[CODE]									AS [CaseAssociateCode],  
			 CAN.[TYPE]									AS [CaseAssociateType],  
			 CAN.[NAME]									AS [CaseAssociateName],  
			 CAN.[COMPANY]								AS [CaseAssociateCompany],  
			 CAN.[ADDRESS]								AS [CaseAssociateAddress],  
			 CAN.[PHONENO]								AS [CaseAssociatePhoneNo],  
			 CAN.[MOBILENO]								AS [CaseAssociateMonileNo],  
			 CAN.[EMAIL]								AS [CaseAssociateEmail],  
			 CAN.[SEARCH]								AS [CaseAssociateSearch],  
			 CAN.[CONTACTNO]							AS [CaseAssociateContactNo],  
			 CAN.[SALUTATION],							         
			 CASE WHEN RTRIM(ISNULL(CAN.[COMPANY],'')) <> ''    
				  THEN RTRIM(CAN.[Name]) + ' ('+ RTRIM(CAN.[COMPANY]) +')'    
				  ELSE RTRIM(CAN.[Name]) 
			 END										AS [CaseAssociateNameNCompany]  
		FROM [dbo].[CaseContacts] CCN    
			 LEFT OUTER JOIN [dbo].[CaseAssociatesContacts] CAC    
						  ON CAC.[KEYID] = CCN.[ASSIGNEDCONTACT]    
			 LEFT OUTER JOIN [dbo].[AssociateTypes] AST    
						  ON AST.[CODE] = CCN.[CONTYPE]    
			 LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CAN    
						  ON CAN.[CODE] = CCN.[NAMECODE]    
	   WHERE UPPER(CCN.[CASECODE]) = UPPER(@CaseCode)    
		 AND LEN(ISNULL(CCN.[NAMECODE],'')) >0    
		 AND CCN.[NAMECODE] <> 'N/A'    
		 AND LEN(ISNULL(CAN.[NAME],''))>0    
		 AND CAN.[NAME] <> 'N/A'    
		 AND (@RETIRED = 'Y'    
			  OR ISNULL(CCN.Retired, 'N') <> 'Y')
		 AND 
			(
				@EmailSearch IS NULL
				OR
				CAN.[EMAIL] LIKE '%' + @EmailSearch + '%'				
			)
	ORDER BY CCN.[CASECODE],    
			 CCN.[CONTYPE],    
			 CCN.[CONNUM]    
    
SET NOCOUNT OFF    
END    
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_GetCaseFolders'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetCaseFolders]
  END
GO

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

/*******************************************************************************************************
* Returns the default location for any documents stored against a case/matter						   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetCaseFolders]												   *
* Copied from			: [dbo].[ky_NETGetCaseFolders]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

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 EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_GetCaseWorkType'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetCaseWorkType]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_GetCaseWorkType]
      (@MatterCode       VARCHAR(20))
AS
/*******************************************************************************************************
* Gets the Work Type to default to in the Case Diary for this matter                                   *
* - will get CSWKTCODE if this refers to an existing Work Type                                         *
* - if that fails it will get the GEN code if it exists and it isn't retired                           *
* - finally, as a last resort, if both the above fail it will get the first available non-retired one  *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetCaseWorkType]												   *
* Copied from			: [dbo].[ky_NETSPGetCaseWorkType]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 
BEGIN

DECLARE @WKCODE VARCHAR(4)
DECLARE @WKDESC CHAR (40)
DECLARE @Retired CHAR(1)

SELECT @WKCODE = RTRIM(ISNULL([TMP].[WKCODE], '')),
       @WKDESC = RTRIM(ISNULL([TMP].[WKDESC], '')),
       @Retired = CASE WHEN ISNULL([TMP].[Retired], 'N') = 'Y'
                            THEN 'Y'
                       ELSE 'N' END
	FROM [dbo].[CaseMaster] [CSM]
       INNER JOIN [dbo].[Templates] [TMP]
               ON [TMP].[WKCODE] = [CSM].[CSWKTCODE]
	WHERE [CSM].[CSCODE] = @MatterCode

IF NOT @WKCODE IS NULL
  BEGIN
    SELECT @WKCODE  AS [CsWktCode],
	       @WKDESC  AS [CsWktDesc],
           @Retired AS [Retired]
    RETURN
  END

SELECT @WKCODE = RTRIM(ISNULL([TMP].[WKCODE], '')),
       @WKDESC = RTRIM(ISNULL([TMP].[WKDESC], '')),
       @Retired = CASE WHEN ISNULL([TMP].[Retired], 'N') = 'Y'
                            THEN 'Y'
                       ELSE 'N' END
  FROM [dbo].[Templates] [TMP]
  WHERE [TMP].[WKCODE] = 'GEN'
   AND ISNULL([TMP].[Retired], 'N') <> 'Y'

IF NOT @WKCODE IS NULL
  BEGIN
    SELECT @WKCODE  AS [CsWktCode],
		   @WKDESC  AS [CsWktDesc],
           @Retired AS [Retired]
    RETURN
  END

  SELECT TOP 1
         @WKCODE = RTRIM(ISNULL([TMP].[WKCODE], '')),
		 @WKDESC = RTRIM(ISNULL([TMP].[WKDESC], '')),
         @Retired = CASE WHEN ISNULL([TMP].[Retired], 'N') = 'Y'
                              THEN 'Y'
                         ELSE 'N' END
    FROM [dbo].[Templates] [TMP]
    WHERE [TMP].[WKCODE] = 'GEN'
     AND ISNULL([TMP].[Retired], 'N') <> 'Y'
	ORDER BY [TMP].[WKCODE]

IF NOT @WKCODE IS NULL
  BEGIN
    SELECT @WKCODE  AS [CsWktCode],
	       @WKDESC  AS [CsWktDesc],
           @Retired AS [Retired]
    RETURN
  END

SELECT CONVERT(VARCHAR(4), '')  AS [CsWktCode],
       CONVERT(CHAR(40), '') AS [CsWktDesc],
       CONVERT(CHAR(1), 'Y')    AS [Retired]

END

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

CREATE PROCEDURE [dbo].[KEYHM_GETChargeRate]
      (@HandlerCode  VARCHAR(10),
       @Matter       VARCHAR(20),
       @TaskCode     VARCHAR(6)      = '')
AS
/*******************************************************************************************************
* Get rate for posting time based on Handler, Matter and Task Code.									   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GETChargeRate]												   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
	DECLARE @TimeorCharge VARCHAR(1)
	SET @TimeorCharge = (
		SELECT 
			TOP 1 TimeOrCharge 
		FROM 
			TimeDayBook 
		WHERE 
			Matter = @Matter or
			FeeEarn = @HandlerCode 
		ORDER BY 1 DESC
	)
	
SELECT CASE WHEN ISNULL(MAT.[ChargeOutRateInd], 'N') = 'Y'
                 THEN CASE WHEN MHCG.[Rate] IS NULL
                                THEN ISNULL(MCR.[Rate], 0)
                           WHEN MHCG.[Rate] IS NOT NULL
                            AND MCR.[Rate] IS NOT NULL
                                THEN ISNULL(MCR.[Rate], 0)
                           ELSE MHCG.[Rate] END
            WHEN ISNULL(CON.[ChargeOutRateInd], 'N') = 'Y'
                 THEN CASE WHEN CHCG.[Rate] IS NULL
                                THEN ISNULL(CCR.[Rate], 0)
                           WHEN CHCG.[Rate] IS NOT NULL
                            AND CCR.[Rate] IS NOT NULL
                                THEN ISNULL(CCR.[Rate], 0)
                           ELSE CHCG.[Rate] END
            ELSE ISNULL(FEP.[ChargeFct], 1.00) * (CASE WHEN FER.[RATE] = 0 THEN ISNULL(H.[RATE], 0) ELSE FER.[RATE] END) END AS [Rate], 
			ISNULL(@TimeorCharge,'T') AS [TimeorCharge]
  FROM [dbo].[Matters] MAT
       INNER JOIN [dbo].[Contacts] CON
               ON CON.[Code] = MAT.[ClientCode]
       OUTER APPLY (SELECT MCOR.[Rate]
                      FROM [dbo].[Handlers] HS
                           INNER JOIN [dbo].[HandlerChargeGroups] HCG
                                   ON HS.[ChargeGroup] = HCG.[Code]
                           INNER JOIN [dbo].[MatterChargeOutRates] MCOR
                                   ON MCOR.[FeCode] = HCG.[Code]
                                  AND MCOR.[MatterCode] = @Matter
                     WHERE HS.[CODE] = @HandlerCode) MHCG
       OUTER APPLY (SELECT MCOR.[Rate]
                      FROM [dbo].[Handlers] HS
                           INNER JOIN [dbo].[HandlerChargeGroups] HCG
                                   ON HS.[ChargeGroup] = HCG.[Code]
                           INNER JOIN [dbo].[ClientChargeOutRates]  MCOR
                                   ON MCOR.[FeCode] = HCG.[Code]
                                  AND MCOR.[ClientCode] = MAT.[ClientCode]
                     WHERE HS.[CODE] = @HandlerCode) CHCG
       OUTER APPLY (SELECT MCOR.[Rate]
                      FROM [dbo].[MatterChargeOutRates] MCOR
                     WHERE MCOR.[FeCode] = @HandlerCode
                       AND MCOR.[MatterCode] = @Matter) MCR
       OUTER APPLY (SELECT CCOR.[Rate]
                      FROM [dbo].[ClientChargeOutRates] CCOR
                     WHERE CCOR.[FeCode] = @HandlerCode
                       AND CCOR.[ClientCode] = MAT.[CLIENTCODE]) CCR
       CROSS APPLY (SELECT CASE ISNULL(MAT.[ChargeLevel], 3)
                                WHEN 1 THEN ISNULL(HDL.[RATE1], 0)
                                WHEN 2 THEN ISNULL(HDL.[RATE2], 0)
                                WHEN 3 THEN ISNULL(HDL.[RATE3], 0)
                                WHEN 4 THEN ISNULL(HDL.[RATE4], 0)
                                WHEN 5 THEN ISNULL(HDL.[RATE5], 0)
ELSE ISNULL(HDL.[RATE], 0) END AS [RATE]
                      FROM [dbo].[Handlers] HDL
                     WHERE HDL.[CODE] = @HandlerCode) FER
       OUTER APPLY (SELECT CASE ISNULL(TAC.[ChargeLevel], 'C')
                                WHEN 'A' THEN 0.33
                                WHEN 'B' THEN 0.67
                                WHEN 'C' THEN 1.00
                                WHEN 'D' THEN 1.33
                                WHEN 'E' THEN 1.67
                                ELSE 1.00 END AS [ChargeFct]
                      FROM [dbo].[TasksCodes] TAC
                     WHERE TAC.[CODE] = @TaskCode) FEP
       LEFT OUTER JOIN [dbo].[Handlers] H
                    ON H.[CODE] = @HandlerCode
 WHERE MAT.[Code] = @Matter

END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_GetDocumentsIM'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetDocumentsIM]
  END
GO
CREATE PROCEDURE
       [dbo].[KEYHM_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)     = '',
	   @LoggedInHandler		VARCHAR(10)		= NULL,
	   @ColumnNames         VARCHAR(50)		= '',
	   @FilterValues        VARCHAR(4000)	= ''
	   )
AS
/************************************************************************************************************************
 *                                                                                                                      *
 * [dbo].[KEYHM_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-12-04   Kowshik.R         Mobile documents page special character search and.docx file type issue is fixed                                                    *
 ************************************************************************************************************************/
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 
			KEYHM_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 ))
		)

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
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN 
			([DA].FILEPATH 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 ))
		)

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],[DAS].[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
 INNER JOIN dbo.[DiaryAttachmentSelector] [DAS] ON  [DAS].[ActionID] = [DA].[DiaryID] and [DAS].CASECODE = [DA].CASECODE and [DAS].[TrackReference]=[DA].[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 [DIA].[CaseCode] = @matter
		AND
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN 
			([DA].FILEPATH LIKE '%' + @SearchText + '%')
			OR
			([DA].[DATEENTERED] LIKE '%' + @SearchText + '%')
			OR
			([DA].[TYPE] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DocClass] LIKE '%' + @SearchText + '%')
			OR
			([DA].[DOCUMENT] LIKE '%' + @SearchText + '%')
			THEN 1
			ELSE 0
			END = 1
		)
		
		AND
		(
			ISNULL(@FileType, '') = ''
			OR ([DA].[TYPE] IN (select FileType from @FileTypeList ))
		)
 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 #DiaryTables
  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]
   
   

 --  OFFSET @PageSize * (@PageNo - 1) ROWS
 --  FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);
END
ELSE IF ISNULL(@DocFolderID, 0) <> 0
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
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN
				([DA].FILEPATH 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 ))
		)

	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],[DAS].[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]
 INNER JOIN dbo.DiaryAttachmentSelector [DAS] on [DA].[DiaryID]=[DAS].[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
		(
		CASE WHEN @SearchText = '' THEN 1
			 WHEN
				([DA].FILEPATH 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 ))
		)
 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
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
		(
		CASE WHEN @SearchText = '' THEN 1 
			 WHEN			
			([DA].FILEPATH 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 ))
		)

  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
		(
		CASE WHEN @SearchText = '' THEN 1 
			 WHEN			
			([DA].FILEPATH 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 ))
		)
 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.KEYHM_FNConvertUTCDateToTargetTimeZone([RES].[DiaryDate], @LoggedInHandler), 23) AS [DATE],
       ISNULL([RES].[ActionID], 0) AS [ACTIONID],
       CONVERT(VARCHAR(15), dbo.KEYHM_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],
       CONVERT(VARCHAR(15),dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([DiaryDate], @LoggedInHandler), 23)  AS [DATE],
       [ACTIONID],
       CONVERT(VARCHAR(15), dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([DocumentDate], @LoggedInHandler), 23) AS [DocumentDate],
       [IMDocID],
       [IMClass],
       [DocumentClassDescription],
       [DocClass],
       [Document],
       [TRACKREFERENCE],
       [TYPE],
       [Attachments],
       [EMAIL],
       [EMAILFROM] AS [EMAILADDRESS],
       [EMAILTO] AS [ADDRESSTO],
       [EMAILSENT],
       [SUBJECT],
       [ShortText],
       [NAME],
       [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 * FROM [dbo].[KEYHM_FN_GetDocFolders](@matter, @DocFolderID, 1, 1) WHERE parent <> -1
    END
  ELSE
    BEGIN
      SELECT TOP 0
             CONVERT(INT, 0) AS [seq],
             CONVERT(INT, 0) AS [id],
             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 EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_GetDormantMatters'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetDormantMatters]
  END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetDormantMatters] (
       @FECODE VARCHAR(20))
AS
/*******************************************************************************************************
* Gets a list of dormant matters. Return value is set to the number of matters.						   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetDormantMatters]		                                       *
* Copied from			: [dbo].[ky_NETGetDormantMatters]			                                   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-16	Vinodhan K		Created                                                                *
 *******************************************************************************************************/ 
BEGIN
    SET NOCOUNT ON
    
    DECLARE @SQL NVARCHAR(MAX)

    SET @SQL = N'
    DECLARE @LastActionMonth INT
    DECLARE @GETDATE         DATETIME

    SELECT @LastActionMonth = [KeyValue]
      FROM [dbo].[Settings]
     WHERE [KeyName] = ''LastActionMonth''

    SET @LastActionMonth = ISNULL(@LastActionMonth, 6)
    SET @GETDATE = GETDATE()

    SELECT MAT.[Code],
           MAX(ISNULL(LST.[Date], MAT.[Started])) AS [LastActivity]
      FROM [dbo].[matters] AS MAT
           LEFT OUTER JOIN (SELECT TIE.[Matter],
                                   MAX(TIE.[DATE]) AS [Date]
                              FROM [dbo].[TimeEntry] AS TIE
                                   GROUP BY TIE.[Matter]
                            UNION
                            SELECT DIA.[CASECODE],
                                   MAX(DIA.[DATE])
                              FROM [dbo].[diary] AS DIA
                                   GROUP BY DIA.[CASECODE]
                            UNION
                            SELECT UND.[MATTER],
                                   MAX(CASE WHEN UND.[DISCHARGEDATE] > UND.[UNDDATE]
                                             AND UND.[DISCHARGEDATE] > UND.[DATE]
                                                 THEN UND.[DISCHARGEDATE]
                                            WHEN UND.[UNDDATE] > UND.[DISCHARGEDATE]
                                             AND UND.[UNDDATE] > UND.[DATE]
                                                 THEN UND.[UNDDATE]
                                            ELSE UND.[DATE] END)
                              FROM [dbo].Undertakings AS UND
                                   GROUP BY UND.[MATTER]'

    IF [dbo].[ISSAM4]() = 0
    BEGIN
        SET @SQL = @SQL + N'
                            UNION
                            SELECT MTL.[MATTER],
                                   MAX(MTL.[DATE])
                              FROM [dbo].[MatterLedger] AS MTL
                                   GROUP BY MTL.[MATTER]'
    END
    ELSE
    BEGIN
        SET @SQL = @SQL + N'
                            UNION
                            SELECT TRN.[MatterCode],
                                   MAX(TRN.[TransDate])
                              FROM [dbo].[Transactions] AS TRN
                                   GROUP BY TRN.[MatterCode]'
    END

    SET @SQL = @SQL + N') AS LST
                        ON LST.[Matter] = MAT.[Code]
     WHERE MAT.[Closed] <> ''Y''
       AND (@FECODE IS NULL
         OR MAT.[FECode] = @FECODE)
            GROUP BY MAT.[Code],
                     MAT.[Started]
    HAVING DATEDIFF(MONTH, MAX(ISNULL(LST.[Date], MAT.[Started])), @GETDATE) > @LastActionMonth'

    EXEC sp_executesql @SQL, N'@FECODE VARCHAR(20)', @FECODE = @FECODE

    RETURN @@ROWCOUNT

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

CREATE PROCEDURE [dbo].[KEYHM_GetFileData] (@FilePath NVARCHAR(MAX))
AS
/*******************************************************************************************************
*																				                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetFileData]										  			   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
* 2019-12-26    Arun V            Have included KAAS_GetUNCPathFromFile function to convert file path  *
*                                 into UNC                                                             *
 *******************************************************************************************************/ 
BEGIN
 DECLARE @NCOMMAND NVARCHAR(MAX)
 DECLARE @result INT
 DECLARE @UNCFilePath NVARCHAR(256)

 SET @FilePath = REPLACE(@FilePath, '''', '''''');

  SET @UNCFilePath = (select dbo.KEYHM_FN_GetUNCPathFromFile(@FilePath))

 SET @NCOMMAND = 'EXEC Master.dbo.xp_fileexist ''' + @UNCFilePath + ''', @result OUTPUT PRINT @result'
 EXECUTE sp_executesql @NCOMMAND, N'@result INT OUTPUT', @result = @result OUTPUT

IF (@result = 1)
 BEGIN
  SET @NCOMMAND = 'DECLARE @file AS VARBINARY(MAX);
				    SELECT @file = CAST(bulkcolumn AS VARBINARY(MAX)) 
				      FROM OPENROWSET (BULK ''' + @UNCFilePath + ''', SINGLE_BLOB) AS x;
				    SELECT @file AS FileData'
  EXECUTE sp_executesql @NCOMMAND
 END
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_GetFileName'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetFileName]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_GetFileName]
       (@TrackReference    INT)
AS

/*******************************************************************************************************
* Fetches the file path using Track Reference No.                                                      *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetFileName]											           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2020-06-19	Arun V		Created                                                                *
********************************************************************************************************/

BEGIN
    SELECT
	    [Document]
	FROM
	    [DiaryAttachments]
	WHERE
	    [TrackReference] = @TrackReference
END
GO

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

CREATE PROCEDURE
       [dbo].[KEYHM_GetFilePath]
       (@TrackReference    INT)
AS

/*******************************************************************************************************
* Fetches the file path using Track Reference No.                                                      *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetFilePath]											           *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-09-26	Vinodhan K		Created                                                                *
********************************************************************************************************/

BEGIN
    SELECT
	    [FilePath]
	FROM
	    [DiaryAttachments]
	WHERE
	    [TrackReference] = @TrackReference
END

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

CREATE PROCEDURE [dbo].[KEYHM_GetHandlerDefaultTask] (@Code VARCHAR(15))
AS
/*******************************************************************************************************
*																				                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetHandlerDefaultTask]										   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
	SELECT RTRIM(DEFAULTTASK) AS [DefaultTask]
	  FROM Handlers
	 WHERE RETIRED <> 'Y'
		   AND CODE = @Code
END
GO
IF OBJECT_ID(N'KEYHM_GetHandlerLogon', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetHandlerLogon]
END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetHandlerLogon]    
      (@HandlerCode VARCHAR(10))    
AS    
/*******************************************************************************************************
*																				                       *
* Stored Procedure Name : [dbo].[KEYHM_GetHandlerLogon]												   *
* Copied from			: [dbo].[ky_NETGetHandlerLogon]												   *
*							                                                                           * 
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
* 2019-09-04    Arun V            Have included UserDefaultpageSize setting                            *
* 2019-09-05    Arun V            Have included UserFavourites setting                                 *
* 2019-09-12    Vinodhan K        ISNULL checked for @UserFavourites                                   *
* 2019-09-18    Vinodhan K        Department of the user added                                         *
* 2019-12-12    Prabhu V          DefaultVAT Code added                                                *
* 2020-02-17    Ganapathy T	      Day Book progress value added                                        *
* 2020-03-09    Rajesh  	      kaas_side_panel_state value added                                    *
 *******************************************************************************************************/ 
BEGIN    
DECLARE @PasswordExpiryDate INT    
SET @PasswordExpiryDate = (    
                            SELECT ISNULL(KeyValue,60)    
                              FROM Settings    
                             WHERE [KeyName] = 'PasswordExpiryDays')  
							 
							 
DECLARE @UserDefaultPageSize INT    
SET @UserDefaultPageSize = (    
                            SELECT [Value]    
                              FROM UserSettings    
                             WHERE [Key] = 'UserDefaultPageSize' and Handler = @HandlerCode)
							 
							 
DECLARE @UserFavourites VARCHAR(300)    
SET @UserFavourites = (    
                            SELECT [Value]  
                              FROM UserSettings    
                             WHERE [Key] = 'UserFavourites' and Handler = @HandlerCode)    

DECLARE @TimerSettings VARCHAR(300)    
SET @TimerSettings = (    
                            SELECT [Value]  
                              FROM UserSettings    
                             WHERE [Key] = 'TimerSettings' and Handler = @HandlerCode)    

DECLARE @DefaultVATCode VARCHAR(2)

SET @DefaultVATCode = (SELECT TOP 1 DEFAULTVAT FROM CONTROL)    
    
DECLARE @COMMAND VARCHAR(MAX)    
    
SET @COMMAND = 'SELECT HLO.[HANDLER]								AS [Handler],
					   RTRIM(ISNULL(HAN.[NAME], ''''))				AS [Name],
					   RTRIM(ISNULL(HAN.[Email], ''''))				AS [Email],  
					   REPLACE(ISNULL(RETIRED,''N''),'' '',''N'')   AS [Retired],    
					   CASE
					   	WHEN RTRIM(ISNULL(HAN.[TYPE], '''')) = ''P''    
					   		THEN CONVERT(BIT, 1)    
					   	WHEN RTRIM(ISNULL(HAN.[CODE], '''')) = ''ADM''    
					   		THEN CONVERT(BIT, 1)    
					   	ELSE CONVERT(BIT, 0)
					   END AS [IsPartner],    
					   ISNULL(GM.[BitWiseID], [dbo].[KEYHM_FN_GetOldPermissions](RTRIM(ISNULL(HAN.[CODE], '''')))) AS [BitWiseId],
					   UPPER(ISNULL(HAN.AutoLaunchTimer, ''N''))	AS [AutoLaunchTimer],
					   ISNULL([HAN].[TEAM], '''')                   AS [Team],
					   ISNULL([HAN].[Dept], '''')                   AS [Department]'
  
SET @COMMAND = @COMMAND + ',    
						 HLO.[Date] + '+ CONVERT(VARCHAR(5),ISNULL(@PasswordExpiryDate,'60')) +' AS [Date],    
						 ISNULL(HAN.[TYPE], '''') AS [Type],
						 ' + CONVERT(VARCHAR(5),ISNULL(@UserDefaultPageSize,10)) + ' as UserDefaultPageSize ,
						 ''' + CONVERT(VARCHAR(300), ISNULL(@UserFavourites, '')) + ''' as UserFavourites ,
						 ''' + CONVERT(VARCHAR(500), ISNULL(@TimerSettings, '')) + ''' as TimerSettings ,
						 ''' + CONVERT(VARCHAR(2), ISNULL(@DefaultVATCode, '')) + ''' as DefaultVAT 
					FROM [dbo].[Handlers] HAN    
						 LEFT OUTER JOIN [dbo].[HandlerNETLogons] HLO    
						 	ON HLO.[HANDLER] = HAN.[CODE]    
						 LEFT OUTER JOIN [dbo].[HandlerNETGroupMembership] GM    
						 	ON GM.[HANDLER] = HAN.[CODE]    
				   WHERE HAN.[CODE] = ''' + Replace(@HandlerCode, '''', '''''') + ''''    
EXEC (@COMMAND)  


DECLARE @DayBookValue INT

SELECT
	@DayBookValue = ISNULL(SUM([TDB].[Time]), 0)
FROM
	[dbo].[Timedaybook] [TDB] WITH (NOLOCK)
WHERE
	[TDB].[FeeEarn] = @HandlerCode

SELECT @DayBookValue AS [DayBookValue]

DECLARE @MaxDayBookValue DECIMAL(10,2) = 7.5

IF EXISTS(SELECT TOP 1 1 FROM [dbo].[UserSettings] WHERE [Handler] = @HandlerCode  AND [Key] = 'TimeDayBookLimit')
BEGIN
	SELECT @MaxDayBookValue = Value FROM [dbo].[UserSettings] WHERE [Handler] = @HandlerCode  AND [Key] = 'TimeDayBookLimit'
END

SELECT 
	CASE WHEN (ISNULL(@MaxDayBookValue,0) = 0) THEN 7.5 * 60 ELSE @MaxDayBookValue * 60 END AS [MaxDayBookValue]
 SELECT  Value  AS SidePanelState FROM [dbo].[UserSettings]  WHERE [Handler] = @HandlerCode  AND [Key] = 'kaas_side_panel_state';
   
END  
GO
IF OBJECT_ID(N'[KEYHM_GETHandlerRate]',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_GETHandlerRate]
GO
CREATE PROC [KEYHM_GETHandlerRate] (@HandlerCode  VARCHAR(10)  )
AS  
/*******************************************************************************************************
* Used to Get new Handler Rate. 																	   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GETHandlerRate]												   *
* Copied from			: [dbo].[ky_NETGETHandlerRate]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN  
	SELECT 
		ISNULL(RATE,0) AS Rate 
	FROM 
		Handlers 
	WHERE 
		CODE=@HandlerCode
END
GO


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

CREATE PROCEDURE [dbo].[KEYHM_GetHandlersResource] (
	@CODE			VARCHAR(15),
	@SearchText		VARCHAR(4000)	= '',
	@PageNumber		INT				= NULL,
	@PageSize		INt				= NULL)
AS
/*************************************************************************************************************************
* To fetch the handler resource list available from the database excluding the currently logged in user                  *
*                                                                                                                        *
* Stored Procedure Name : [dbo].[KEYHM_GetHandlersResource]											                     *
* Copied from			: [dbo].[ky_NETGetHandlersResource]											                     *
*                                                                                                                        *
* Modification History:                                                                                                  *
* 2019-04-23    Vinodhan K        Created                                                                                *
* 2019-08-05    Vinodhan K        Modifed to list the handler list by recently selected handlers by the logged in user   *
 *************************************************************************************************************************/

BEGIN

	DECLARE @StartRow INT;
	DECLARE @EndRow INT;

	SET @PageNumber = ISNULL(@PageNumber, 0) - 1;

	IF(@PageNumber > -1)
	BEGIN
		SET @StartRow = ((@PageNumber) * @PageSize) + 1;
		SET @EndRow = (@StartRow + @PageSize) - 1;
	END

	SELECT 
		IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#FoundTable
	FROM
	(SELECT
		RTRIM(A.CODE)				AS CODE,
		RTRIM(A.TEAM)				AS TEAM,
		RTRIM(A.TEAMCODE)			AS TEAMCODE,
		RTRIM(A.[NAME])				AS [NAME],
		RTRIM(A.LOGON)				AS LOGON,
		RTRIM(A.EXCHANGEALIAS)		AS EXCHANGEALIAS,
		RTRIM(A.RETIRED)			AS RETIRED,
		RTRIM(B.HANDLER)			AS HANDLER,
		RTRIM(B.NOOUTSTANDACTIONS)	AS NOOUTSTANDACTIONS,
		RTRIM(A.DEFAULTTASK)		AS DEFAULTTASK,
		C.AccessedTime				AS AccessedTime
	FROM
		Handlers A
	LEFT JOIN
		NoOverDueTasks B
	ON
		A.CODE = B.HANDLER
	LEFT JOIN
		RecentHandlerList C
	ON
		C.Code = A.CODE AND C.AccessedBy = @CODE
	 WHERE
	 (
		A.CODE LIKE '%' + @SearchText + '%'
		OR
		A.[NAME] LIKE '%' + @SearchText + '%'
	 )
	AND
		A.RETIRED <> 'Y'
	AND
		A.CODE <> @CODE) AS FoundTable
	ORDER BY
		FoundTable.AccessedTime DESC,
		CODE ASC

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

	SELECT
		(COUNT([Row_Number])) AS [TotalRecords]
	FROM
		#FoundTable
END
GO
IF OBJECT_ID(N'KEYHM_GetMatterDocFolderTree', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetMatterDocFolderTree]
END
GO

CREATE PROCEDURE [dbo].[KEYHM_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].[KEYHM_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 *                                                   
 *******************************************************************************************************/    
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].[KEYHM_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].[KEYHM_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].[KEYHM_DuplicateDocFolderTree] @folderid      
        END      
      
      INSERT      
        INTO [dbo].[MatterDocFolders]      
            ([MatterCode],      
             [DocFolderID])      
      SELECT @MatterCode,      
             @folderid      
    END    
      
 SELECT  
  *    
 FROM [dbo].[KEYHM_FN_GetDocFolders](@matter, @folderid, 1, 1)     
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_GetMatterLedger'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetMatterLedger]
  END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetMatterLedger]
                       (
					   @MatterCode         VARCHAR(20),
					   @PageNumber         INT           = NULL, 
					   @PageSize           INT           = NULL,
					   @SearchText         VARCHAR(400)  = NULL, 
					   @SortColumn         VARCHAR(50)   = NULL,
					   @SortDirection      VARCHAR(10)   = NULL
					   )
AS
/*******************************************************************************************************
*                                                                                                      *
*Used to list the matter ledger                                                                        *
*                                                                                                      *
* Stored Procedure Name: [dbo].[KAAS_WebApi_DeleteOtherContacts]                                       *
* Copied From: [dbo].[ky_NETGetMatterLedger]                                                           *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-26    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
    DECLARE @SQL NVARCHAR(MAX)

    DECLARE @ISSAM4 BIT
    SELECT @ISSAM4 = [dbo].[ISSAM4]()

	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(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

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

    IF @ISSAM4 = 0
    BEGIN
      SET @SQL = N'
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #MatterLedgerTable
	    FROM
	    (SELECT
		       [MTL].[MATTER]                          AS [Matter],
               ISNULL([MTL].[BATCHNO], 0)              AS [BATCHNO],
               ISNULL([MTL].[PREF], 0)                 AS [Pref],
			   CONVERT(NVARCHAR(30),[MTL].[DATE],23)   AS [Date],
               ISNULL([MTL].[REF], '''')               AS [Reference],
               ISNULL([MTL].[NARR], '''')              AS [Narrative],
               ISNULL([MTL].[VALUED], 0)               AS [Billing],
               ISNULL([MTL].[VALUEO], 0)               AS [OutLay],	
               ISNULL([MTL].[VALUECC], 0)              AS [ClientCurrent],
               ISNULL([MTL].[VALUECD], 0)              AS [Deposit],
               ISNULL([MTL].[FEE], '''')               AS [Fee],
               [MTL].[EntryDate]                       AS [EntryDate],
               ISNULL([MTL].[CLIENT], '''')            AS [Client],
               ISNULL([MTL].[LREF], 0)                 AS [LRef],
               ISNULL([MTL].[BILLED], 0)               AS [Billed],
               CASE WHEN CHARINDEX(''undertaking'', ISNULL([MTL].[NARR], '''')) > 0
                         THEN 1
                    WHEN ISNULL([MTL].[PREF], 0) = 0
                         THEN 0
                    ELSE 2 END                         AS [RowHighlight],
               ISNULL([BAH].[TYPE], '''')              AS [Type],
               ISNULL([BAD].[OUTLAYCODE],'''')         AS [OutlayCode],
               RTRIM(ISNULL([BAD].[OUTLAYDESC], '''')) AS [OutlayDesc],
               0                                       AS [Unbilled] /* Not used in SAM3 */
          FROM [dbo].[MatterLedger] AS [MTL]
               LEFT OUTER JOIN [dbo].[BatchH] AS [BAH]
                            ON [BAH].[BATCHNO] = [MTL].[BATCHNO]
                           AND [BAH].[BATCHNO] <> 0
               OUTER APPLY (SELECT TOP 1
                                   [BDL].[OUTLAYCODE],
                                   [OLC].[DESCRIPTION] AS [OUTLAYDESC]
                              FROM [dbo].[BatchDetails] [BDL]
                                   LEFT OUTER JOIN [dbo].[OutlayCode] [OLC]
                                                ON [OLC].[CODE] = [BDL].[OUTLAYCODE]
                             WHERE [BDL].[BATCHNO] = [MTL].[BATCHNO]
                               AND [BDL].[PREF] = [MTL].[PREF]
                               AND [BDL].[BATCHNO] <> 0) [BAD]
         WHERE
		      (
			   @SearchText = ''''
		       OR
			   (
		       [MTL].[MATTER] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[BATCHNO] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[PREF] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[DATE] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[REF] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[NARR] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[VALUED] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[VALUEO] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[VALUECC] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[VALUECD] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[FEE] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[EntryDate] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[CLIENT] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[LREF] LIKE ''%' + @SearchText + '%''
			   OR
			   [MTL].[BILLED] LIKE ''%' + @SearchText + '%''
			   OR
			   [BAH].[TYPE] LIKE ''%' + @SearchText + '%''
			   OR
			   [BAD].[OUTLAYCODE] LIKE ''%' + @SearchText + '%''
			   OR
			   [BAD].[OUTLAYDESC] LIKE ''%' + @SearchText + '%''
			   )
              )
			  AND
			  [MTL].[MATTER] = @MatterCode) AS FoundTable'
     
	 IF((@SortColumn IS NULL) AND (RTRIM(@SortColumn) = ''))
	 BEGIN
	  SET @SQL = @SQL + ' ORDER BY
               [Matter] ASC,
               [Date] ASC,
               [LRef] ASC'
	 END

     IF((@SortColumn IS NOT NULL) AND (RTRIM(@SortColumn) != ''))
	 BEGIN
		SET @SQL =  @SQL + '
		ORDER BY ' + @SortColumn + ' ' + @SortDirection
	 END

      SET @SQL = @SQL +' SELECT
		*
	  FROM
	  	#MatterLedgerTable
	  WHERE
	  (
		@StartRow IS NULL
		OR
		(
			[Row_Number] BETWEEN @StartRow AND @EndRow		
		)
	  )

	  SELECT
		  (COUNT([Row_Number])) AS [TotalRecords]
	  FROM
	      #MatterLedgerTable'

      SET @SQL = @SQL +' SELECT TOP 1
             ISNULL([MAT].[ClientMin], 0)    AS [ClientMin],
             ISNULL([MTL].[BillingSum], 0)   AS [BillingSum],
             ISNULL([MTL].[OutlaySum], 0)    AS [OutlaySum],
             ISNULL([MTL].[CurrentSum], 0)   AS [CurrentSum],
             ISNULL([MTL].[DepositSum], 0)   AS [DepositSum],
             ISNULL([UND].[Undertakings], 0) AS [Undertakings],
             0                               AS [WIP]
        FROM [dbo].[matters] AS [MAT]
             OUTER APPLY (SELECT SUM(ISNULL(MTL.[VALUED], 0)) AS [BillingSum],
                                 SUM(ISNULL(MTL.[VALUEO], 0)) AS [OutlaySum],
                                 SUM(ISNULL(MTL.[VALUECC], 0)) AS [CurrentSum],
                                 SUM(ISNULL(MTL.[VALUECD], 0)) AS [DepositSum]
                            FROM [dbo].[MatterLedger] AS MTL
                           WHERE MTL.[MATTER] = @MatterCode) AS MTL
             OUTER APPLY (SELECT COUNT(1) AS [Undertakings]
                            FROM [dbo].[Undertakings] AS UND
                           WHERE UND.[MATTER] = @MatterCode
                             AND UND.[DISCHARGEDATE] IS NULL) AS UND
       WHERE MAT.[Code] = @MatterCode'
    END
    ELSE
    BEGIN
        SET @SQL = N'
        SELECT 
		    IDENTITY(INT, 1,1) AS [Row_Number],
		    *
	    INTO
		    #MatterLedgerTable
	    FROM
	    (SELECT TRN.[MatterCode] AS [Matter],
               ISNULL(TRN.[BatchNo], 0)       AS [BATCHNO],
               ISNULL(TRN.[PostRef], 0)       AS [Pref],
               TRN.[TransDate]                AS [Date],
               ISNULL(TRN.[TransRef], '''')   AS [Reference],
               ISNULL(TRN.[Narrative], '''')  AS [Narrative],
               ISNULL(TRN.[DebtorsValue], 0)  AS [Billing],
               ISNULL(TRN.[OutlayValue], 0)   AS [OutLay],
               ISNULL(TRN.[ClientCurrent], 0) AS [ClientCurrent],
               ISNULL(TRN.[ClientDeposit], 0) AS [Deposit],
               ISNULL(TRN.[FeeEarner], '''')  AS [Fee],
               TRN.[EntryDate]                AS [EntryDate],
               ISNULL(MAT.[ClientCode], '''') AS [Client],
               ISNULL(TRN.[XnID], 0)          AS [LRef],
               ''''                             AS [Billed], /* Not used in SAM4 */
               CASE WHEN CHARINDEX(''undertaking'', ISNULL(TRN.[Narrative], '''')) > 0
                         THEN 1
                    WHEN ISNULL(TRN.[PostRef], 0) = 0
                         THEN 0
                    ELSE 2 END                AS [RowHighlight],
               ISNULL(TRN.[XnType], '''')     AS [Type],
               ISNULL(TRN.[OutlayCode], '''') AS [OutlayCode],
			   [TRN].[Seq]                    AS [Seq],
               RTRIM(ISNULL([OLC].[DESCRIPTION], '''')) AS [OutlayDesc],
               CASE WHEN TRN.[XnType] IN (''P'', ''B'', ''J'')
                     AND ISNULL(TRN.[OutlayValue], 0) <> 0
                     AND ISNULL(TRN.[BilledOutlay], 0) = 0
                         THEN 1
                    WHEN TRN.[XnType] IN (''P'', ''B'', ''J'')
                     AND ISNULL(TRN.[OutlayValue], 0) <> 0
                     AND ISNULL(TRN.[BilledOutlay], 0) <> ISNULL(TRN.[OutlayValue], 0)
                         THEN 2
                    ELSE 0 END                AS [Unbilled]
          FROM [dbo].[matters] AS MAT
               INNER JOIN [dbo].[Transactions] AS TRN
                          LEFT OUTER JOIN [dbo].[OutlayCode] [OLC]
                                       ON [OLC].[OutlayCode] = [TRN].[OutlayCode]
                       ON MAT.[Code] = TRN.[MatterCode]
		   WHERE
           (
            @SearchText = ''''
            OR
            (
            [TRN].[MatterCode] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[BatchNo] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[PostRef] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[TransDate] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[TransRef] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[Narrative] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[DebtorsValue] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[OutlayValue] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[ClientCurrent] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[ClientDeposit] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[FeeEarner] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[EntryDate] LIKE ''%' + @SearchText + '%''
            OR
            [MAT].[ClientCode] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[XnID] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[XnType] LIKE ''%' + @SearchText + '%''
			OR
			[TRN].[OutlayCode] LIKE ''%' + @SearchText + '%''
            OR
            [TRN].[BilledOutlay] LIKE ''%' + @SearchText + '%''
            OR
            [OLC].[DESCRIPTION] LIKE ''%' + @SearchText + '%''
            )
           )
           AND
		   MAT.[Code] = @MatterCode
           AND TRN.[Posted] = ''Y''
           AND TRN.[RecType] <> ''V''
           AND TRN.[CorrectionInd] IN (''L'', ''C'')) AS FoundTable'
      
	 IF((@SortColumn IS NULL) AND (RTRIM(@SortColumn) = ''))
	 BEGIN
	  SET @SQL = @SQL + ' ORDER BY
               [Matter] ASC,
               [Date] ASC,
               [Seq] ASC,
               [LRef] ASC'
	 END

     IF((@SortColumn IS NOT NULL) AND (RTRIM(@SortColumn) != ''))
	 BEGIN
		SET @SQL =  @SQL + '
		ORDER BY ' + @SortColumn + ' ' + @SortDirection
	 END

      SET @SQL = @SQL + ' SELECT
		*
	  FROM
	  	#MatterLedgerTable
	  WHERE
	  (
		@StartRow IS NULL
		OR
		(
			[Row_Number] BETWEEN @StartRow AND @EndRow		
		)
	  )

	  SELECT
		  (COUNT([Row_Number])) AS [TotalRecords]
	  FROM
	      #MatterLedgerTable'

      SET @SQL = @SQL + 
	   ' SELECT ISNULL(MAT.[ClientMin], 0) AS [ClientMin],
               0.00                       AS [BillingSum], /* These balances aren''t used in SAM4. They are calculated on the client machine */
               0.00                       AS [OutlaySum],
               0.00                       AS [CurrentSum],
               0.00                       AS [DepositSum],
               ISNULL(UND.[Count], 0)     AS [Undertakings],
               ISNULL(TIE.[WIP], 0)       AS [WIP]
          FROM [dbo].[matters] AS MAT
               OUTER APPLY (SELECT COUNT(1) AS [Count]
                              FROM [dbo].[Undertakings] AS UND
                             WHERE UND.[MATTER] = @MatterCode
                               AND UND.[DISCHARGEDATE] IS NULL) AS UND
               OUTER APPLY (SELECT SUM(ISNULL(TIE.[Charge], 0)) AS [WIP]
                              FROM [dbo].[TimeEntry] AS TIE
                             WHERE TIE.[Matter] = @MatterCode
                               AND TIE.[InvoiceNo] = 0
                               AND TIE.[Rec_Irr] = ''C''
                               AND TIE.[IncludeInBill] <> 2
                               AND TIE.[TimeOrCharge] IN (''T'', ''C'')) AS TIE
         WHERE MAT.[Code] = @MatterCode'
    END

    IF ISNULL(@SQL, '') <> ''
    BEGIN
        EXEC sp_executesql @SQL, N'@MatterCode VARCHAR(20), @SearchText VARCHAR(400), @SortColumn VARCHAR(50), @SortDirection VARCHAR(10), @StartRow INT, @EndRow INT', @MatterCode = @matterCode, @SearchText = @searchText, @SortColumn = @sortColumn, @SortDirection = @sortDirection, @StartRow = @startRow, @EndRow = @endRow
    END
END
GO
IF OBJECT_ID(N'KEYHM_GetMatterLedgerDetail', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetMatterLedgerDetail]
END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetMatterLedgerDetail]  (@MatterCode VARCHAR(20))  
AS  
/******************************************************************************************************************
*                                                                                                                 *
* Used to fetch matter ledger and account summary details                                                         *
*                                                                                                                 *
* Stored Procedure Name: [dbo].[KEYHM_GetMatterLedgerDetail]                                                       *
* Copied from   : [dbo].[ky_NETGetMatterLedger]                                                                   *
*                 [dbo].[ky_NETGetMatterLedgerSAM4]                                                               *
*                                                                                                                 *  
* Modification History:                                                                                           *  
* 2019-04-26    Vinodhan K        Created                                                                         *  
 ******************************************************************************************************************/  
BEGIN    

DECLARE @IsSAM4 bit      
DECLARE @Query NVARCHAR(200)

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

EXECUTE KEYHM_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'KEYHM_GetMostRecentMatterHeader'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetMostRecentMatterHeader]
  END
GO

CREATE PROCEDURE [KEYHM_GetMostRecentMatterHeader]
      (@handler      VARCHAR(10))
AS
/*******************************************************************************************************
* Get the Header details for the Most Recent Matter for a handler 									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetMostRecentMatterHeader]									   *
* Copied from			: [dbo].[ky_NETPGetMostRecentMatterHeader]									   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 
BEGIN
  SELECT TOP 1
         [KHD].[CODE],
         [KHD].[ClientCode],
         [KHD].[MatterNo],
         [KHD].[YourRef],
         [KHD].[DESCRIPTION],
         [KHD].[FECode],
         [KHD].[FEName],
         [KHD].[Name],
         [KHD].[TelNo],
         [KHD].[Address],
         [KHD].[Closed],
         [KHD].[TOOLTIP],
         [KHD].[IsChildcare],
         [KHD].[User1],
         [KHD].[User2],
         [KHD].[User3],
         [KHD].[Partner],
         [KHD].[PartnerName],
         [KHD].[CompBillingMatter],
         [KHD].[MatterUniqueID]
    FROM [dbo].[RecentMatterList] [RML]
         CROSS APPLY [dbo].[KEYHM_FN_MatterHeaderDetails]([RML].[MATTER]) [KHD]
   WHERE [RML].[FEE] = @handler
ORDER BY [RML].[DateField] DESC
END

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

CREATE PROCEDURE [dbo].[KEYHM_GetMyDayBook]
				  (@FECode			VARCHAR(10),
				   @Post			CHAR(1)			= 'N',
				   @Handler			NVARCHAR(10),
				   @Key				NVARCHAR(100),
				   @SearchText		VARCHAR(4000)	= '',
				   @PageNumber		INT				= NULL,
				   @PageSize		INT				= NULL,
				   @SortColumn		VARCHAR(50)		= NULL,
				   @SortDirection	VARCHAR(10)		= NULL)
AS
/*******************************************************************************************************
* Gets the Day Book																				       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetMyDayBook]													   *
* Copied from			: [dbo].[ky_NETGetMyDayBook]												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K		Created																   *
* 2019-07-02	Vinodhan K		Case Time format has been modifed to "00:00"					       *
 *******************************************************************************************************/   
BEGIN

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(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = 'Row_Number'
	END
IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = 'ASC'
	END

DECLARE @DayBookValue INT

SELECT
	@DayBookValue = ISNULL(SUM([TDB].[Time]), 0)
FROM
	[dbo].[Timedaybook] [TDB] WITH (NOLOCK)
WHERE
	[TDB].[FeeEarn] = @FECode

IF(@DayBookValue = 0)
  BEGIN
    SET @DayBookValue=1
  END

DECLARE @DAYBOOK TABLE
       ([Row_Number]			INT				IDENTITY(1, 1)	 NOT NULL,
	    [Time]				    INT                              NOT NULL,
        [CaseTime]              VARCHAR(60)                      NOT NULL,
        [MatterDetails]         VARCHAR(500)                     NOT NULL,
        [Progress]              INT                              NOT NULL,
        [StopwatchStatus]       INT                              NOT NULL,
        [RecordID]              INT                              NOT NULL   PRIMARY KEY,
        [DATE]                  DATETIME                         NOT NULL,
        [MATTER]                VARCHAR(20)                      NOT NULL,
        [DisplayMatter]         VARCHAR(20)                      NOT NULL,
        [Name]                  VARCHAR(256)                     NOT NULL,
        [COMMENT]               VARCHAR(1000)                    NOT NULL,
        [CHARGE]                DECIMAL(10, 2)                   NOT NULL,
        [TimeOrCharge]          VARCHAR(1)                       NOT NULL,
        [Post]                  VARCHAR(1)                       NOT NULL)

DECLARE @DAYBOOKSUM TABLE
       ([id]                    INT             IDENTITY(1, 1)   NOT NULL   PRIMARY KEY,
        [RecordID]              INT                              NOT NULL,
        [Time]                  INT                              NOT NULL,
        [OriginalTime]          INT                              NOT NULL,
        [TotalTimeMinusOne]     INT                              NOT NULL)

INSERT
	INTO @DAYBOOK
		([Time],
		[CaseTime],
		[MatterDetails],
		[Progress],
		[StopwatchStatus],
		[RecordID],
		[DATE],
		[MATTER],
		[DisplayMatter],
		[Name],
		[COMMENT],
		[CHARGE],
		[TimeOrCharge],
		[Post])
	SELECT
		[TDB].[Time],
			CASE
				WHEN
					[TDB].[Time] < 0
				THEN
					'-'
				ELSE
					''
			END
			+
			--RIGHT('00' + CAST(FLOOR(ABS([TDB].[Time]) / 60) AS VARCHAR), 3)
			--SUBSTRING(CONVERT(VARCHAR, FLOOR(ABS([TDB].[Time]) / 60)), LEN(CONVERT(VARCHAR, FLOOR(ABS([TDB].[Time]) / 60))) - 1, 2)
			CASE
				WHEN
					LEN(FLOOR(ABS([TDB].[Time]) / 60)) < 2
				THEN
					'0' +  CAST(FLOOR(ABS([TDB].[Time])) / 60 AS VARCHAR)
				ELSE
					CAST(FLOOR(ABS([TDB].[Time])) / 60 AS VARCHAR)
	        END
			+
			':'
			+
			SUBSTRING
			(
				CONVERT(VARCHAR, 100 + ABS([TDB].[Time]) % 60),
				LEN(CONVERT(VARCHAR, 100 + ABS([TDB].[Time]) % 60)) - 1,
				2
			)																				AS [CaseTime],
		[dbo].[KEYHM_FN_RemoveSpuriousWhitespace] --2018-03-12
		( 
			RTRIM(ISNULL([CON].[Name], ''))
			+
			' '
			+
			RTRIM(ISNULL([MAT].[Description], '')),
			500
		)																					AS [MatterDetails],
		0																					AS [Progress],
		ISNULL([TDB].[StopwatchStatus], 0)													AS [StopwatchStatus],
		[TDB].[RecordID]																	AS [RecordID],
		[TDB].[Date]																		AS [DATE],
		[TDB].[Matter]																		AS [Matter],
		CASE
			WHEN
				[TDB].[Matter] = '~'
			THEN
				'Admin Time'
			ELSE
				[TDB].[Matter]
			END																				AS [DisplayMatter],
		RTRIM(ISNULL([CON].[Name],''))														AS [Name],
		RTRIM(ISNULL([TDB].[Comment], ''))													AS [COMMENT],
		[TDB].[Charge]																		AS [CHARGE],
		UPPER([TDB].[TimeOrCharge])															AS [TimeorCharge],
		CASE
			WHEN
				RTRIM(UPPER(ISNULL([TDB].[Post], ''))) = 'N'    
            THEN
				'N'
            ELSE
				'Y'
		END																					AS [Post]
	FROM
		[dbo].[TimeDayBook] [TDB] WITH (NOLOCK)
	LEFT OUTER JOIN
		[dbo].[matters] [MAT] WITH (NOLOCK)
	ON
		[MAT].[Code] = [TDB].[Matter]
	LEFT OUTER JOIN
		[dbo].[Contacts] [CON] WITH (NOLOCK)
	ON
		[CON].[Code] = [MAT].[ClientCode]
   WHERE
	(
		RTRIM(ISNULL([CON].[Name],'')) LIKE '%' + @SearchText + '%'
		OR
		RTRIM(ISNULL([MAT].[Description],'')) LIKE '%' + @SearchText + '%'
		OR
		RTRIM(ISNULL([TDB].[Matter],'')) LIKE '%' + @SearchText + '%'
		OR
		RTRIM(ISNULL([TDB].[Comment],'')) LIKE '%' + @SearchText + '%'
	)
	AND
		[TDB].[FeeEarn] = @FECode
	AND
		ISNULL([TDB].[Post], 'Y') IN ('Y', @Post)
	ORDER BY
		[TDB].[RecordID]

	INSERT INTO @DAYBOOKSUM
        ([RecordID],
         [Time],
         [OriginalTime],
         [TotalTimeMinusOne])
	SELECT [TDB].[RecordID],
         0,
         ISNULL([TDB].[Time], 0),
         0
    FROM
		@DAYBOOK [TDB]
	ORDER BY
		[TDB].[RecordID]

DECLARE @TOTALTIME INT
SET @TOTALTIME = 0

UPDATE [DBS]
	SET @TOTALTIME = @TOTALTIME + ISNULL([DBSPREV].[OriginalTime], 0),
       [DBS].[TotalTimeMinusOne] = @TOTALTIME
	FROM @DAYBOOKSUM [DBS]
       LEFT OUTER JOIN @DAYBOOKSUM [DBSPREV]
                    ON [DBSPREV].[id] = [DBS].[id] - 1

UPDATE [DBS]
	SET [DBS].[Time] = [DBS].[OriginalTime] + [DBS].[TotalTimeMinusOne]
	FROM @DAYBOOKSUM [DBS]

-- This will guarantee that the percentages in [Progress] will always add up to exactly 100
UPDATE [TDB]
	SET [TDB].[Progress]
		= CONVERT(INT, ROUND((CONVERT(FLOAT, [TDBS].[Time]) / CONVERT(FLOAT, @DayBookValue)) * CONVERT(FLOAT, 100), 0))                --The current cumulative percentage
		- CONVERT(INT, ROUND((CONVERT(FLOAT, [TDBS].[Time] - [TDB].[Time]) / CONVERT(FLOAT, @DayBookValue)) * CONVERT(FLOAT, 100), 0)) -- minus the last cumulative percentage
	FROM @DAYBOOKSUM [TDBS]
		INNER JOIN @DAYBOOK [TDB]
			ON [TDB].[RecordID] = [TDBS].[RecordID]
       --CROSS APPLY (SELECT ISNULL(SUM([TDBP].[Time]), 0) AS [Time]
       --               FROM @DAYBOOK [TDBP]
       --              WHERE [TDBP].[RecordID] <= [TDB].[RecordID]) [TDBS]

	SELECT
		[TDB].[Row_Number],
		[TDB].[Time],
		[TDB].[CaseTime],
		[TDB].[MatterDetails],
		[TDB].[Progress],
		[TDB].[StopwatchStatus],
		[TDB].[RecordID],
		CONVERT(NVARCHAR(30),[TDB].[DATE],23) AS [DATE],
		[TDB].[MATTER],
		[TDB].[DisplayMatter],
		[TDB].[Name],
		[TDB].[COMMENT],
		[TDB].[CHARGE],
		[TDB].[TimeOrCharge],
		[TDB].[Post]
	FROM
		@DAYBOOK [TDB]
	WHERE
	(
		@StartRow IS NULL
		OR
		(
			[Row_Number] BETWEEN @StartRow AND @EndRow
		)
	)
	ORDER BY
		CASE WHEN @SortDirection = 'ASC' THEN
			CASE @SortColumn 
					WHEN 'Row_Number'   THEN [Row_Number]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Row_Number'   THEN [Row_Number]
				END
			END DESC,
		CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Date'   THEN [DATE]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Date'   THEN [DATE]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
			CASE @SortColumn 
					WHEN 'DisplayMatter'   THEN [DisplayMatter]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'DisplayMatter'   THEN [DisplayMatter]
				END
			END DESC,
		CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Name'   THEN [Name]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Name'   THEN [Name]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'MatterDetails'   THEN [MatterDetails]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'MatterDetails'   THEN [MatterDetails]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Comment'   THEN [Comment]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Comment'   THEN [Comment]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Charge'   THEN [Charge]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Charge'   THEN [Charge]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'CaseTime'   THEN [CaseTime]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'CaseTime'   THEN [CaseTime]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Progress'   THEN [Progress]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Progress'   THEN [Progress]
				END
			END DESC
    
	SELECT
		[TDB].[Rec_Irr]                                                                     AS [ChargeType],
		CASE WHEN SUM([TDB].[Time]) < 0 THEN '-' ELSE '' END
		+ CASE WHEN ABS(FLOOR(SUM([TDB].[Time]) / 60.0)) < 10 THEN '0' ELSE '' END
		+ CONVERT(VARCHAR, ABS(FLOOR(SUM([TDB].[Time]) / 60)))
		+ ':'
		+ RIGHT('00' + CONVERT(VARCHAR, ABS(FLOOR(SUM([TDB].[Time]))) % 60), 2)             AS [CaseTime]
	FROM
		[dbo].[TimeDayBook] [TDB] WITH (NOLOCK)
	WHERE
		[TDB].[FeeEarn] = @FECode
     AND
		ISNULL([TDB].[Post], 'Y') IN ('Y', @Post)
	 GROUP BY
		[TDB].[Rec_Irr]
	ORDER BY
		[TDB].[Rec_Irr]

SELECT @DayBookValue AS DayBookValue

EXECUTE [dbo].[KEYHM_GetUserSettings] @Handler, @Key

SELECT
	COUNT([Row_Number])
FROM
	@DAYBOOK

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

CREATE PROCEDURE
       [dbo].[KEYHM_GetNextActionID]
AS

/*******************************************************************************************************
* Dummy Procedure in preparation for the use of the DiarySeed table									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetNextActionID]												   *
* Copied from			: [dbo].[ky_NETGetNextActionID]											       *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

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'KEYHM_GetNextTrackReferenceInDiaryAttachments'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetNextTrackReferenceInDiaryAttachments]
  END
GO

CREATE PROCEDURE 
       [dbo].[KEYHM_GetNextTrackReferenceInDiaryAttachments]
AS
/*******************************************************************************************************
* Gets next available track referene number                                                            *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetNextTrackReferenceInDiaryAttachments]                         *
* Copied from			: [dbo].[spGetNextTrackReferenceInDiaryAttachments]                            *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-10	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
	DECLARE @TrackReference INT

	EXEC @TrackReference = [dbo].[ky_NETGetNextTrackReference]

	SELECT @TrackReference AS [TRACKREFERENCE]
	--SELECT
	--	ISNULL(MAX(TRACKREFERENCE), 0)+1    AS    TRACKREFERENCE
	--FROM
	--	dbo.DiaryAttachments  --ORDER BY TRACKREFERENCE DESC
END
GO
IF OBJECT_ID(N'KEYHM_GetTaskList',N'P')IS NOT NULL
	DROP PROCEDURE KEYHM_GetTaskList
GO
CREATE PROCEDURE [dbo].[KEYHM_GetTaskList]
      (@HandlerID			VARCHAR(10)   = NULL,
       @FromDate			DATETIME      = NULL,
       @ToDate				DATETIME      = NULL,
       @TaskListMode		BIT,
       @TeamID				VARCHAR(10)   = NULL,
       @IsOutstandingOnly	BIT           = 1,
       @BitWiseID			BIGINT,
	   @From				INT           = 0,
       @To					INT           = 5000,
       @TaskType			VARCHAR(20)   = '',
	   @PageNumber			INT           = NULL,
       @PageSize			INT           = NULL,
	   @SearchText			VARCHAR(4000) = NULL,
	   @ActionType			VARCHAR(4000) = NULL,
	   @Priority			VARCHAR(4000) = NULL,
       @Flag				VARCHAR(4000) = NULL,
	   @SortColumn			VARCHAR(50)   = NULL,
	   @SortDirection		VARCHAR(10)   = NULL,
       @TotalRecords		INT           = 1 OUT,
       @userprompt1			VARCHAR(MAX)  = 'USERPROMPT1' OUT,
       @userprompt2			VARCHAR(MAX)  = 'USERPROMPT2' OUT,
       @userprompt3			VARCHAR(MAX)  = 'USERPROMPT3' OUT)
AS
/*****************************************************************************************************************
*																											     *
* Get the task list for the framework's main Task screen													     *
*																											     *
* Stored Procedure Name : [dbo].[KEYHM_GetTaskList]															     *
* Copied from           : [dbo].[ky_NETGetTaskList]															     *
*																											     *
* Modification History:																						     *
* 2018-12-03	Vinodhan K			Created                                                                      *
* 2019-01-29	Vinodhan K			Paging added                                                                 *
* 2019-04-09	Vinodhan K			Sorting of few columns have been implemeneted                                *
* 2019-04-30	Arun V				KEYHM-402 Issue corrected. If SortColumn and SortDirection not			     *
									specified then make these column as empty string, so sorting will not	     *
									perform. default sorting condition will apply.							     *
									ORDER BY DEL.[HANDLER] DESC,											     *
									DEL.[DATE] DESC,														     *
									DEL.[TIME] DESC,														     *
									DEL.[AssignNo] DESC														     *
* 2019-11-18    Vinodhan K          FNName will be fecthed from [Handlers] table instead of [FeeEarnerCodes]     *
* 2020-03-19    Prabhu V            SP Optimized																 *
* 2020-03-28    Prabhu V            Optimized SP not working properly for Outstanding and Over due tasks         *
                                    Issue Fixed																     *
* 2020-03-30    Ganapathy T         Like Search functionality implemented                                        *
* 2020-04-08    Prabhu V            SP Optimized	to Load Data with in a second								 *
* 2020-05-04    Arun                randomly record got changed issue fixed.KEYHM-588						     *
*																											     *
******************************************************************************************************************/
BEGIN


--Insert into LogTable(LogInfo, Module) values 
--(
--'@HandlerID			'+isnull(convert(nvarchar(500),	@HandlerID			),'')+
--'@FromDate			'+isnull(convert(nvarchar(500),	@FromDate			),'')+
--'@ToDate			'+isnull(convert(nvarchar(500),	@ToDate				),'')+
--'@TaskListMode		'+isnull(convert(nvarchar(500),	@TaskListMode		),'')+
--'@TeamID			'+isnull(convert(nvarchar(500),	@TeamID				),'')+
--'@IsOutstandingOnly	'+isnull(convert(nvarchar(500),	@IsOutstandingOnly	),'')+
--'@BitWiseID			'+isnull(convert(nvarchar(500),	@BitWiseID			),'')+
--'@From				'+isnull(convert(nvarchar(500),	@From				),'')+
--'@To				'+isnull(convert(nvarchar(500),	@To					),'')+
--'@TaskType			'+isnull(convert(nvarchar(500),	@TaskType			),'')+
--'@PageNumber		'+isnull(convert(nvarchar(500),	@PageNumber			),'')+
--'@PageSize			'+isnull(convert(nvarchar(500),	@PageSize			),'')+
--'@SearchText		'+isnull(convert(nvarchar(500),	@SearchText			),'')+
--'@ActionType		'+isnull(convert(nvarchar(500),	@ActionType			),'')+
--'@Priority			'+isnull(convert(nvarchar(500),	@Priority			),'')+
--'@Flag				'+isnull(convert(nvarchar(500),	@Flag				),'')+
--'@SortColumn		'+isnull(convert(nvarchar(500),	@SortColumn			),'')+
--'@SortDirection		'+isnull(convert(nvarchar(500),	@SortDirection		),'')+
--'@TotalRecords		'+isnull(convert(nvarchar(500),	@TotalRecords		),'')+
--'@userprompt1		'+isnull(convert(nvarchar(500),	@userprompt1		),'')+	
--'@userprompt2		'+isnull(convert(nvarchar(500),	@userprompt2		),'')+	
--'@userprompt3		'+isnull(convert(nvarchar(500),	@userprompt3		),'')	
--,'My Task')


DECLARE @StartRow INT;
DECLARE @EndRow INT;

IF(@SortColumn = '' OR @SortColumn = NULL)
	BEGIN
		SET @SortColumn = ''
	END
IF(@SortDirection = '' OR @SortDirection = NULL)
	BEGIN
		SET @SortDirection = ''
	END
IF REPLACE(RTRIM(ISNULL(@SearchText, '')), '%', '') = ''
  BEGIN
    SET @SearchText = NULL
  END

IF @SearchText IS NOT NULL AND CHARINDEX('%', @SearchText) = 0
	BEGIN
		SET @SearchText = '%' + @SearchText + '%';
	END


SET NOCOUNT ON

DECLARE @ShowFromToSynopsis BIT

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

SET @BitWiseID = ISNULL(@BitWiseID, CONVERT(BIGINT, 0))


DECLARE @DELS    TABLE( [ID] 					INT NOT NULL IDENTITY(1,1),
						[DATE] 					DATETIME,
						[TIME]					VARCHAR(10) ,
						[AssignNo] 				INT ,
						[ACTIONID] 				INT ,
						[STATUS] 					SMALLINT,
						[HANDLER] 				VARCHAR(10) ,
						[TEAM] 					VARCHAR(10) ,
						[FromHandler] 			VARCHAR(10) ,
						[DelType] 				VARCHAR(15) ,
						[OWNER] 					CHAR(1) ,
						[DELEGATESTATUS] 			SMALLINT ,
						[PRIORITY] 				VARCHAR(1),
						[diaryDATE] 				DATETIME,
						[CASECODE] 				VARCHAR(20),
						[DisplayText] 			VARCHAR(200),
						[diarySTATUS] 			SMALLINT,
						[HIGHLIGHTED] 			VARCHAR(1),
						[diaryACTIONID] 			INT,
						[PROCESSSTATUS]			SMALLINT,
						[DELEGATIONSTATUS] 		INT ,
						[WORKPROCESS] 			SMALLINT,
						[IMAGENO] 				INT,
						[Flag] 					TINYINT,
						[ACTIONTYPE] 				VARCHAR(1) ,
						[PROCESSTYPE] 			VARCHAR(1),
						[EMAILADDRESS] 			VARCHAR(150),
						[Subject] 				VARCHAR(500),
						[AddressTo] 				VARCHAR(2000),
						[TEXT1] 					VARCHAR(max),
						[DUEDATE] 				DATETIME,
						[ACTIONCODE] 				VARCHAR(15),
						[DRAFTBILLNO] 			INT,
						[DYStartTime] 			VARCHAR(10),
						[DYENDTIME] 				VARCHAR(10),
						[CreationDate] 			DATETIME,
						[Delegatedfnr] 			VARCHAR(10),
						[ACTIONSTATUS] 			VARCHAR(3) ,
						[FNCODE] 					VARCHAR(10),
						[User1] 					VARCHAR(100),
						[User2] 					VARCHAR(100),
						[User3] 					VARCHAR(100),
						[YourRef] 				VARCHAR(100),
						[OldRef] 					VARCHAR(12),
						[Description] 			VARCHAR(200),
						[ChargeArrangement] 		CHAR(3),
						[ClientCode] 				VARCHAR(8),
						[FileColour] 				CHAR(3),
						[FECode] 					VARCHAR(10),
						[Secretary] 				VARCHAR(10),
						[Partner] 				VARCHAR(10), 
						[Synopsis] 				VARCHAR(max), 
						[TotalRowsCount] 			Int)
INSERT into @DELS 
  SELECT ISNULL([DEL].[DATE], '18000101') DATE,
         ISNULL([DEL].[TIME], '') TIME,
         [DEL].[AssignNo],
         [DEL].[ACTIONID],
         ISNULL([DEL].[STATUS], 0) STATUS,
		 [DEL].[HANDLER],
		 [DEL].[TEAM],
		 [DEL].[FromHandler],
		 [DEL].[DelType],
		 [DEL].[OWNER],
		 [DEL].[DELEGATESTATUS],
		 [DIA].[PRIORITY],
		 [DIA].[DATE] AS diaryDATE,
		 [DIA].[CASECODE],
		 [DIA].[DisplayText],
		 [DIA].[STATUS] AS diarySTATUS,
		 [DIA].[HIGHLIGHTED],
		 [DIA].[ACTIONID] AS diaryACTIONID,
		 [DIA].[PROCESSSTATUS],
		 [DIA].[DELEGATIONSTATUS],
		 [DIA].[WORKPROCESS],
		 [DIA].[IMAGENO],
		 [DIA].[Flag],
		 [DIA].[ACTIONTYPE],
		 [DIA].[PROCESSTYPE],
		 [DIA].[EMAILADDRESS],
		 [DIA].[Subject],
		 [DIA].[AddressTo],
		 [DIA].[TEXT1],
		 [DIA].[DUEDATE],
		 [DIA].[ACTIONCODE],
		 [DIA].[DRAFTBILLNO],
		 [DIA].[DYStartTime],
		 [DIA].[DYENDTIME],
		 [DIA].[CreationDate],
		 [DIA].[Delegatedfnr],
		 [DIA].[ACTIONSTATUS],
		 [DIA].[FNCODE],
		 [MAT].[User1],
		 [MAT].[User2],
		 [MAT].[User3],
		 [MAT].[YourRef],
		 [MAT].[OldRef],
		 [MAT].[Description],
		 [MAT].[ChargeArrangement],
		 [MAT].[ClientCode],
		 [MAT].[FileColour],
		 [MAT].[FECode],
		 [MAT].[Secretary],
		 [MAT].[Partner], 
		 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(50)),''))) + ' - ' + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(MAX)),'')
							ELSE 'Email To:' + RTRIM(CAST(ISNULL([DIA].[AddressTo],'') AS VARCHAR(50))) + ' - ' + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(MAX)),'')
						END
					ELSE
						CASE
							WHEN [DIA].[SUBJECT] IS NULL OR RTRIM(CAST([DIA].[SUBJECT] AS VARCHAR(max))) = '' OR 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
							ELSE [DIA].[SUBJECT]
						END
				END AS [Synopsis],
				Count(1) Over() as TotalRowsCount

		 
    FROM [dbo].[DiaryDelegations] DEL WITH(NOLOCK)
         INNER JOIN [dbo].[diary] DIA WITH(NOLOCK) 
		 ON [DIA].[ACTIONID] = [DEL].[ACTIONID]
		 INNER JOIN [dbo].[matters] MAT WITH(NOLOCK) 
		 ON [MAT].[Code] = DIA.[CASECODE]  AND [MAT].[Closed] = 'N'
         LEFT OUTER JOIN [dbo].[MatterNETPrivileges] MNP WITH(NOLOCK)     
		 ON [MNP].[MATTER] = [MAT].[Code]    
		 LEFT OUTER JOIN [dbo].[Handlers] [HAN] WITH(NOLOCK)	
		 ON  [HAN].[CODE] = [DIA].[FNCODE]
		 INNER JOIN [dbo].[Contacts] CON WITH(NOLOCK)		
		 ON [CON].[Code] = [MAT].ClientCode
   WHERE
  ( (ISNULL(@TaskListMode, 0) = 1 AND [DEL].[HANDLER] = @HandlerID) 
	OR (ISNULL(@TaskListMode, 0) = 0 AND [DEL].[TEAM] = @TeamID))
  AND [DEL].[DelType] NOT IN ('Completed', 'Processed', 'Returned')     
  AND [DEL].[DATE] >= CONVERT(DATETIME, @FromDate)

 
 AND  (CASE WHEN @TaskType = 'OUTSTANDING' THEN 1
		   WHEN
			(CASE WHEN @TaskType = 'OVERDUE' THEN  DATEADD(DAY, 1, CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112)))
			  WHEN @TaskType != 'OUTSTANDING' THEN DATEADD(DAY, 1, CONVERT(DATETIME, @ToDate))
			  END) > DEL.[DATE] THEN 1
		   ELSE 0
	  END) = 1

  AND ( ((ISNULL(@IsOutstandingOnly, 1) <> 0 AND  [DEL].[STATUS] = 0) ) OR ISNULL(@IsOutstandingOnly, 1) = 0)
  AND (ISNULL([MNP].[Privileges], CONVERT(BIGINT, -1)) & CONVERT(BIGINT, @BitWiseID)<> 0
          OR ISNULL([MNP].[Privileges], CONVERT(BIGINT, 0)) = 0)
  AND (
				RTRIM(LTRIM(ISNULL(@SearchText, ''))) = ''
				OR
				(
					(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(50)),''))) + ' - ' + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(MAX)),'')
							ELSE 'Email To:' + RTRIM(CAST(ISNULL([DIA].[AddressTo],'') AS VARCHAR(50))) + ' - ' + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(MAX)),'')
						END
					ELSE
						CASE
							WHEN [DIA].[SUBJECT] IS NULL OR RTRIM(CAST([DIA].[SUBJECT] AS VARCHAR(max))) = '' OR 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
							ELSE [DIA].[SUBJECT]
						END
				END) LIKE  @SearchText
					 OR RTRIM(ISNULL([DIA].[DisplayText], '')) LIKE  @SearchText
					 OR CONVERT(DATETIME, CONVERT(VARCHAR, ISNULL([DEL].[DATE], '18000101'), 112) + ' ' + CONVERT(VARCHAR, ISNULL([DEL].[DATE], '18000101'), 108))  LIKE  @SearchText
					 OR RTRIM(ISNULL([HAN].[Name], '')) LIKE  @SearchText
					 OR RTRIM(ISNULL([DIA].[CASECODE],'')) LIKE  @SearchText
					 OR RTRIM(ISNULL([DEL].[HANDLER],'')) LIKE  @SearchText
					 OR RTRIM(ISNULL([DEL].[TEAM],'')) LIKE  @SearchText
					 OR RTRIM(ISNULL([CON].[Name],'')) + CHAR(13) +  RTRIM(ISNULL([MAT].[Description],'')) LIKE  @SearchText
				)
			)
	AND
			(
				ISNULL(@ActionType, '') = ''
				OR
				(
					(
						CASE WHEN ISNULL(LTRIM(RTRIM([DIA].[ACTIONTYPE])), '') = '' THEN 'A'
						ELSE [DIA].[ACTIONTYPE]
						END
					) IN (SELECT RTRIM(LTRIM([Item])) FROM KEYHM_FN_SplitString(@ActionType, ','))
				)
			)
			AND
			(
				ISNULL(@Priority, '') = ''
				OR
				(
					[DIA].[PRIORITY] IN (SELECT RTRIM(LTRIM([Item])) FROM KEYHM_FN_SplitString(@Priority, ','))
				)
		
			)
			AND
			(
				ISNULL(@Flag, '') = ''
				OR
				(
					ISNULL([DIA].[Flag],0) IN (SELECT RTRIM(LTRIM([Item])) FROM KEYHM_FN_SplitString(@Flag, ','))
				)
			)
			ORDER BY [DEL].[HANDLER] DESC,
         [DEL].[DATE] DESC,
         [DEL].[TIME] DESC,
         [DEL].[AssignNo] DESC,
		 CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'CompleteOrGeneratedD'   
					THEN (CASE
							WHEN ISNULL([DIA].[WORKPROCESS],0) = 1 AND ISNULL([DIA].[STATUS], 0) <> 1
							THEN 'G'
							WHEN ISNULL([DEL].[STATUS], 0) = 1
							THEN 'C'
							ELSE ''
						  END)
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'CompleteOrGeneratedD'   
					THEN (CASE
							WHEN ISNULL([DIA].[WORKPROCESS],0) = 1 AND ISNULL([DIA].[STATUS], 0) <> 1
							THEN 'G'
							WHEN ISNULL([DEL].[STATUS], 0) = 1
							THEN 'C'
							ELSE ''
						  END)
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'ActionType' THEN  [DIA].[ACTIONTYPE]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'ActionType'   THEN  [DIA].[ACTIONTYPE]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'DelegationStatus'   THEN [DIA].[DelegationStatus]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'DelegationStatus'   THEN [DIA].[DelegationStatus]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Priority'   THEN [DIA].[Priority]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Priority'   THEN [DIA].[Priority]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Date1'   THEN (CASE
											WHEN ISNULL(DEL.[DATE], '18000101') != NULL OR ISNULL(DEL.[DATE], '18000101') != ''
											THEN CONVERT(VARCHAR, ISNULL(DEL.[DATE], '18000101'), 20)
											ELSE
												'1900-01-01'
										END)
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Date1'   THEN (CASE
											WHEN ISNULL(DEL.[DATE], '18000101') != NULL OR ISNULL(DEL.[DATE], '18000101') != ''
											THEN CONVERT(VARCHAR, ISNULL(DEL.[DATE], '18000101'), 20)
											ELSE
												'1900-01-01'
										END)
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Time'   THEN [DEL].[Time]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Time'   THEN [DEL].[Time]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'CaseCode'   THEN [DIA].[CaseCode]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'CaseCode'   THEN [DIA].[CaseCode]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Handler'   THEN [DEL].[Handler]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Handler'   THEN [DEL].[Handler]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Team'   THEN RTRIM(ISNULL([DEL].[TEAM],''))
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Team'   THEN RTRIM(ISNULL([DEL].[TEAM],''))
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'ClientCase'   THEN RTRIM(ISNULL([CON].[Name],'')) + CHAR(13) +  RTRIM(ISNULL([MAT].[Description],''))
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'ClientCase'   THEN RTRIM(ISNULL([CON].[Name],'')) + CHAR(13) +  RTRIM(ISNULL([MAT].[Description],''))
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'Synopsis'   THEN (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(50)),''))) + ' - ' + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(MAX)),'')
													ELSE 'Email To:' + RTRIM(CAST(ISNULL([DIA].[AddressTo],'') AS VARCHAR(50))) + ' - ' + ISNULL(CAST ([DIA].[Subject] AS VARCHAR(MAX)),'')
												END
											ELSE
												CASE
													WHEN [DIA].[SUBJECT] IS NULL OR RTRIM(CAST([DIA].[SUBJECT] AS VARCHAR(max))) = '' OR 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
													ELSE [DIA].[SUBJECT]
												END
											END)
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'Synopsis'   THEN (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(50)),''))) + ' - ' + ISNULL(CAST (DIA.[Subject] AS VARCHAR(MAX)),'')
													ELSE 'Email To:' + RTRIM(CAST(ISNULL(DIA.[AddressTo],'') AS VARCHAR(50))) + ' - ' + ISNULL(CAST (DIA.[Subject] AS VARCHAR(MAX)),'')
												END
											ELSE
												CASE
													WHEN DIA.[SUBJECT] IS NULL OR RTRIM(CAST(DIA.[SUBJECT] AS VARCHAR(max))) = '' OR 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
													ELSE DIA.[SUBJECT]
												END
											END)
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'FileColour'   THEN [MAT].[FileColour]
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'FileColour'   THEN [MAT].[FileColour]
				END
			END DESC,
			CASE WHEN @SortDirection = 'ASC' THEN
				CASE @SortColumn 
					WHEN 'DelDate'   THEN CONVERT(DATETIME, CONVERT(VARCHAR, ISNULL([DEL].[DATE], '18000101'), 112) + ' ' + CONVERT(VARCHAR, ISNULL([DEL].[DATE], '18000101'), 108))
				END
			END,
			CASE WHEN @SortDirection = 'DESC' THEN
				CASE @SortColumn 
					WHEN 'DelDate'   THEN CONVERT(DATETIME, CONVERT(VARCHAR, ISNULL([DEL].[DATE], '18000101'), 112) + ' ' + CONVERT(VARCHAR, ISNULL([DEL].[DATE], '18000101'), 108))
				END
			END DESC
	OFFSET @PageSize * (@PageNumber - 1) ROWS
    FETCH NEXT @PageSize ROWS ONLY OPTION (RECOMPILE);

			SELECT
				[DEL].ID AS [Row_Number],
				[DEL].[STATUS] AS [DDStatus],
				CASE
					WHEN RTRIM(ISNULL([DEL].[PRIORITY], '')) IN ('H', 'L', 'N')
					THEN UPPER(RTRIM(ISNULL([DEL].[PRIORITY], '')))
					ELSE 'N'
				END AS [Priority],
				CONVERT(DATETIME,dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([DEL].[DATE], @HandlerID))	AS [DelDate],
				CONVERT(VARCHAR(5),dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([DEL].[DATE], @HandlerID), 108)	AS [Time],
				RTRIM(ISNULL(DEL.[CASECODE],'')) AS [CaseCode],
				RTRIM(ISNULL(DEL.[HANDLER],'')) AS [Handler],
				RTRIM(ISNULL(DEL.[TEAM],'')) AS [Team],
				RTRIM(ISNULL(DEL.[FromHandler],'')) AS [From],
				RTRIM(ISNULL(CON.[Name],'')) + CHAR(13) +  RTRIM(ISNULL(DEL.[Description],'')) AS [ClientCase],
				RTRIM(ISNULL(CON.[Name],'')) AS [ClientName],
				RTRIM(ISNULL(DEL.[DisplayText], '')) as [Action],
				CASE
					WHEN DEL.[DATE] != NULL OR DEL.[DATE] != ''
					THEN CONVERT(VARCHAR, DEL.[DATE], 20)
				ELSE
					'1900-01-01'
				END                                              AS Date1, 
				ISNULL(DEL.[STATUS], 0) as DStatus,
				RTRIM(ISNULL(DEL.[DelType], '')) AS [DelType],
				RTRIM(ISNULL(DEL.[ACTIONTYPE],'')) as [ActionType],
				RTRIM(ISNULL(DEL.[HIGHLIGHTED], '')) as [Highlighted],
				ISNULL(DEL.diaryACTIONID,0) AS [ActionId],
				RTRIM(ISNULL(DEL.[FNCODE],'')) AS [FNCode],
				RTRIM(ISNULL([HAN].[Name], '')) AS [FNName],
				RTRIM(ISNULL(DEL.[FECode],'')) AS [CaseFe],
				RTRIM(ISNULL(DEL.[PROCESSTYPE],'')) as [ProcessType],
				CASE
					WHEN RTRIM(ISNULL(DEL.[OWNER], 'N')) = 'Y'
					THEN 'Y'
					ELSE 'N'
				END AS [Owner],
				ISNULL(DEL.[DELEGATESTATUS],0) as [DelegateStatus],
				ISNULL(DEL.[PROCESSSTATUS],0) as [ProcessStatus],
				ISNULL(DEL.[WORKPROCESS],0) as [WorkProcess],
				ISNULL(DEL.[DELEGATIONSTATUS],0) as [DelegationStatus],
				ISNULL(DEL.[ASSIGNNO], 0) AS [AssignNo],
				CASE
					WHEN ISNULL(DEL.[WORKPROCESS],0) = 1 AND ISNULL(DEL.diarySTATUS, 0) <> 1
					THEN 'G'
					WHEN ISNULL(DEL.diarySTATUS, 0) = 1
					THEN 'C'
					ELSE ''
				END AS [CompleteOrGenerate],
				CASE
					WHEN ISNULL(DEL.[WORKPROCESS],0) = 1 AND ISNULL(DEL.diarySTATUS, 0) <> 1
					THEN 'G'
					WHEN ISNULL(DEL.diarySTATUS, 0) = 1
					THEN 'C'
					ELSE ''
				END AS [CompleteOrGeneratedD],
				CONVERT(VARCHAR, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](CONVERT(DATETIME, '19000101'), DEL.[IMAGENO]), 108) AS [Duration],
				ISNULL(DEL.[Flag],0) AS [Flag],
				CASE
					WHEN RTRIM(ISNULL(DEL.[ACTIONTYPE], '')) = 'E' AND @ShowFromToSynopsis = 1
					THEN
						CASE
							WHEN ISNULL(DEL.[PROCESSTYPE], 'O') = 'I'
							THEN 'Email From:' + (RTRIM(ISNULL(CAST(DEL.[EMAILADDRESS] AS VARCHAR(50)),''))) + ' - ' + ISNULL(CAST (DEL.[Subject] AS VARCHAR(MAX)),'')
							ELSE 'Email To:' + RTRIM(CAST(ISNULL(DEL.[AddressTo],'') AS VARCHAR(50))) + ' - ' + ISNULL(CAST (DEL.[Subject] AS VARCHAR(MAX)),'')
						END
					ELSE
						CASE
							WHEN DEL.[SUBJECT] IS NULL OR RTRIM(CAST(DEL.[SUBJECT] AS VARCHAR(max))) = '' OR DATALENGTH(DEL.[SUBJECT]) = 0
							THEN
								CASE
									WHEN SUBSTRING(DEL.[DisplayText],0,CHARINDEX (CHAR(13),DEL.[DisplayText])) = ''
									THEN ISNULL(DEL.[TEXT1],'')
									ELSE SUBSTRING(DEL.[DisplayText],0,CHARINDEX (CHAR(13),DEL.[DisplayText]))
								END
							ELSE DEL.[SUBJECT]
						END
				END AS [Synopsis],
				ISNULL(RTRIM(DEL.[User1]),'') AS [User1],
				ISNULL(RTRIM(DEL.[User2]),'') AS [User2],
				ISNULL(RTRIM(DEL.[User3]),'') AS [User3],
				ISNULL(RTRIM(DEL.[YourRef]),'') AS [YourRef],
				CASE
					WHEN DEL.[DUEDATE] != NULL OR DEL.[DUEDATE] != ''
					THEN CONVERT(VARCHAR, DEL.[DUEDATE], 20)
				ELSE
					'1900-01-01'
				END                                              AS [DueDate],
				CONVERT(VARCHAR(5), DEL.[DUEDATE], 108) AS [DueTime],
				ISNULL(RTRIM(DEL.[OldRef]),'') AS [OldRef],
				ISNULL(RTRIM(DEL.[ACTIONCODE]),'') AS [ActionCode],
				CASE
					WHEN SSC.[CODE] IS NULL
					THEN ''
					ELSE RTRIM(SSC.[CODE]) + ' - ' + RTRIM(ISNULL(SSC.[DESCRIPTION], ''))
				END AS [ActionStatus],
				RTRIM(ISNULL(FC.[COLOURDESC], '')) AS [FileColour],
				CASE
					WHEN FC.[RGBColour] = -1
					THEN 'Transparent'
					ELSE RTRIM(ISNULL(FC.[ForegroundColour], 'Transparent'))
				END AS [BackgroundColour],
				ISNULL(DEL.[DRAFTBILLNO],0) AS [DraftBillNo],
				ISNULL(TA.[DESC],'') AS [ActionTitle],
				ISNULL(T.[WKDESC],'') AS [WorkFlow],
				CASE
					WHEN ISNUMERIC(DEL.[DYStartTime]) = 0
					THEN 0
					ELSE ISNULL(CONVERT(INT, CONVERT(DECIMAL, DEL.[DYSTARTTIME])), 0)
				END AS [DYStartTime],
				CASE
					WHEN ISNUMERIC(DEL.[DYEndTime]) = 0
					THEN 0
					ELSE ISNULL(CONVERT(INT, CONVERT(DECIMAL, DEL.[DYENDTIME])), 0)
				END AS [DYEndTime],
				RTRIM(ISNULL(FEE.[NAME], '')) AS [FeeEarner],
				RTRIM(ISNULL(SEC.[NAME], '')) AS [Secretary],
				RTRIM(ISNULL(PAR.[NAME], '')) AS [Partner],
				RTRIM(ISNULL(DEL.[Description], '')) AS [MatterDescription],
				ISNULL(DEL.[CreationDate],CONVERT(DATETIME, DEL.diaryDATE)) AS [CreationDate],
				ISNULL(DEL.[Delegatedfnr],'') as DelegatedFE,
				RTRIM(ISNULL(TA.[Arrangement],''))      AS [Arrangement],
				RTRIM(ISNULL(DEL.[ChargeArrangement],''))      AS [ChargeArrangement]
			FROM @DELS DEL
				INNER JOIN [dbo].[Contacts] CON WITH(NOLOCK)
					ON CON.[Code] = DEL.[ClientCode]
				LEFT OUTER JOIN [dbo].[FileColours] FC WITH(NOLOCK)
					ON FC.[COLOURCODE] = DEL.[FileColour]
				LEFT OUTER JOIN [dbo].[MatterNETPrivileges] MNP WITH(NOLOCK)
					ON MNP.[MATTER] = DEL.[CASECODE]
				LEFT OUTER JOIN [dbo].[Handlers] FEE WITH(NOLOCK)
					ON FEE.[CODE] = DEL.[FECode]
				LEFT OUTER JOIN [dbo].[Handlers] SEC WITH(NOLOCK)
					ON SEC.[CODE] = DEL.[Secretary]
				LEFT OUTER JOIN [dbo].[Handlers] PAR WITH(NOLOCK)
					ON PAR.[CODE] = DEL.[Partner]
				
				LEFT OUTER JOIN [dbo].[StatusCodes] SSC WITH(NOLOCK)
					ON SSC.[CODE] = DEL.[ACTIONSTATUS]
				
				LEFT OUTER JOIN [TemplateActions] TA WITH(NOLOCK) ON  TA.[ACTIONCODE] =DEL.[ACTIONCODE]  
				LEFT OUTER JOIN [Templates] T  WITH(NOLOCK) ON T.[WKCODE] = TA.[WKTCODE]
				LEFT OUTER JOIN [dbo].[Handlers] [HAN] WITH(NOLOCK)	ON  [HAN].[CODE] =DEL.[FNCODE]
			ORDER BY [Row_Number]
			
				
			IF EXISTS(SELECT  Top 1  TotalRowsCount FROM @DELS)
				BEGIN
					SELECT  Top 1 @TotalRecords = TotalRowsCount FROM @DELS;
				END
			ELSE
				BEGIN
				SET @TotalRecords = 0;
				END

	SELECT
		@userprompt1 = ISNULL(RTRIM([USERPROMPT1]),'USERPROMPT1'),
		@userprompt2 = ISNULL(RTRIM([USERPROMPT2]),'USERPROMPT2'),
		@userprompt3 = ISNULL(RTRIM([USERPROMPT3]),'USERPROMPT3')
	FROM [dbo].[CONTROL] CTL

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

CREATE PROCEDURE
       [dbo].[KEYHM_GetTaskRate]
      (@TaskCode VARCHAR(6))
AS
/*******************************************************************************************************
* This procedure is used to get default value from TaskCodes										   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetTaskRate]											           *
* Copied from			: [dbo].[ky_NETGetTaskRate]										               *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-05-23	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN

SELECT [TCD].[Default]
  FROM [TasksCodes] [TCD]
 WHERE [TCD].[CODE] = @TaskCode
END

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

CREATE PROCEDURE
       [dbo].[KEYHM_GetTasksCodes]
       (@PostDay         BIT,
        @Code            VARCHAR(20),
        @HandlerCode     VARCHAR(10))
AS
/*******************************************************************************************************
* Used to list the Tasks Codes.																		   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetTasksCodes]												   *
* Copied from			: [dbo].[ky_NETGetTasksCodes2] in ky_NETGetTasksCodes	                       *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-26    Vinodhan K        Created                                                              *
*******************************************************************************************************/
BEGIN

SET @PostDay     = ISNULL(@PostDay, 1)
SET @Code        = ISNULL(@Code, '')
SET @HandlerCode = ISNULL(@HandlerCode, '')

IF(@PostDay = 1)
  BEGIN
    IF @HandlerCode = ''
      BEGIN
        SELECT RTRIM(ISNULL([TAC].[CODE], '')) AS [TaskType],
               RTRIM(ISNULL([TAC].[DESC], '')) AS [Description]
          FROM [dbo].[TasksCodes] [TAC]
         WHERE ISNULL([TAC].[Retired], 0) <> 1
      END
    ELSE
      BEGIN
        SELECT RTRIM(ISNULL([TAC].[CODE], '')) AS [TaskType],
               RTRIM(ISNULL([TAC].[DESC], '')) AS [Description]
          FROM [dbo].[TasksCodes] [TAC]
         WHERE ISNULL([TAC].[Retired], 0) <> 1
            OR [TAC].[CODE] = @HandlerCode
      END
  END
ELSE
  BEGIN
    IF(@Code = '')
      BEGIN
        IF @HandlerCode = ''
          BEGIN
            SELECT RTRIM(ISNULL([TAC].[CODE], '')) AS [TaskType],
                   RTRIM(ISNULL([TAC].[DESC], '')) AS [Description]
              FROM [dbo].[TasksCodes] [TAC]
             WHERE RTRIM(ISNULL([TAC].[Department], '')) = ''
               AND ISNULL([TAC].[Retired], 0) <> 1
          END
        ELSE
          BEGIN
            SELECT RTRIM(ISNULL([TAC].[CODE], '')) AS [TaskType],
                   RTRIM(ISNULL([TAC].[DESC], '')) AS [Description]
              FROM [dbo].[TasksCodes] [TAC]
             WHERE RTRIM(ISNULL([TAC].[Department], '')) = ''
               AND (   ISNULL([TAC].[Retired], 0) <> 1
                    OR [TAC].[CODE] = @HandlerCode)
          END
      END
    ELSE
      BEGIN
        SELECT RTRIM(ISNULL([TAC].[CODE], '')) AS [TaskType],
               RTRIM(ISNULL([TAC].[DESC], '')) AS [Description]
          FROM [dbo].[matters] [MAT]
               LEFT OUTER JOIN [dbo].[WorkTypes] [WKT]
                            ON [WKT].[CODE] = [MAT].[WType]
               INNER JOIN [dbo].[TasksCodes] [TAC]
                       ON (   [TAC].[Department] = [MAT].[Dept]
                           OR RTRIM(ISNULL([TAC].[Department], '')) = '')
                      AND (   (    ISNULL([WKT].[ChildCare], 'N') <> 'Y'
                               AND ISNULL([TAC].[AxleTask], 'N') <> 'Y'
                               AND (   ISNULL([TAC].Retired, 0) <> 1
                                    OR [TAC].[CODE] = @HandlerCode))
                           OR (    ISNULL([WKT].[ChildCare], 'N') = 'Y'
                               AND ISNULL([TAC].[AxleTask], 'N') = 'Y'))
           WHERE [MAT].[Code] = @Code
     END
END
END

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

CREATE PROCEDURE [dbo].[KEYHM_GetTeamLookupList]
AS

/*******************************************************************************************************
*																									   *
* Stored Procedure Name : [dbo].[KEYHM_GetTeamLookupList]											   *
* Copied from			: [dbo].[ky_NETGetTeamLookupList]				                               *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-26    Vinodhan K        Created                                                              *
 *******************************************************************************************************/

BEGIN
    SELECT RTRIM(ISNULL(HAN.[CODE], '')) AS [CODE],
		   RTRIM(ISNULL(HAN.[NAME], '')) AS [NAME],
		   RTRIM(ISNULL(HAN.[DEPT], '')) AS [DEPT],
		   CASE 
			WHEN RTRIM(ISNULL(HAN.[TEAMCODE], 'N')) = 'Y' 
				THEN 'Y' 
			ELSE 'N' 
		   END AS [TEAMCODE]
      FROM [Handlers] HAN
     WHERE RTRIM(ISNULL(HAN.[TEAMCODE], 'N')) = 'Y'
  ORDER BY RTRIM(ISNULL(HAN.[NAME], ''))
END

GO
IF OBJECT_ID(N'KEYHM_GetTimeAdminCodes',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_GetTimeAdminCodes]
GO
CREATE PROCEDURE
       [KEYHM_GetTimeAdminCodes]
       (@Code   VARCHAR(10))
AS 
/*******************************************************************************************************
* This stored procedure is used to FETCH the Time Admin codes for post day book.					   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetTimeAdminCodes]											   *
* Copied from			: [dbo].[Ky_NETGetTimeAdminCodes]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/
BEGIN
SET NOCOUNT ON
    SELECT
		     RTRIM(NCCODE)                    AS [NCCODE],
		     RTRIM(ISNULL([DESCRIPTION],''))  AS [DESCRIPTION]
	  FROM
		     [TimeAdminCodes]
	  WHERE
		     ISNULL([Retired],'N') = 'N'
		     OR NCCODE = @Code
SET NOCOUNT OFF
END
GO
IF OBJECT_ID(N'[KEYHM_GetTimeDayBookDetails]',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_GetTimeDayBookDetails]
GO

/*******************************************************************************************************
* Used to list the Tasks Codes				 														   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetTimeDayBookDetails]										   *
* Copied from			: [dbo].[ky_NETGetTimeDayBookDetails]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/  
  
CREATE PROC [KEYHM_GetTimeDayBookDetails]  
	@RecordID		DECIMAL(17,0)  
AS   
BEGIN  
	SELECT     
		TDB.MATTER    
		,RTRIM(ISNULL(M.[Description],''))		AS [Description]
		,FEEEARN    
		,[DATE]    
		,[TIME]    
		,CASE    
			WHEN [TIME]>59 THEN     
			CAST(FLOOR(([TIME] / 60)) AS VARCHAR(8)) + ':' +     
			RIGHT('0' + CAST(([TIME] % 60) AS VARCHAR(2)), 2)     
		ELSE     
			'00:' + CAST([TIME] AS VARCHAR(30)) END	AS CaseTime     
		,ISNULL(RATE,0) RATE    
		,ISNULL(CHARGE,0)						AS Charge    
		,ISNULL(Task,'')						AS Task
		,TimeOrCharge     
		,RTRIM(ISNULL(TDB.Comment,''))			AS Comment    
		,RTRIM(Name) AS Name     
		,RTRIM(ISNULL(M.[Description],''))		AS MatterDecription    
		,ISNULL(REC_IRR,'C')					AS IsChargeable    
		,ISNULL(NCCCODE,'')						AS AdminCode    
		,ISNULL(TAC.Retired,'N') AS Retired
	FROM     
		[dbo].TimeDayBook  TDB    
		LEFT OUTER JOIN    
		Matters M    
		ON    
		TDB.MATTER=M.Code    
		LEFT OUTER JOIN    
		Contacts C    
		ON    
		SUBSTRING(TDB.MATTER,0,CHARINDEX('/',TDB.MATTER)) =C.Code    
		LEFT OUTER JOIN TimeAdminCodes TAC on TAC.NCCODE =  TDB.NCCCode 
     WHERE    
		RECORDID	=	@RecordID    
END
GO
IF OBJECT_ID(N'KEYHM_GetUserSettings',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KEYHM_GetUserSettings]
GO
CREATE PROCEDURE
       [dbo].[KEYHM_GetUserSettings]
      (@Handler        NVARCHAR(10),    --DO NOT CHANGE, table contains NVARCHAR columns
       @Key            NVARCHAR(100))   --DO NOT CHANGE, table contains NVARCHAR columns
As
/*******************************************************************************************************
* This Procedure is used to Get User Settings value                                                    *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_GetUserSettings]                                                 *
* Copied from			: [dbo].[Ky_NETGetUserSettings]                                                *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-24	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
  SET NOCOUNT ON

   SELECT USS.[Value] 
     FROM [dbo].[UserSettings] USS
    WHERE USS.[Handler] = @Handler 
      AND USS.[Key] = @Key
        
  SET NOCOUNT OFF
END
GO
IF OBJECT_ID(N'KEYHM_GetUTEDayBook', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KEYHM_GetUTEDayBook]
END
GO

CREATE PROCEDURE [dbo].[KEYHM_GetUTEDayBook]    
				  (@FECode		VARCHAR(10),    
				   @Post		CHAR(1)  = 'N',  
				   @Handler		NVARCHAR(10),
				   @RecordId	INT)    
AS  
/*******************************************************************************************************
* Gets the Day Book	for a Record Id													                   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_GetUTEDayBook]												   *
* Copied from			: [dbo].[ky_NETGetMyDayBook]												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-05-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/   
BEGIN    
    
DECLARE @DayBookValue INT    
    
SELECT @DayBookValue = ISNULL(SUM([TDB].[Time]), 0)    
  FROM [dbo].[Timedaybook] [TDB] WITH (NOLOCK)    
 WHERE [TDB].[FeeEarn] = @FECode    
    
IF(@DayBookValue = 0)    
  BEGIN    
    SET @DayBookValue=1    
  END    
    
DECLARE @DAYBOOK TABLE    
       ([Time]				    INT                              NOT NULL,    
        [CaseTime]              VARCHAR(60)                      NOT NULL,    
        [MatterDetails]         VARCHAR(500)                     NOT NULL,    
        [Progress]              INT                              NOT NULL,    
        [StopwatchStatus]       INT                              NOT NULL,    
        [RecordID]              INT                              NOT NULL   PRIMARY KEY,    
        [DATE]                  DATETIME                         NOT NULL,    
        [MATTER]                VARCHAR(20)                      NOT NULL,    
        [DisplayMatter]         VARCHAR(20)                      NOT NULL,    
        [Name]                  VARCHAR(256)                     NOT NULL,    
        [COMMENT]               VARCHAR(1000)                    NOT NULL,    
        [CHARGE]                DECIMAL(10, 2)                   NOT NULL,    
        [TimeOrCharge]          VARCHAR(1)                       NOT NULL,    
        [Post]                  VARCHAR(1)                       NOT NULL)    
    
DECLARE @DAYBOOKSUM TABLE    
       ([id]                    INT             IDENTITY(1, 1)   NOT NULL   PRIMARY KEY,    
        [RecordID]              INT                              NOT NULL,    
        [Time]                  INT                              NOT NULL,    
        [OriginalTime]          INT                              NOT NULL,    
        [TotalTimeMinusOne]     INT                              NOT NULL)    
    
INSERT    
  INTO @DAYBOOK    
      ([Time],    
       [CaseTime],    
       [MatterDetails],    
       [Progress],    
       [StopwatchStatus],    
       [RecordID],    
       [DATE],    
       [MATTER],    
       [DisplayMatter],    
       [Name],    
       [COMMENT],    
       [CHARGE],    
       [TimeOrCharge],    
       [Post])    
  SELECT [TDB].[Time],    
         CASE WHEN [TDB].[Time] < 0    
                   THEN '-'    
              ELSE '' END     
         + 
		 SUBSTRING(CONVERT(VARCHAR, FLOOR(ABS([TDB].[Time]) / 60)),    
                     LEN(CONVERT(VARCHAR, FLOOR(ABS([TDB].[Time]) / 60))) - 2,    
                     3)    
         + ':'    
         + SUBSTRING(CONVERT(VARCHAR, 100 + ABS([TDB].[Time]) % 60),    
                     LEN(CONVERT(VARCHAR, 100 + ABS([TDB].[Time]) % 60)) - 1,    
                     2)                                                                    AS [CaseTime],    
   [dbo].[KEYHM_FN_RemoveSpuriousWhitespace] --2018-03-12    
         (  RTRIM(ISNULL([CON].[Name], ''))    
          + ' '    
          + RTRIM(ISNULL([MAT].[Description], '')), 500)                                   AS [MatterDetails],    
         0                                                                                 AS [Progress],    
         ISNULL([TDB].[StopwatchStatus], 0)                                                AS [StopwatchStatus],    
         [TDB].[RecordID]                                                                  AS [RecordID],    
         [TDB].[Date]                                                                      AS [DATE],    
         [TDB].[Matter]                                                                    AS [Matter],    
         CASE WHEN [TDB].[Matter] = '~'    
                   THEN 'Admin Time'    
              ELSE [TDB].[Matter] END                                                      AS [DisplayMatter],    
         RTRIM(ISNULL([CON].[Name],''))                                                    AS [Name],    
         RTRIM(ISNULL([TDB].[Comment], ''))                                                AS [COMMENT],    
         [TDB].[Charge]                                                                    AS [CHARGE],    
         UPPER([TDB].[TimeOrCharge])                                                       AS [TimeorCharge],    
         CASE WHEN RTRIM(UPPER(ISNULL([TDB].[Post], ''))) = 'N'    
                   THEN 'N'    
              ELSE 'Y' END                                                                 AS [Post]    
    FROM [dbo].[TimeDayBook] [TDB] WITH (NOLOCK)    
      LEFT OUTER JOIN [dbo].[matters] [MAT] WITH (NOLOCK)    
                      ON [MAT].[Code] = [TDB].[Matter]    
         LEFT OUTER JOIN [dbo].[Contacts] [CON] WITH (NOLOCK)    
                      ON [CON].[Code] = [MAT].[ClientCode]    
   WHERE [TDB].[RecordID] = @RecordId 
	 AND [TDB].[FeeEarn] = @FECode
	 AND ISNULL([TDB].[Post], 'Y') IN ('Y', @Post)
    
  INSERT    
    INTO @DAYBOOKSUM    
        ([RecordID],    
         [Time],    
         [OriginalTime],    
         [TotalTimeMinusOne])    
  SELECT [TDB].[RecordID],    
         0,    
         ISNULL([TDB].[Time], 0),    
         0    
    FROM @DAYBOOK [TDB]    
ORDER BY [TDB].[RecordID]    
    
DECLARE @TOTALTIME INT    
SET @TOTALTIME = 0    
    
UPDATE [DBS]    
   SET @TOTALTIME = @TOTALTIME + ISNULL([DBSPREV].[OriginalTime], 0),    
       [DBS].[TotalTimeMinusOne] = @TOTALTIME    
  FROM @DAYBOOKSUM [DBS]    
       LEFT OUTER JOIN @DAYBOOKSUM [DBSPREV]    
                    ON [DBSPREV].[id] = [DBS].[id] - 1    
    
UPDATE [DBS]    
   SET [DBS].[Time] = [DBS].[OriginalTime] + [DBS].[TotalTimeMinusOne]    
  FROM @DAYBOOKSUM [DBS]    
    
-- This will guarantee that the percentages in [Progress] will always add up to exactly 100    
UPDATE [TDB]    
   SET [TDB].[Progress]     
       = CONVERT(INT, ROUND((CONVERT(FLOAT, [TDBS].[Time]) / CONVERT(FLOAT, @DayBookValue)) * CONVERT(FLOAT, 100), 0))                --The current cumulative percentage    
       - CONVERT(INT, ROUND((CONVERT(FLOAT, [TDBS].[Time] - [TDB].[Time]) / CONVERT(FLOAT, @DayBookValue)) * CONVERT(FLOAT, 100), 0)) -- minus the last cumulative percentage    
  FROM @DAYBOOKSUM [TDBS]    
       INNER JOIN @DAYBOOK [TDB]    
               ON [TDB].[RecordID] = [TDBS].[RecordID]    
       --CROSS APPLY (SELECT ISNULL(SUM([TDBP].[Time]), 0) AS [Time]    
       --               FROM @DAYBOOK [TDBP]    
       --              WHERE [TDBP].[RecordID] <= [TDB].[RecordID]) [TDBS]    
    
SELECT [TDB].[Time],    
       [TDB].[CaseTime],    
       [TDB].[MatterDetails],    
       [TDB].[Progress],    
       [TDB].[StopwatchStatus],    
       [TDB].[RecordID],    
       [TDB].[DATE],    
       [TDB].[MATTER],    
       [TDB].[DisplayMatter],    
       [TDB].[Name],    
       [TDB].[COMMENT],    
       [TDB].[CHARGE],    
       [TDB].[TimeOrCharge],    
       [TDB].[Post]    
  FROM @DAYBOOK [TDB]  
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_HandlerIsAuthorisedToControlGroup'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_HandlerIsAuthorisedToControlGroup]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_HandlerIsAuthorisedToControlGroup]
      (@Handler      VARCHAR(10),
       @GroupName    VARCHAR(100))
AS
/*******************************************************************************************************
* Procedure checks whether a particular handler is authorised to use a piece of Framework			   *
* functionality. This can be useful in external components from which the same functionality		   *
* needs to be restricted.																			   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_HandlerIsAuthorisedToControlGroup]							   *
* Copied from			: [dbo].[ky_NETSPHandlerIsAuthorisedToControlGroup]							   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 
BEGIN
DECLARE @IsAuthorised INT

SELECT @IsAuthorised = CASE WHEN COUNT(1) = 0 THEN 1 ELSE 0 END
  FROM [dbo].[KHCtlGroups] [KCG]
       LEFT OUTER JOIN [dbo].[KHCtlHandlers] [ALL]
                    ON [ALL].[Handler] = ''
                   AND [ALL].[groupid] = [KCG].[id]
       LEFT OUTER JOIN [dbo].[KHCtlHandlers] [KHH]
                    ON [KHH].[Handler] = @Handler
                   AND [KHH].[groupid] = [KCG].[id]
 WHERE [KCG].[GroupName] = @GroupName
   AND (   [ALL].[id] IS NOT NULL
        OR [KHH].[id] IS NOT NULL)

SELECT CONVERT(BIT, @IsAuthorised) AS [IsAuthorised]

RETURN @IsAuthorised
END

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

CREATE PROCEDURE 
       [dbo].[KEYHM_InsertDiaryAttachment]
      (@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,
       @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].[KEYHM_InsertDiaryAttachment]                                          *
* Copied from			: [dbo].[ky_NETAAInsertDiaryAttchement]                                        *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-10	Vinodhan K		Created                                                                *
* 2020-05-26    Arun V          Modified the type extension size from 3 to 5                           *
 *******************************************************************************************************/
BEGIN

	SET NOCOUNT OFF

	IF NOT EXISTS
	(SELECT 1 
		FROM [dbo].[DiaryAttachments] DAT
		WHERE DAT.[TRACKREFERENCE] = @TRACKREFERENCE) 
	BEGIN
	SET @FILEPATH = dbo.KEYHM_FN_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 EXISTS(SELECT * FROM diary WHERE ACTIONID = @DIARYID AND ACTIONTYPE = 'U')
		BEGIN
			DECLARE @UserName VARCHAR(20)
			DECLARE @Description VARCHAR(500)
			SET @UserName = (SELECT NAME FROM Handlers WHERE Code = @ENTEREDBY)
			SET @Description = 'Attachment Added: ' + CHAR(13) + CHAR(10)
							+  'Date:  ' + CONVERT(VARCHAR(11),CONVERT(DATETIME,@DATEENTERED),106) + CHAR(13) + CHAR(10)
						+ 'Document Name: ' + @DOCUMENT +CHAR(13) + CHAR(10)
						+ 'Document Class: ' + @DOCCLASS + CHAR(13) + CHAR(10)
			INSERT INTO
				[dbo].[UndertakingLog]
				([UndertakingID],
				[FieldChanges],
				[FromValue],
				[ToValue],
				[ByWho],
				[ModifiedDate])
			VALUES(@DIARYID,
				'New Documents Added',
				@Description,
				' - NIL - ',
				@UserName,
				CONVERT(DATETIME,GETDATE(),112))
		END
               
		SET @Result = @FILEPATH 
		END
		ELSE  
		BEGIN  
			SET @Result = 'NOCHANGE'  
		END  
	END 
	--ELSE 
	--  BEGIN
	--    UPDATE DAT
	--       SET DAT.[TRACKREFERENCE]           =    @TRACKREFERENCE,
	--           DAT.[CASECODE]                 =    @CASECODE,
	--           DAT.[NAME]                     =    @NAME,
	--           DAT.[DOCUMENT]                 =    @DOCUMENT,
	--           DAT.[FILEPATH]                 =    @FILEPATH,
	--           DAT.[TYPE]                     =    @TYPE,
	--           DAT.[DOCCLASS]                 =    @DOCCLASS,
	--           DAT.[DATEENTERED]              =    @DATEENTERED,
	--           DAT.[ENTEREDBY]                =    @ENTEREDBY,
	--           DAT.[LASTACCESSDATE]           =    @LASTACCESSDATE,
	--           DAT.[LASTACCESSBY]             =    @LASTACCESSBY,
	--           DAT.[SYSTEM]                   =    @SYSTEM,
	--           DAT.[DICTATIONFILE]            =    @DICTATIONFILE,
	--           DAT.[Source]                   =    @Source,
	--           DAT.[Fees]                     =    @Fees,
	--           DAT.[Outlay]                   =    @Outlay
	--      FROM [dbo].[DiaryAttachments] DAT
	--     WHERE DAT.[TRACKREFERENCE]           =    @TRACKREFERENCE
	--  END

END
GO
IF OBJECT_ID(N'[KEYHM_InsertIntellisense]',N'P')IS NOT NULL
	DROP PROCEDURE [KEYHM_InsertIntellisense]
GO
CREATE PROCEDURE [KEYHM_InsertIntellisense]      
(      
	@Handler			VARCHAR(6),      
    @Narrative			VARCHAR(100)     
)      
      
AS      
/*******************************************************************************************************
* This procedure is used To insert & update the Intellisense.										   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_InsertIntellisense]											   *
* Copied from			: [dbo].[ky_NETInsertIntellisense]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/
BEGIN      
	SET NOCOUNT ON   
	IF NOT EXISTS(SELECT TOP 1 * FROM Intellisense WHERE Handler = @Handler AND Narrative = @Narrative )
		BEGIN
			INSERT INTO 
				Intellisense
				   ([Handler]
				   ,[Narrative])
			 VALUES
				  (@Handler, 
				  @Narrative )
			SELECT 
				RTRIM(Id) AS Id, 
				RTRIM(Handler) AS Handler, 
				RTRIM(Narrative) AS Narrative
			FROM 
				Intellisense
			WHERE
				Handler = @Handler 
			ORDER by Narrative 
		END	
	ELSE
		BEGIN
			SELECT 
				RTRIM(Id) AS Id, 
				RTRIM(Handler) AS Handler, 
				RTRIM(Narrative) AS Narrative
			FROM 
				Intellisense
			WHERE
				Handler = @Handler 	
			ORDER by Narrative 
		END
	SET NOCOUNT OFF      
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_InsertTasksAction'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_InsertTasksAction]
  END
GO

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

/*******************************************************************************************************
* This sp used to insert blank action.																   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_InsertTasksAction]											   *
* Copied from			: [dbo].[ky_NETInsertTasksAction]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
*******************************************************************************************************/ 

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

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

    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,
           null,
           null,
           @FNCODE,
           @TEAMCODE,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           null,
           @TIMECONVERT,
           @TIMECONVERT,
           0,
           @ACTIONID,
           0,
           null,
           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 EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_ModifyDiaryDetails'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_ModifyDiaryDetails]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_ModifyDiaryDetails]
      (@CASECODE                 VARCHAR(20),
       @DATE                     DATETIME,
       @STATUS                   SMALLINT,
       @ACTIONCODE               VARCHAR(15),
       @ACTIONSTATUS             VARCHAR(3),
       @ACTIONTYPE               VARCHAR(1),
       @PROCESSTYPE              VARCHAR(1),
       @FNCODE                   VARCHAR(10),
       @TEAMCODE                 VARCHAR(10),
       @TEXT1                    VARCHAR(MAX),
       @TEXT2                    VARCHAR(MAX),
       @DELEGATEDFNR             VARCHAR(10),
       @DELEGATEDDATE            DATETIME,
       @DELEGATEDBACKDATE        DATETIME,
       @DEFERRED                 VARCHAR(3),
       @DUEDATE                  DATETIME,
       @PUBLISH                  VARCHAR(1),
       @DYSTARTTIME              DATETIME,
       @DYENDTIME                DATETIME,
       @DURATION                 NVARCHAR(20),
       @ACTIONID                 BIGINT,
       @ORGINALACTIONID          BIGINT,
       @PRIORITY                 VARCHAR(1),
       @HIGHLIGHTED              VARCHAR(1),
       @MILESTEONETYPE           VARCHAR(12),
       @ATTACHMENTS              VARCHAR(1),
       @PROCESSSTATUS            SMALLINT,
       @WORKPROCESS              SMALLINT,
       @BILLABLE                 VARCHAR(1),
       @BILLDESCRIPTION          VARCHAR(150),
       @EMAILADDRESS             VARCHAR(150),
       @ADDRESSTO                VARCHAR(150),
       @CCTo                     VARCHAR(150),
       @BCCTo                    VARCHAR(150),
       @EMAIL                    VARCHAR(1),
       @SUBJECT                  VARCHAR(150),
       @DELEGATIONSTATUS         INT,
       @DRAFTBILLNO              INT,
       @CHEQUEREQNO              INT,
       @TxmSent                  BIT,
       @Location                 VARCHAR(50),
       @HearingType              VARCHAR(50),
       @ForCopy                  VARCHAR(1),
       @TxmDate                  DATETIME,
       @TxmSeqNo                 INT,
       @Flag                     TINYINT,
       @KYC                      VARCHAR(1)='N',
       @Result                   INT = 0 OUTPUT )
AS
/*******************************************************************************************************
* This stored procedure is used to insert or update the Client Case Action information. If ID is       * 
* already exist then it will update that record. otherwise new record will insert.					   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_ModifyDiaryDetails]											   *
* Copied from			: [dbo].[ky_NETCCModifyDiaryDetails]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
* 2019-11-28	Arun			have fixed UTC  conversion issue                                       *
*******************************************************************************************************/ 
BEGIN
SET NOCOUNT ON

DECLARE @TIMECONVERT INT
SET @TIMECONVERT =   dbo.ky_ConvertTimeToClarion(dbo.KEYHM_FNConvertDateToUTC(@DYSTARTTIME, @FNCODE))
--SET @TIMECONVERT = dbo.ky_ConvertTimeToClarion(@DYSTARTTIME  AT TIME ZONE dbo.KEYHM_FNGetHandlerTimeZone(@FNCODE) AT TIME ZONE 'UTC')
DECLARE @ENDTIME INT
SET @ENDTIME = dbo.ky_ConvertTimeToClarion(dbo.KEYHM_FNConvertDateToUTC(@DYENDTIME, @FNCODE))
--SET @ENDTIME = dbo.ky_ConvertTimeToClarion(@DYENDTIME  AT TIME ZONE dbo.KEYHM_FNGetHandlerTimeZone(@FNCODE) AT TIME ZONE 'UTC')


DECLARE @DisplaytextValue VARCHAR(220)

SET @DisplaytextValue = [dbo].[KEYHM_FN_RemoveSpuriousWhitespace](ISNULL(@TEXT1, ''), 200)

--Creating temporary VARIABLE to get value based on actioncode
DECLARE @ACTIONCATEGORY1 VARCHAR(1),
@PUBLISHER1 VARCHAR(1) ,
@PROCEESSTYPE1 VARCHAR(1) ,
@HIGTLIGHTED1 VARCHAR(1) ,
@BILLABLE1 VARCHAR(1) ,
@KYC1 VARCHAR(1) 

SELECT @ACTIONCATEGORY1 = ACTIONCATEGORY , @PUBLISHER1 = PUBLISHER ,@PROCEESSTYPE1 = PROCESSTYPE ,
@HIGTLIGHTED1=HIGHLIGHTED,@BILLABLE1= BILLABLE ,@KYC1= KYC 
 FROM [TEMPLATEACTIONS] where ACTIONCODE=@ACTIONCODE

 
IF(@ACTIONTYPE ='' or @ACTIONTYPE is null)
BEGIN 
  SET @ACTIONTYPE=@ACTIONCATEGORY1
END

IF(@PUBLISH =''  or @PUBLISH is null)
BEGIN 
  SET @PUBLISH=@PUBLISHER1
END

IF(@PROCESSTYPE ='' or  @PROCESSTYPE is null)
BEGIN 
  SET @PROCESSTYPE=@PROCEESSTYPE1
END

IF(@HIGHLIGHTED ='' or @HIGHLIGHTED is null)
BEGIN 
  SET @HIGHLIGHTED=@HIGTLIGHTED1
END

IF(@BILLABLE ='' or @BILLABLE  is null)
BEGIN 
  SET @BILLABLE=(IIF(@BILLABLE1='Y',1,0))
END

IF(@KYC ='' or @KYC is null)
BEGIN 
  SET @KYC=@KYC1
END




UPDATE DIA
   SET [CASECODE]       = @CASECODE,
       [DATE]           = dbo.KEYHM_FNConvertDateToUTC(@DATE, @FNCODE),
       [STATUS]         = @STATUS,
       [ACTIONCODE]     = @ACTIONCODE,
       [ACTIONSTATUS]   = @ACTIONSTATUS,
       [ACTIONTYPE]     = @ACTIONTYPE,
       [FNCODE]         = @FNCODE,
       [TEAMCODE]       = @TEAMCODE,
       [TEXT1]          = @TEXT1,
       [TEXT2]          = @TEXT2,
       [DUEDATE]        = dbo.KEYHM_FNConvertDateToUTC(@DUEDATE, @FNCODE),
       [PUBLISH]        = @PUBLISH,
       [DYSTARTTIME]    = @TIMECONVERT,
       [DYENDTIME]      = @ENDTIME,
       [PRIORITY]       = @PRIORITY,
       [HIGHLIGHTED]    = @HIGHLIGHTED,
       [MILESTEONETYPE] = @MILESTEONETYPE,
       [WORKPROCESS]    = @WORKPROCESS,
       [BILLABLE]       = @BILLABLE,
       [SUBJECT]        = @SUBJECT,
       [TxmSent]        = @TxmSent,
       [Location]       = @Location,
       [HearingType]    = @HearingType,
       [DisplayText]    = @DisplaytextValue,
       [Flag]           = @Flag,
       [KYC]            = @KYC,
	   [IMAGENO]		= dbo.ky_ConvertTimeToClarion(@DURATION)
  FROM [dbo].[diary] DIA
 WHERE DIA.[ACTIONID] = @ACTIONID

UPDATE DEL
   SET DEL.[HANDLER]    = @FNCODE,
       DEL.[DELEGATE]   = @FNCODE,
       DEL.[TEAM]       = @TEAMCODE
  FROM [dbo].[DiaryDelegations] DEL
 WHERE DEL.[ACTIONID]   = @ACTIONID
   AND DEL.[OWNER]      = 'Y'

UPDATE DEL
   SET DEL.[ActionType] = @ACTIONTYPE,
       DEL.[DATE]       =  dbo.KEYHM_FNConvertDateToUTC(@DATE, @FNCODE),
       DEL.[DUEDATE]    = dbo.KEYHM_FNConvertDateToUTC(@DUEDATE, @FNCODE)
  FROM [dbo].[DiaryDelegations] DEL
 WHERE DEL.[ACTIONID]   = @ACTIONID
   AND DEL.[STATUS]      = 0

IF (@STATUS = 0)
  BEGIN
    UPDATE DEL
       SET DEL.[STATUS]     = 0
      FROM [dbo].[DiaryDelegations] DEL
     WHERE DEL.[ACTIONID]   = @ACTIONID
       AND DEL.[OWNER]      = 'Y'
  END
ELSE
  BEGIN
    UPDATE DEL
       SET DEL.[STATUS]     = 1
      FROM [dbo].[DiaryDelegations] DEL
     WHERE DEL.[ACTIONID]   = @ACTIONID
  END


SET @Result = @ACTIONID
SET NOCOUNT OFF
END

GO

IF OBJECT_ID('[dbo].[KEYHM_NetWorkingDays]') IS NOT NULL
	DROP FUNCTION [dbo].[KEYHM_NetWorkingDays]
GO

CREATE FUNCTION [dbo].[KEYHM_NetWorkingDays] (
       @FROMDATE DATETIME,
       @TODATE   DATETIME) 
RETURNS INT
AS
/*******************************************************************************************************
* Returns number of total working days between two dates.											   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_NetWorkingDays]			                                       *
* Copied from			: [dbo].[ky_NETNetWorkingDays]				                                   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-16	Vinodhan K		Created                                                                *
 *******************************************************************************************************/ 
BEGIN
	DECLARE @I     INT 
	DECLARE @COUNT INT
	DECLARE @DIFF  INT

	SELECT @DIFF = DATEDIFF(D, @FROMDATE, @TODATE),
	       @I = 0,
	       @COUNT = 0
	
	WHILE(@I < @DIFF)
	BEGIN
		SELECT @COUNT = @COUNT + 1 
		 WHERE DATENAME(DW, DATEADD(D, @I, @FROMDATE)) NOT IN ('Saturday','Sunday')
		
		   SET @I = @I + 1
	END

	RETURN @COUNT
END

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

CREATE PROCEDURE
       [dbo].[KEYHM_OutlayBalanceDrilldown]
      (@Handler VARCHAR(10),
	   @PageNumber		INT          = NULL,
	   @PageSize		INT          = NULL,
	   @SearchText		VARCHAR(100) = '',
	   @SortColumn		VARCHAR(20)  = '',
	   @SortDirection	VARCHAR(10)  = '')
AS
/**************************************************************************************************
 *
 * Details the values that make up the Outlay Balance in ky_NETDashboard
 *
 * Stored procedure name : KEYHM_OutlayBalanceDrilldown
 * Copied from           : ky_NETOutlayBalanceDrilldown
 *
 * Modification History
 * 2015-06-24   Pino Carafa      Created
 * 2015-11-25   John Ginnane     Formatting balance so negative balances are wrapped in parenthese
 * 2016-01-11	John Ginnane     Undone previous changes as VB .NET handles this 
 * 2019-22-04   Vinodhan K		 Created KAAS_OutlayBalanceDrilldown
 *
 ***************************************************************************************************/
BEGIN

DECLARE @NCOMMAND NVARCHAR(MAX)

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(@SortColumn = '' OR @SortColumn = NULL)
BEGIN
	SET @SortColumn = 'Row_Number'
END
IF(@SortDirection = '' OR @SortDirection = NULL)
BEGIN
	SET @SortDirection = 'ASC'
END

IF [dbo].[ISSAM4]() = 0
  BEGIN
    SET @NCOMMAND = N'
	SELECT 
	    IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#OutlayBalanceSAM3Table
	FROM
	    (
         SELECT RTRIM(ISNULL(MAT.[CODE], ''''))         AS [Code],
              RTRIM(ISNULL(CON.[NAME], ''''))           AS [ClientName],
              RTRIM(ISNULL(MAT.[Description], ''''))    AS [Description],
              ISNULL(MAT.[OutlayBal], 0)				AS [OutlayBalance],
              ISNULL(MAT.[ClientBal], 0)				AS [ClientACBalance]
         FROM [dbo].[matters] MAT
              INNER JOIN [dbo].[contacts] CON
                      ON CON.[code] = MAT.[clientcode]
         WHERE
		      (
	           RTRIM(LTRIM(@SearchText)) = ''''
	           OR
	           (
		       [MAT].[CODE] LIKE ''%' + @SearchText + '%''
		       OR
		       [CON].[NAME] LIKE ''%' + @SearchText + '%''
		       OR
		       [MAT].[Description] LIKE ''%' + @SearchText + '%''
		       OR
		       [MAT].[OutlayBal] LIKE ''%' + @SearchText + '%''
		       OR
		       [MAT].[ClientBal] LIKE ''%' + @SearchText + '%''
	           )
		      )
		      AND MAT.[FECode] = @Handler
              AND MAT.[Closed] <> ''Y''
              AND MAT.[OutlayBal] <> 0) AS FoundTable
		 ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
	        *
	     FROM
	        #OutlayBalanceSAM3Table
	     WHERE
	     (
	     	@StartRow IS NULL
	     	OR
	     	(
	     		[Row_Number] BETWEEN @StartRow AND @EndRow		
	     	)
	     )

	    SELECT
	    	(COUNT([Row_Number])) AS TotalRecords
	    FROM
		    #OutlayBalanceSAM3Table'
  END
ELSE
  BEGIN
    SET @NCOMMAND = N'
    SELECT 
	    IDENTITY(INT, 1,1) AS [Row_Number],
		*
	INTO
		#OutlayBalanceSAM4Table
	FROM
	    (SELECT RTRIM(ISNULL(OBL.[CODE], ''''))          AS [Code],
       RTRIM(ISNULL(CON.[NAME], ''''))          AS [ClientName],
       RTRIM(ISNULL(MAT.[Description], ''''))   AS [MatterDescription],
       ISNULL(OBL.[OutlayBalance], 0)			AS [OutlayBalance],
       ISNULL(OBL.[ClientACBalance], 0)			AS [ClientACBalance]
    FROM (  SELECT MT1.[Code],
                 ISNULL(SUM(ISNULL(TRN.[OutlayValue], 0)), 0) AS [OutlayBalance],
                 ISNULL(SUM(ISNULL(TRN.[ClientCurrent], 0) + ISNULL(TRN.[ClientDeposit], 0)), 0) AS [ClientACBalance]
            FROM [dbo].[matters] MT1
                 INNER JOIN [dbo].[Transactions] TRN
                         ON TRN.[MatterCode] = MT1.[Code]
                        AND (   (    (TRN.[Posted] = ''Y'')
                                 AND (TRN.[RecType] <> ''V'')
                                 AND (TRN.[CorrectionInd] = ''L''))
                             OR (    (TRN.[Posted] IS NULL)
                                 AND (TRN.[RecType] IS NULL)
                                 AND (TRN.[CorrectionInd] IS NULL)))
           WHERE MT1.[FECode] = @Handler
             AND MT1.[Closed] <> ''Y''
        GROUP BY MT1.[Code]) OBL
       INNER JOIN [dbo].[matters] MAT
                  INNER JOIN [dbo].[contacts] CON
                          ON CON.[code] = MAT.[clientcode]
               ON MAT.[code] = OBL.[code]
   WHERE
    (
     RTRIM(LTRIM(@SearchText)) = ''''
     OR
     (
     [OBL].[CODE] LIKE ''%' + @SearchText + '%''
     OR
     [CON].[NAME] LIKE ''%' + @SearchText + '%''
     OR
     [MAT].[Description] LIKE ''%' + @SearchText + '%''
     OR
     [OBL].[OutlayBalance] LIKE ''%' + @SearchText + '%''
     OR
     [OBL].[ClientACBalance] LIKE ''%' + @SearchText + '%''
     )
    )
    AND ISNULL(OBL.[OutlayBalance], 0) <> 0) AS FoundTable
    ORDER BY ' + @SortColumn + ' ' + @SortDirection + ' SELECT
     *
    FROM
       #OutlayBalanceSAM4Table
    WHERE
    (
    	@StartRow IS NULL
    	OR
    	(
    		[Row_Number] BETWEEN @StartRow AND @EndRow		
    	)
    )

    SELECT
    	(COUNT([Row_Number])) AS TotalRecords
    FROM
        #OutlayBalanceSAM4Table'
  END

EXECUTE sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @SearchText VARCHAR(100), @StartRow INT, @EndRow INT', @Handler = @Handler, @SearchText = @SearchText, @StartRow = @StartRow, @EndRow = @EndRow

END

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

CREATE PROCEDURE
       [dbo].[KEYHM_ReseedActionID]
AS

/*******************************************************************************************************
* Dummy Procedure in preparation for the use of the DiarySeed table 								   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_ReseedActionID]												   *
* Copied from			: [dbo].[ky_NETReseedActionID]											       *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

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

CREATE PROCEDURE
       [dbo].[KEYHM_RestartDayBookEntry]
      (@RecordID INT)
AS
/*******************************************************************************************************
* Resets a Day Book's Stopwatch status to 0                                                            *
* Note: In order for this to work, the Fee Earner must NOT have other Daybook Entries with status 0    *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_RestartDayBookEntry]											   *
* Copied from			: [dbo].[ky_NETSPRestartDayBookEntry]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN

DECLARE @FeeEarn VARCHAR(10)

SELECT @FeeEarn = [TDB].[FeeEarn]
  FROM [dbo].[TimeDayBook] [TDB]
 WHERE [TDB].[RecordID] = @RecordID

IF @FeeEarn IS NOT NULL
  IF NOT EXISTS
    (SELECT TOP 1 1
       FROM [dbo].[TimeDayBook] [TDB]
      WHERE [TDB].[FeeEarn] = @FeeEarn
        AND [TDB].[RecordID] <> @RecordID
        AND [TDB].[StopwatchStatus] = 0)
    BEGIN
      UPDATE [TDB]
         SET [TDB].[StopwatchStatus] = 0
        FROM [dbo].[TimeDayBook] [TDB]
       WHERE [TDB].[RecordID] = @RecordID

      SELECT CONVERT(INT, 0) AS [NewStopwatchStatus]
      RETURN
    END

SELECT CONVERT(INT, 1) AS [NewStopwatchStatus]
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'KEYHM_SaveDiaryAttachement'
		 AND SO.[type] = 'P')
	BEGIN
		DROP PROCEDURE [dbo].[KEYHM_SaveDiaryAttachement]
	END

	DECLARE @NCOMMAND NVARCHAR(MAX)
	
	SET @NCOMMAND = 
	N'CREATE PROCEDURE [dbo].[KEYHM_SaveDiaryAttachement] (
		@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].[KEYHM_SaveDiaryAttachement]                                            *
	*                                                                                                      *
	* Modification History	:                                                                              *
	* 2019-04-12	Vinodhan K		Created                                                                *
	 *******************************************************************************************************/
	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 EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_SaveDocFolderTree'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_SaveDocFolderTree]
  END
GO

 CREATE PROCEDURE
        [dbo].[KEYHM_SaveDocFolderTree]
       (@folderxml         NVARCHAR(MAX))
AS
/*******************************************************************************************************
* Saves the changes to a folder tree											                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_SaveDocFolderTree]							  				   *
* Copied from			: [dbo].[ky_NETSPSaveDocFolderTree]											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/ 
BEGIN
  DECLARE @iSL INT
  DECLARE @MAX INT

  DECLARE @data TABLE
         ([seq]                       INT              IDENTITY(1, 1)    NOT NULL      PRIMARY KEY,
          [id]                        INT                                NOT NULL,
          [parent]                    INT                                NOT NULL,
          [foldername]                VARCHAR(500)                       NOT NULL,
          [foldericon]                INT                                NOT NULL,
          [newfolder]                 BIT                                NOT NULL,
          [deletefolder]              BIT                                NOT NULL)
          
  BEGIN TRY
  EXEC SP_XML_PREPAREDOCUMENT @iSL OUTPUT, @folderxml
  END TRY
  BEGIN CATCH
  EXEC SP_XML_PREPAREDOCUMENT @iSL OUTPUT, N'<folders/>'
  END CATCH

  INSERT
    INTO @data
        ([id],
         [parent],
         [foldername],
         [foldericon],
         [newfolder],
         [deletefolder])
  SELECT SRC.[id],
         SRC.[parent],
         SRC.[foldername],
         ISNULL(SRC.[foldericon], 1),
         SRC.[newfolder],
         SRC.[deletefolder]
    FROM OPENXML(@iSL, N'folders/folder')
    WITH ([id]                        INT            '@id',
          [parent]                    INT            '@parent',
          [foldername]                VARCHAR(500)   '@foldername',
          [foldericon]                INT            '@foldericon',
          [newfolder]                 BIT            '@newfolder',
          [deletefolder]              BIT            '@deletefolder') SRC

  EXEC SP_XML_REMOVEDOCUMENT @iSL

  SELECT @MAX = ISNULL(MAX([DF].[id]), 0) FROM [dbo].[DocFolders] [DF]

  DECLARE @new TABLE
         ([seq]                       INT              IDENTITY(1, 1)    NOT NULL      PRIMARY KEY,
          [oldid]                     INT                                NOT NULL      UNIQUE NONCLUSTERED,
          [newid]                     INT                                NOT NULL)

  INSERT
    INTO @new
        ([oldid],
         [newid])
  SELECT [DT].[id],
         0
    FROM @data [DT]
   WHERE [DT].[newfolder] = 1

  UPDATE [nw]
     SET [nw].[newid] = @MAX + [nw].[seq]
    FROM @new [NW]

  SET IDENTITY_INSERT [dbo].[DocFolders] ON

  INSERT
    INTO [dbo].[DocFolders]
        ([id],
         [foldername],
         [parent],
         [foldericon])
  SELECT [nw].[newid]                                            AS [id],
         [dt].[foldername]                                       AS [foldername],
         CASE ISNULL([pr].[newid], 0)
              WHEN 0 THEN CASE ISNULL([dt].[parent], 0)
                               WHEN 0 THEN NULL
                               ELSE [dt].[parent] END     
              ELSE [pr].[newid] END                              AS [parent],
         [dt].[foldericon]
    FROM @data [dt]
         INNER JOIN @new [nw]
                 ON [nw].[oldid] = [dt].[id]
         LEFT OUTER JOIN @new [pr]
                      ON [pr].[oldid] = [dt].[parent]

  SET IDENTITY_INSERT [dbo].[DocFolders] OFF

  SELECT @MAX = ISNULL(MAX([DF].[id]), 0) + 1
    FROM [dbo].[DocFolders] [DF]

  DBCC CHECKIDENT('DocFolders', RESEED, @MAX)

  DELETE [DF]
    FROM @data [dt]
         INNER JOIN [dbo].[DocFolders] [DF]
                 ON [DF].[id] = [dt].[id]
   WHERE [dt].[deletefolder] = 1

  UPDATE [DF]
     SET [DF].[foldername] = [dt].[foldername],
         [DF].[parent] = CASE ISNULL([dt].[parent], 0)
                              WHEN 0 THEN NULL
                         ELSE [dt].[parent] END,
         [DF].[foldericon] = [dt].[foldericon]
    FROM @data [dt]
         INNER JOIN [dbo].[DocFolders] [DF]
                 ON [DF].[id] = [dt].[id]
   WHERE [dt].[deletefolder] = 0
     AND [dt].[newfolder] = 0

  DECLARE @newid INT

  SELECT TOP 1
         @newid = ISNULL([nw].[newid], dt.[id])
    FROM @data [dt]
         LEFT OUTER JOIN @new [nw]
                      ON [nw].[oldid] = [dt].[id]

  SELECT @newid [id]

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

CREATE PROCEDURE [dbo].[KEYHM_ScalarXMLDiaryDelegation]
      (@DEL VARCHAR(MAX))
AS
/*******************************************************************************************************
*																									   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_ScalarXMLDiaryDelegation]										   *
* Copied from			: [dbo].[ky_NETSPScalarXMLDiaryDelegation]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN

/*
example

<del actionid="100"
     handler="BR"
     team="GEN"
     date="20251102 11:12:13"
     time="20251102 11:12:13"
     dater="20251102 11:12:13"
     timer="20251102 11:12:13"
     duedate="20251102 11:12:13"
     duetime="20251102 11:12:13"
     review="N"
     owner= "Y"
     delegate="BR"
     delegatestatus="2"
     actiontype="X"
     fromhandler="JJ"
     returnedby="JX"
     deltype="released"
     crruser="bohiss" />

*/

DECLARE @ACTIONID        INT
DECLARE @HANDLER         VARCHAR(10)
DECLARE @TEAM            VARCHAR(10)
DECLARE @DATE            DATETIME
DECLARE @TIME            DATETIME
DECLARE @DATER           DATETIME
DECLARE @TIMER           DATETIME
DECLARE @DUEDATE         DATETIME
DECLARE @DUETIME         DATETIME
DECLARE @REVIEW          VARCHAR(1)
DECLARE @STATUS          SMALLINT
DECLARE @OWNER           VARCHAR(1)
DECLARE @DELEGATE        VARCHAR(10)
DECLARE @DELEGATESTATUS  SMALLINT
DECLARE @ActionType      VARCHAR(1)
DECLARE @FromHandler     VARCHAR(10)
DECLARE @ReturnedBy      VARCHAR(10)
DECLARE @DelType         VARCHAR(15)
DECLARE @CRRUSER         VARCHAR(10)
DECLARE @CURRENTOWNER    VARCHAR(10)
DECLARE @DIARYSTATUS     INT

DECLARE @iSL INT

BEGIN TRY
EXEC sp_xml_preparedocument @iSL OUTPUT, @DEL
END TRY
BEGIN CATCH
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<del/>'
END CATCH

SELECT @ActionID       = [DEL].[ACTIONID],
       @Handler        = [DEL].[HANDLER],
       @Team           = [DEL].[TEAM],
       @Date           = [DEL].[DATE],
       @Time           = [DEL].[TIME],
       @Dater          = [DEL].[DATER],
       @Timer          = [DEL].[TIMER],
       @DueDate        = ISNULL([DEL].[DUEDATE], [DIA].[DUEDATE]),
       @DueTime        = ISNULL([DEL].[DUETIME], [DIA].[DUEDATE]),
       @Review         = CASE [DEL].[REVIEW]
                              WHEN NULL THEN NULL
                              WHEN 'N' THEN 'N'
                              WHEN '' THEN ''
                              WHEN ' ' THEN ''
                              WHEN 'Y' THEN 'Y'
                              ELSE NULL END,
       @Status         = ISNULL([DEL].[STATUS], 0),
       @Owner          = CASE WHEN ISNULL([DEL].[OWNER], 'N') = 'Y'
                                   THEN 'Y'
                              ELSE 'N' END,
       @Delegate       = [DEL].[DELEGATE],
       @DelegateStatus = CASE ISNULL([DEL].[DELEGATESTATUS], 0)
                              WHEN 1 THEN 1
                              WHEN 2 THEN 2
                              ELSE 0 END,
       @ActionType     = ISNULL([DEL].[ACTIONTYPE], [DIA].[ACTIONTYPE]),
       @FromHandler    = ISNULL(ISNULL([DEL].[FROMHANDLER], CDL.[HANDLER]), [DIA].[FNCODE]),
       @ReturnedBy     = [DEL].[RETURNEDBY],
       @DelType        = CASE WHEN [DEL].[DELTYPE] IS NULL THEN NULL
                              WHEN [DEL].[DELTYPE] = 'Completed'
                                   THEN 'Completed'
                              WHEN [DEL].[DELTYPE] = 'Created'
                                   THEN 'Created'
                              WHEN [DEL].[DELTYPE] = 'Delegated'
                                   THEN 'Delegated'
                              WHEN [DEL].[DELTYPE] = 'Processed'
                                   THEN 'Processed'
           WHEN [DEL].[DELTYPE] = 'Released'
                                   THEN 'Released'
                              WHEN [DEL].[DELTYPE] = 'Returned'
                                   THEN 'Returned'
                              ELSE 'Delegated' END,
       @CRRUSER        = [DEL].[CRRUSER],
       @CURRENTOWNER   = ISNULL([CDL].[HANDLER], ''),
       @DIARYSTATUS    = CASE WHEN ISNULL([DIA].[STATUS], 0) = 1
                                   THEN 1
                              ELSE 0 END
  FROM OPENXML(@iSL, N'del')
          WITH ([ACTIONID]         INT                '@actionid',
                [HANDLER]          VARCHAR(10)        '@handler',
                [TEAM]             VARCHAR(10)        '@team',
                [DATE]             DATETIME           '@date',
                [TIME]             DATETIME           '@time',
                [DATER]            DATETIME           '@dater',
                [TIMER]            DATETIME           '@timer',
                [DUEDATE]          DATETIME           '@duedate',
                [DUETIME]          DATETIME           '@duetime',
                [REVIEW]           VARCHAR(1)         '@review',
                [STATUS]           SMALLINT           '@status',
                [OWNER]            VARCHAR(1)         '@owner',
                [DELEGATE]         VARCHAR(10)        '@delegate',
                [DELEGATESTATUS]   SMALLINT           '@delegatestatus',
                [ACTIONTYPE]       VARCHAR(1)         '@actiontype',
                [FROMHANDLER]      VARCHAR(10)        '@fromhandler',
                [RETURNEDBY]       VARCHAR(10)        '@returnedby',
                [DELTYPE]          VARCHAR(15)        '@deltype',
                [CRRUSER]          VARCHAR(15)        '@crruser') [DEL]
     INNER JOIN [dbo].[diary] [DIA]
     LEFT OUTER JOIN [dbo].[DiaryDelegations] [CDL]
     ON [CDL].[ACTIONID] = [DIA].[ACTIONID]
     AND [CDL].[OWNER] = 'Y'
     ON [DIA].[ACTIONID] = [DEL].[ACTIONID]


EXEC sp_xml_removedocument @iSL

DECLARE @AssignNo             INT
DECLARE @TIMECONVERSION       VARCHAR(10)
DECLARE @TIMERCONVERSION      VARCHAR(10)
DECLARE @DUETIMECONVERSION    VARCHAR(10)

IF @ACTIONID IS NULL
  BEGIN
    RETURN -1 -- requested action not found.
  END

SET @DATE = ISNULL(@DATE, GetDate())
SET @TIME = ISNULL(@TIME, @DATE)

SET @DUEDATE = ISNULL(@DUEDATE, GetDate())
SET @DUETIME = ISNULL(@DUETIME, @DUEDATE)
SET @ActionType = ISNULL(@ActionType, 'A')
SET @FromHandler = ISNULL(@FromHandler, 'ADM')
IF @DelType = 'Returned'
  BEGIN
    SET @ReturnedBy = ISNULL(@ReturnedBy, @Handler)
  END
SET @CRRUSER = ISNULL(@CRRUSER, @FromHandler)

SET @status = CASE WHEN ISNULL(@status, 0) = 1 THEN 1 ELSE 0 END

SET @DELEGATE = ISNULL(@DELEGATE, @HANDLER)

SET @DELEGATESTATUS = ISNULL(@DELEGATESTATUS, 0)

SELECT @Team = ISNULL(@Team, HAN.[TEAM])
  FROM [dbo].[Handlers] HAN
 WHERE HAN.[CODE] = @Handler

IF NOT @TIME IS NULL
  BEGIN
    SET @TIMECONVERSION    = dbo.ky_ConvertTimeToClarion(@TIME)
  END

IF NOT @TIMER IS NULL
  BEGIN
    SET @TIMERCONVERSION   = dbo.ky_ConvertTimeToClarion(@TIMER)
  END

IF NOT @DUETIME IS NULL
  BEGIN
    SET @DUETIMECONVERSION = dbo.ky_ConvertTimeToClarion(@DUETIME)
  END

DECLARE @DATER1 DATETIME
SET @DATER1 =  GETDATE()

DECLARE @TIMER1 VARCHAR(20)
SET @TIMER1 =  dbo.ky_ConvertTimeToClarion(GETDATE())

SELECT @AssignNo = ISNULL(MAX([DEL].[AssignNo] + 1),1) 
  FROM [dbo].[DiaryDelegations] [DEL]

-- Check whether authorised to Delegate or Release
IF @DelType IN ('Delegated', 'Released')
  BEGIN
    IF ISNULL(@CRRUSER, '') <> @CURRENTOWNER
      BEGIN
        RETURN -2 --Not Authorised
      END
  END

-- Things to do BEFORE inserting the delegation record
IF ISNULL(@CRRUSER, '') = @CURRENTOWNER
  BEGIN
    IF @DIARYSTATUS = 0
      BEGIN
   IF @DelType = 'Released'
          BEGIN
            UPDATE [DEL]
               SET [DEL].[DATER]            = @DATER1,
                   [DEL].[TIMER]            = @TIMER1,
                   [DEL].[STATUS]           = 1,
                   [DEL].[OWNER]            = 'N',
                   [DEL].[DELEGATESTATUS]   = 1
              FROM [dbo].[DiaryDelegations] [DEL]
             WHERE [DEL].[ACTIONID] = @ACTIONID
               AND [DEL].[OWNER] = 'Y'
          END
      END
  END

--KEYD-3961 - In case a user creates an action and then delegates it twice to the same user,
--            the following statement will stop it showing the same task twice as "outstanding"
--            in that user's task list. Please note: it will NOT prevent the user seeing the
--            same task twice if they choose to look at "completed" actions.
UPDATE [DEL]
   SET [DEL].[STATUS] = 1
  FROM [dbo].[DiaryDelegations] [DEL]
 WHERE [DEL].[ACTIONID] = @ACTIONID
   AND [DEL].[HANDLER] = @HANDLER
   AND ISNULL([DEL].[OWNER], 'N') <> 'Y'
   
   DECLARE @NEWDATE AS DATETIME
   SELECT @NEWDATE= [DATE] 
     FROM Diary 
    WHERE ACTIONID=@ACTIONID

-- the actual insert itself
INSERT
  INTO [dbo].[DiaryDelegations]
      ([ACTIONID],
       [HANDLER],
       [TEAM],
       [DATE],
       [TIME],
       [DATER],
       [TIMER],
       [DUEDATE],
       [DUETIME],
       [REVIEW],
       [STATUS],
       [OWNER],
       [DELEGATE],
       [DELEGATESTATUS],
       [ActionType],
       [FromHandler],
       [ReturnedBy],
       [DelType])
VALUES(@ACTIONID,
       @HANDLER,
       @TEAM,
       @NEWDATE,
       @TIMECONVERSION,
       @DATER,
       @TIMERCONVERSION,
       @DUEDATE,
       @DUETIMECONVERSION,
       @REVIEW,
       @STATUS,
       @OWNER,
       @DELEGATE,
       @DELEGATESTATUS,
       @ACTIONTYPE,
       @FROMHANDLER,
       @RETURNEDBY,
       @DELTYPE)

-- Things to do AFTER inserting the delegation record
IF @DelType = 'Created'
  BEGIN
    -- no other changes required.
    RETURN 0
  END

IF @DelType = 'Delegated'
  BEGIN
    UPDATE [DIA]
       SET [DIA].[DELEGATEDFNR]     = @HANDLER,
           [DIA].[DELEGATEDDATE]    = @DATER,
           [DIA].[DELEGATIONSTATUS] = 1
      FROM [dbo].[diary] [DIA]
     WHERE [DIA].[ACTIONID] = @ACTIONID

    RETURN 0
  END

IF @DelType <> 'Released'
  BEGIN
    RETURN -3 --Unknown request
  END

--Released a completed action
IF @DIARYSTATUS = 1
  BEGIN
    UPDATE [DEL]
       SET [DEL].[STATUS]         = 1,
           [DEL].[DELEGATESTATUS] = 1
      FROM [dbo].[DiaryDelegations] [DEL]
     WHERE [DEL].[ACTIONID] = @ACTIONID
       AND [DEL].[DelType] = 'Released'
 
    UPDATE [DEL]
       SET [DEL].[STATUS]         = 0,
           [DEL].[DELEGATESTATUS] = 0
      FROM [dbo].[DiaryDelegations] [DEL]
     WHERE [DEL].[ACTIONID] = @ACTIONID
       AND [DEL].[DelType] = 'Created'

    UPDATE [DIA]
       SET [DIA].[DATE]          = @NEWDATE,
           [DIA].[FNCODE]        = @HANDLER,
           [DIA].[DELEGATEDFNR]  = @HANDLER,
           [DIA].[DELEGATEDDATE] = @DATER1
      FROM [dbo].[diary] [DIA]
     WHERE [DIA].[ACTIONID] = @ACTIONID

    RETURN 0
  END

--Released an open action
UPDATE [DIA]
   SET [DIA].[DATE]             = @NEWDATE,
       [DIA].[FNCODE]           = @HANDLER,
       [DIA].[DELEGATEDFNR]     = @HANDLER,
       [DIA].[DELEGATIONSTATUS] = 0
  FROM [dbo].[diary] [DIA]
 WHERE [DIA].[ACTIONID] = @ACTIONID

UPDATE [DEL]
   SET [DEL].[DELEGATE] = @HANDLER
  FROM [dbo].[DiaryDelegations] [DEL]
 WHERE [DEL].[ACTIONID] = @ACTIONID
   AND [DEL].[OWNER] = 'Y'

RETURN 0

END
GO
IF NOT EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
    WHERE [SO].[name] = 'RMLBackup'
      AND [SO].[type] = 'U')
  BEGIN
    SELECT *
      INTO [dbo].[RMLBackup]
      FROM [dbo].[RecentMatterList]
  END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
          LEFT OUTER JOIN sys.[columns] [SC]
                       ON [SC].object_id = [SO].object_id
                      AND [SC].[name] = 'UniqueID'
    WHERE [SO].[name] = 'RecentMatterList'
      AND [SO].[type] = 'U'
      AND [SC].[column_id] IS NULL)
  BEGIN
    ALTER TABLE
          [dbo].[RecentMatterList]
      ADD [UniqueID] BIGINT IDENTITY(1, 1) NOT NULL
  END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
          INNER JOIN sys.indexes [SI]
                     INNER JOIN sys.index_columns [IC]
                                INNER JOIN sys.columns [SC]
                                        ON [SC].object_id = [IC].object_id
                                       AND [SC].[column_id] = [IC].[column_id]
                             ON [IC].object_id = [SI].object_id
                            AND [IC].[index_id] = [SI].[index_id]
                  ON [SI].object_id = [SO].object_id
                 AND [SI].[is_primary_key] = 1
    WHERE [SO].[name] = 'RecentMatterList'
      AND [SO].[type] = 'U'
      AND [SC].[name] <> 'UniqueID')
  BEGIN
    DECLARE @NAME NVARCHAR(128)

    SELECT @NAME = CONVERT(NVARCHAR(128), [SI].[name])
      FROM sys.objects [SO]
           INNER JOIN sys.indexes [SI]
                   ON [SI].object_id = [SO].object_id
                  AND [SI].[is_primary_key] = 1
     WHERE [SO].[name] = 'RecentMatterList'
       AND [SO].[type] = 'U'

    DECLARE @COMMAND NVARCHAR(MAX)

    SET @COMMAND = N'ALTER TABLE [dbo].[RecentMatterList] DROP CONSTRAINT [' + @NAME + N']'

    EXEC sp_executesql @COMMAND
  END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
          LEFT OUTER JOIN sys.indexes [SI]
                       ON [SI].object_id = [SO].object_id
                      AND [SI].[is_primary_key] = 1
    WHERE [SO].[name] = 'RecentMatterList'
      AND [SO].[type] = 'U'
      AND [SI].[index_id] IS NULL)
  BEGIN
    ALTER 
    TABLE [dbo].[RecentMatterList]
      ADD CONSTRAINT [PK_RecentMatterList] 
                     PRIMARY KEY CLUSTERED
                    ([UniqueID])
  END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
          LEFT OUTER JOIN sys.indexes [SI]
                       ON [SI].object_id = [SO].object_id
                      AND [SI].[name] = 'IDX_FeeMatter'
    WHERE [SO].[name] = 'RecentMatterList'
      AND [SO].[type] = 'U'
      AND [SI].[index_id] IS NULL)
  BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX
           [IDX_FeeMatter]
        ON [dbo].[RecentMatterList]
          ([FEE],
           [MATTER])
           INCLUDE ([Datefield], [UniqueID])
  END
GO

IF EXISTS
  (SELECT TOP 1 1
     FROM sys.objects [SO]
          LEFT OUTER JOIN sys.indexes [SI]
                       ON [SI].object_id = [SO].object_id
                      AND [SI].[name] = 'IDX_FeeDateDesc'
    WHERE [SO].[name] = 'RecentMatterList'
      AND [SO].[type] = 'U'
      AND [SI].[index_id] IS NULL)
  BEGIN
    CREATE NONCLUSTERED INDEX
           [IDX_FeeDateDesc]
        ON [dbo].[RecentMatterList]
          ([FEE],
           [DateField] DESC)
           INCLUDE ([MATTER], [UniqueID])
  END
GO

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

CREATE PROCEDURE
       [dbo].[KEYHM_SetMostRecentMatter]
      (@handler      VARCHAR(10),
       @matter       VARCHAR(20))
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KEYHM_SetMostRecentMatter]                                                                        *
 *                                                                                                           *
 * Updates the Recent Matter List for a handler. The Handlers table stores the                               *
 * maximum number of Recent Matters to store for each handler. If not SET, the                               *
 * default value is 30.                                                                                      *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * Original:                                -                                                        *   *
 *   * First compatible version:                5.7.2.1                                                  *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History                                                                                      *
 * ????-??-?? ???????????     Created                                                                        *
 * 2014-10-23 Pino Carafa     Remove transaction handling                                                    *
 * 2016-07-22 Pino Carafa     Imported into Framework                                                        *
 * 2016-07-22 Pino Carafa     Add Option (KEEPFIXED PLAN) to prevent unnecessary                             *
 *                            procedure recompiles                                                           *
 * 2018-02-15 Pino Carafa     Modify procedure to prevent problems                                           *
 *                            when the system date/time is changed                                           *
 * 2019-08-29 Arun V          Have included the distinct keyword while inserting                             *
 *                            the records into Recent matter.                                                *
 *                            In case of any duplication, due to repeated call,                              *
 *                            this will remove the duplicate item from the list.                             *
 * 2019-08-29 Pino Carafa     Use Group By and MAX instead of DISTINCT                                       *
 * 2019-08-30 Pino Carafa     Rewrite after change to PK and Indexes                                         *
 * 2019-09-10 Pino Carafa     Minor - not critical - addition of Return 1 to indicate success                *
 * 2019-09-12 Pino Carafa     Instead of updating an existing row I will delete and reinsert so that the     *
 *                            most recent matter gets the latest UniqueID which makes sorting in procedures  *
 *                            that rely on the Recent Matter List more reliable                              *
 *                                                                                                           *
 *************************************************************************************************************/
BEGIN

DECLARE @RMLMax INT

SELECT @RMLMax = [HAN].[NORECENTMATTERS]
  FROM [dbo].[Handlers] [HAN]
 WHERE [HAN].[code] = @handler

SET @RMLMax = CASE WHEN ISNULL(@RMLMax, 0) = 0
                        THEN 30
                   ELSE @RMLMax END

DECLARE @NOW DATETIME
DECLARE @MAXDATE DATETIME

SET @NOW = GETDATE()

DECLARE @UniqueID BIGINT

SELECT @UniqueID = [RML].[UniqueID]
  FROM [dbo].[RecentMatterList] [RML]
 WHERE [RML].[FEE] = @handler
   AND [RML].[MATTER] = @matter

IF @UniqueID IS NOT NULL
  BEGIN
    DELETE [RML]
      FROM [dbo].[RecentMatterList] [RML]
     WHERE [RML].[UniqueID] = @UniqueID
  END

INSERT
  INTO [dbo].[RecentMatterList]
      ([FEE],
       [MATTER],
       [DateField])
VALUES(@handler,
       @matter,
       @NOW)

DECLARE @total INT

-- If @UniqueID is not null we deleted one row and inserted one row, so the total won't have changed.
IF @UniqueID IS NULL
  BEGIN
    SELECT @total = COUNT(1)
      FROM [dbo].[RecentMatterList] [RML]
     WHERE [RML].[FEE] = @handler

    SET @total = ISNULL(@total, 0) - @RMLMax --the number of items we must delete

    -- In theory @total should always be <= 1, but just in case
    WHILE @total > 0
      BEGIN
        SET @UniqueID = NULL

        -- Get the oldest item in the Recent Matter List for this FEE
          SELECT TOP 1
                 @UniqueID = [RML].[UniqueID]
            FROM [dbo].[RecentMatterList] [RML]
           WHERE [RML].[FEE] = @handler
        ORDER BY [RML].[UniqueID] ASC

        IF @UniqueID IS NULL
          BEGIN
            -- In theory this should never happen... but just in case
            SET @total = 0
          END
        ELSE
          BEGIN

            -- and delete the oldest item in the Recent Matter List for this FEE
            DELETE [RML]
              FROM [dbo].[RecentMatterList] [RML]
             WHERE [RML].[UniqueID] = @UniqueID

            SET @total = @total - 1
          END
      END
  END

RETURN 1

END

GO

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

CREATE PROCEDURE
       [dbo].[KEYHM_SetTimeDayBookRateCharge]
      (@recordid      int,
       @TUTNUMVALUE   DECIMAL(17, 2))
AS
/*******************************************************************************************************
* Sets the Rate and Charge values according to the Charge Out Rates indicators and/or				   *
* the Task Code used in the TimeDayBook.															   *	 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_SetTimeDayBookRateCharge]										   *
* Copied from			: [dbo].[ky_NETSetTimeDayBookRateCharge]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN

DECLARE @ACTUALRATE DECIMAL(18, 2)
DECLARE @OverriddenRate BIT

SELECT @ACTUALRATE = CASE WHEN TDB.[Rate] = TDB.[FeeRate]
                            OR TDB.[FeeRate] IS NULL
                               THEN [dbo].[KEYHM_FN_GetDefaultRate](RTRIM(ISNULL(TDB.[Matter], '')),
                                                                RTRIM(ISNULL(TDB.[FeeEarn], '')),
                                                                RTRIM(ISNULL(TDB.[NCCCode], '')),
                                                                RTRIM(ISNULL(TDB.[Task], '')))
                          ELSE TDB.[Rate]
					 END,
       @OverriddenRate = CASE WHEN TDB.[Rate] = TDB.[FeeRate]
                                OR TDB.[FeeRate] IS NULL
                                   THEN 0
                              ELSE  1
						 END
  FROM [dbo].[TimeDayBook] TDB
 WHERE TDB.[RecordID] = @recordid

UPDATE TDB
   SET TDB.[Time] = CASE WHEN TDB.[Time] >= 0
                              THEN Ceiling(TDB.[Time] / @TUTNUMVALUE) * @TUTNUMVALUE
                         ELSE -Ceiling(-TDB.[Time] / @TUTNUMVALUE) * @TUTNUMVALUE
					 END,
       TDB.[RATE] = @ACTUALRATE,
       TDB.[FeeRate] = CASE WHEN @OverriddenRate = 1 
                                 THEN TDB.[FEERate]
                            ELSE @ACTUALRATE
						END,
       TDB.[Charge] = Convert(decimal(10, 2),
                             (  (  CASE WHEN TDB.[Time] >= 0
                                             THEN Ceiling(TDB.[Time] / @TUTNUMVALUE)
                                        ELSE -Ceiling(-TDB.[Time] / @TUTNUMVALUE)
									END
                                 * @TUTNUMVALUE
                                 * @ACTUALRATE)
                              / 60)),
       TDB.[Charged] = Convert(decimal(10, 2),
                              (  (  CASE WHEN TDB.[Time] >= 0
                                              THEN Ceiling(TDB.[Time] / @TUTNUMVALUE)
                                         ELSE -Ceiling(-TDB.[Time] / @TUTNUMVALUE) 
									END
                                  * @TUTNUMVALUE
                                  * @ACTUALRATE)
                               / 60)),
       TDB.[Units] = CASE WHEN TDB.[Time] >= 0
                               THEN Ceiling(TDB.[Time] / @TUTNUMVALUE)
                          ELSE -Ceiling(-TDB.[Time] / @TUTNUMVALUE) 
					 END
  FROM [dbo].[TimeDayBook] TDB
 WHERE TDB.[RECORDID] = @RECORDID

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

CREATE PROCEDURE
       [dbo].[KEYHM_StopAllTimers]
      (@FeeCode VARCHAR(10))
AS
/*******************************************************************************************************
* Sets all Stopwatch Status fields to 1                                                                *
* Please note:this should only be called after login, in order to reset the status of any Time Daybook *
*              entries that may have been left after an unexpected shutdown or crash                   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_StopAllTimers]												   *
* Copied from			: [dbo].[ky_NETSPStopAllTimers]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
  UPDATE [TDB]
     SET [TDB].[StopwatchStatus] = 1
    FROM [dbo].[TimeDayBook] [TDB]
   WHERE [TDB].[FeeEarn] = @FeeCode
END
GO
IF OBJECT_ID(N'KEYHM_TakeAction',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KEYHM_TakeAction]
GO

CREATE PROCEDURE  [dbo].[KEYHM_TakeAction]
(
	@Handler  VARCHAR(10),
	@ActionID INT
)
AS
/*******************************************************************************************************
* Allows a handler to take ownership of an Action. This is equivalent to							   *
* the original owner delegating and releasing the action to this handler.							   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_TakeAction]													   *
* Copied from			: [dbo].[ky_NETSPTakeAction]												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-23    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN

SET NOCOUNT ON

DECLARE @Team VARCHAR(10)
DECLARE @DelegatedToHandler INT
DECLARE @OwnerHandler VARCHAR(10)
DECLARE @DATE DATETIME

SELECT @TEAM = [HAN].[TEAM]
  FROM [dbo].[Handlers] [HAN]
 WHERE [HAN].[CODE] = @Handler

EXEC @DelegatedToHandler = [dbo].[KEYHM_TaskScalarDelegatedToHandler] @Handler, @Actionid

SELECT @OwnerHandler = [DEL].[HANDLER]
  FROM [dbo].[DiaryDelegations] [DEL]
 WHERE DEL.[ACTIONID] = @ACTIONID
   AND DEL.[OWNER] = 'Y'
   AND DEL.[STATUS] = 0

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

IF @OwnerHandler = @Handler
  BEGIN
    RETURN
  END

IF @DelegatedToHandler = 0
  BEGIN
    DECLARE @DelegatedHandler AS VARCHAR(10)
    DECLARE @AssignNumber AS INT
    DECLARE @DelType AS VARCHAR(30)

    --Just getting handler and Assign number to check the handler is TEAM
      SELECT TOP 1
             @DelegatedHandler = [DEL].[HANDLER],
             @AssignNumber     = [DEL].[AssignNo]
        FROM [dbo].[DiaryDelegations] [DEL] 
       WHERE (   [DEL].[DelType] = 'Delegated'
              OR [DEL].[DelType] = 'Released')
			 AND [DEL].[ACTIONID] = @ActionID
    ORDER BY [DEL].[AssignNo] DESC

    IF EXISTS
      (SELECT TOP 1 1
         FROM [dbo].[Handlers] [HAN]
        WHERE [HAN].[CODE] = @DelegatedHandler
          AND [HAN].[TEAMCODE] = 'Y')
      BEGIN
        UPDATE [DEL]
           SET [DEL].[HANDLER] = @Handler,
               @DelType = [DEL].[DelType]
          FROM [dbo].[DiaryDelegations] [DEL]
         WHERE (DelType='Delegated' or DelType='Released') AND ACTIONID=@ActionID AND AssignNo = @AssignNumber

        IF (@DelType = 'Released') --FeeCode will only changed when Delegate Type is Released
          BEGIN
            UPDATE [DIA]
               SET [DIA].[FNCODE] = @Handler,
                   [DIA].[DELEGATEDFNR] = @Handler
              FROM [dbo].[diary] [DIA] 
             WHERE [DIA].[ACTIONID] = @ActionID
          END
      END
    ELSE
      BEGIN
        DECLARE @DEL VARCHAR(MAX)

        SET @DEL = CONVERT(VARCHAR(MAX),
                           (SELECT *
                              FROM (SELECT CONVERT(VARCHAR(10), @ActionID) AS [actionid],
                                    @Handler                               AS [handler],
                                    @Team                                  AS [team],
                                    @DATE                                  AS [date],
                                    @DATE                                  AS [time],
                                    'Y'                                    AS [owner],
                                    @OwnerHandler                          AS [delegate],
                                    @OwnerHandler                          AS [fromhandler],
                                    'Released'                             AS [deltype]) [del]
                               FOR XML AUTO))

        DECLARE @DELSuccess INT

        EXEC @DELSuccess = [dbo].[KEYHM_ScalarXMLDiaryDelegation] @DEL

        IF @DELSuccess = 0
          BEGIN
            SET @DelegatedToHandler = 1
          END
      END

  END
ELSE
  BEGIN
    UPDATE [DEL]
       SET [DEL].[STATUS]              = 1,
           [DEL].[OWNER]               = 'N',
           [DEL].[DelegateStatus]      = 1
      FROM [dbo].[DiaryDelegations] [DEL]
     WHERE [DEL].[ACTIONID] = @ACTIONID
       AND [DEL].[OWNER] = 'Y'
       AND [DEL].[STATUS] = 0

    UPDATE [DEL]
       SET [DEL].[OWNER]               = 'Y',
           [DEL].[DELEGATE]            = @Handler,
           [DEL].[DelType]             = 'Released'
      FROM [dbo].[DiaryDelegations] [DEL]
     WHERE [DEL].[ACTIONID] = @ACTIONID
       AND [DEL].[STATUS] = 0
       AND [DEL].[OWNER] = 'N'
       AND [DEL].[HANDLER] = @Handler

    UPDATE [DIA]
       SET [DIA].[FNCODE] = @Handler,
           [DIA].[DELEGATEDFNR] = @Handler,
           [DIA].[DELEGATIONSTATUS] = 0
      FROM [dbo].[diary] [DIA]
     WHERE [DIA].[ACTIONID] = @ActionID
  END


SET NOCOUNT OFF

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

CREATE PROCEDURE [dbo].[KEYHM_TaskCompleteAction2]
      (@ActionID          INT,
       @CurFee            VARCHAR(10),
       @CurTeam           VARCHAR(10),
       @NextActionsXML    VARCHAR(4000),
       @TakeOwnership     INT,
       @HoldDate          BIT=0,
       @Arrangement       VARCHAR(5))
AS
/*******************************************************************************************************
* This stored procedure used to task complete action												   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_TaskCompleteAction2]											   *
* Copied from			: [dbo].[ky_NETTaskCompleteAction2]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
SET NOCOUNT ON

    DECLARE @Now                             DATETIME
    DECLARE @NowDateOnly                     DATETIME
    DECLARE @NowClarionTime                  CHAR(10)
    DECLARE @NowClarionEndTime               CHAR(10)
    DECLARE @Continue                        INT

    DECLARE @Owner                           INT

    DECLARE @IsAuthorisedToComplete          INT
    DECLARE @CountFailedDependentActions     INT
    DECLARE @idoc                            INT

    DECLARE @VCActionID                      VARCHAR(50)
    DECLARE @MaxActionID                     INT
    DECLARE @LocDel                          VARCHAR(10)
    DECLARE @WorkProcess                     INT
    DECLARE @ErrorMsgTable Table
           ([ErrorMsg]  VARCHAR(500))

    DECLARE @NA TABLE
           ([ID]          INT identity(1, 1),
            [ActionID]    INT,
            [Code]        VARCHAR(5),
            [Date]          DATETIME)

    DECLARE @AlarmType INT
    DECLARE @DisabledAlarmStatusID INT
    DECLARE @ActionTypeID INT

    SET XACT_ABORT ON
    
    

    SELECT @AlarmType = ISNULL(ALT1.[TypeID], ALT2.[TypeID])
      FROM [dbo].[AlarmTypes] ALT2
           LEFT OUTER JOIN [dbo].[AlarmTypes] ALT1
                        ON ALT1.[Description] = 'Action'
     WHERE ALT2.[Description] = 'Generic Alarm'

    SELECT @DisabledAlarmStatusID = IsNull(ALS2.[StatusID], ALS1.[StatusID])
      FROM [dbo].[AlarmStatus] ALS1
           LEFT OUTER JOIN [dbo].[AlarmStatus] ALS2
                        ON ALS2.[Description] = convert(VARCHAR(500), 'Actioned')
     WHERE ALS1.[Description] = 'Disabled'

    SELECT @ActionTypeID = ALT1.[TypeID]
      FROM [dbo].[AlarmTypes] ALT1
     WHERE ALT1.[Description] = 'Action'

    IF (RTRIM(ISNULL(@CurTeam,'')) = '')
      BEGIN
        SELECT @CurTeam = HAN.[TEAM]
          FROM [dbo].[Handlers] HAN
         WHERE HAN.[CODE] = @CurFee
      END

/* If @Continue is SET to a value other than zero at any point during this process,
   stop processing further data, and make sure that the transaction at the END is rolled back */
    SET @Continue = 0

/* Some processes are dependent on the current fee handler being the owner of the action
   that is to be completed, others require that the action is/isn't a phone call or e-mail */
    SELECT @Owner = CASE DIA.[FNCODE]
                         WHEN @CurFee
                              THEN 1
                         ELSE 0 END,
           @WorkProcess = ISNULL(DIA.[WORKPROCESS], 0)
      FROM [dbo].[Diary] DIA
     WHERE DIA.[ACTIONID] = @ActionID

    IF (@TakeOwnership = 1)
      SET @Owner = 1

/* Check that this fee earner is authorised to complete this action. Note that this should
   also be checked by the client application, before calling this procedure, but we should
   still check it here in case this somehow gets invoked while bypassing the client checks. */

--SELECT @IsAuthorisedToComplete = [IsAuthorisedToComplete]
--  FROM [dbo].[ky_WDActionAuthorisedToComplete](@ActionID, @CurFee)
     BEGIN
      INSERT
        INTO @ErrorMsgTable
            (ErrorMsg)
      SELECT CASE RTRIM(ISNULL(TAC.[AuthorisationRequired], 'L'))
                  WHEN ''
                       THEN 'Cont'
                  WHEN 'L'
                       THEN 'Cont'
                  WHEN 'C'
                       THEN CASE WHEN RTRIM(ISNULL(MAT.[FECode], '')) = @CurFee
                                      THEN 'Cont'
                                 ELSE 'You are not authorised to complete this action. The f/e for this case is required to complete this action.' END
                  WHEN 'P'
                       THEN CASE WHEN RTRIM(ISNULL(MAT.[Partner], '')) = @CurFee
                                      THEN 'Cont'
                                 ELSE 'You are not authorised to complete this action. The Partner for this case is required complete this ation.' END
                  WHEN 'F'
                       THEN CASE WHEN RTRIM(ISNULL(CNT.[FE], '')) = @CurFee
                                      THEN 'Cont'
                                 ELSE 'You are not authorised to complete this action. The Partner for this client is required to complete this action.' END
                  WHEN 'A'
                       THEN CASE WHEN RTRIM(ISNULL(CNT.[FE], '')) = @CurFee
                                      THEN 'Cont'
                                 ELSE 'You are not authorised to complete this action. A Partner of the firm is required to complete this action. Recommend you delegate this action to a partner.' END
                  WHEN 'O'
                       THEN CASE WHEN RTRIM(ISNULL(CNT.[FE], '')) = @CurFee
                                      THEN 'Cont'
                                 ELSE 'You are not authorised to complete this action.' END
                  ELSE 'You are not authorised to complete this action.' END
        FROM [dbo].[Diary] DIA
             INNER JOIN [dbo].[matters] MAT
                        INNER JOIN [dbo].[Contacts] CNT
                                ON CNT.[Code] = MAT.[ClientCode]
                     ON MAT.[Code] = DIA.[CASECODE]
             LEFT OUTER JOIN [dbo].[TemplateActions] TAC
                          ON TAC.[ACTIONCODE] = dia.[ACTIONCODE]
             INNER JOIN [dbo].[Handlers] FHA
                     ON FHA.[CODE] = @CurFee
       WHERE DIA.[ACTIONID] = @ActionID
     END

/* IF not authorised, do not do anything ELSE */
    IF ((SELECT Top 1 ErrorMsg FROM @ErrorMsgTable)<>'Cont')
    BEGIN
      SET @Continue = 1
    END
    ELSE
    BEGIN
      DELETE FROM @ErrorMsgTable
    END


IF (@Continue = 0)
  BEGIN

    /* this function returns error messages for each dependent action that has not been
       completed within the required timeframe. This should also be checked in the client
       application, and it should display the error messages returned by this function. Here
       it suffices to make sure there are 0 messages before we proceed. */
    --SELECT @CountFailedDependentActions = COUNT(1)
    --  FROM [dbo].[ky_WDActionCheckDependentActions](@ActionID)

    /* If there are any messages, do not continue */

    INSERT
      INTO @ErrorMsgTable
          ([ErrorMsg])
    SELECT CONVERT(VARCHAR(1000),
                     RTRIM(ISNULL(DPA.[DependentActionDescription], '')
                   + ' must be complete')
                   + CASE WHEN ISNULL(DPA.[TimeFrame], '') = 'Any Time'
                               THEN ''
                          WHEN ISNULL(DPA.[TimeFramAmount], 0) <= 0
                               THEN ''
                          ELSE   ' (within a timeframe of '
                               + CONVERT(VARCHAR(4), convert(INT, ISNULL(DPA.[TimeFramAmount], 0)))
                               + ' '
                               + ISNULL(DPA.[TimeFrame], 0)
                               + ')' END
                   + ' before you can complete this action') AS [ErrorMessage]
      FROM [dbo].[Diary] DIA
           OUTER APPLY (SELECT TDA.[ActionCode],
                               TDA.[DependentActionCode],
                               TDA.[TimeFramAmount],
                               TDA.[TimeFrame],
                               TDA.[Status],
                               RTRIM(ISNULL(TAD.[DESC], '')) AS [DependentActionDescription]
                          FROM [dbo].[TemplateDependentActions] TDA
                               INNER JOIN [dbo].[TemplateActions] TAD
                                       ON TAD.[ACTIONCODE] = TDA.[DependentActionCode]
                         WHERE TDA.[ActionCode] = DIA.[ActionCode]) DPA
           OUTER APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[diary] DEPA
                         WHERE DEPA.[CASECODE] = DIA.[CASECODE]
                           AND DEPA.[ACTIONCODE] = DPA.[DependentActionCode]
                           AND DEPA.[STATUS] = 1
                           AND DEPA.[DATE] >= CASE WHEN DPA.[TimeFrame] = 'Any Time'
                                                        THEN CONVERT(DATETIME, '18010101')
                                                   WHEN DPA.[TimeFrame] = 'Day(s)'
                                                        THEN DATEADD(DD, -DPA.[TimeFramAmount], DIA.[DATE])
                                                   WHEN DPA.[TimeFrame] = 'Week(s)'
                                                        THEN DATEADD(WK, -DPA.[TimeFramAmount], DIA.[DATE])
                                                   WHEN DPA.[TimeFrame] = 'Month(s)'
                                                        THEN DATEADD(MM, -DPA.[TimeFramAmount], DIA.[DATE])
                                                   WHEN DPA.[TimeFrame] = 'Year(s)'
                                                        THEN DATEADD(YY, -DPA.[TimeFramAmount], DIA.[DATE])
                                                   ELSE CONVERT(DATETIME, '18010101') END) FON
     WHERE DIA.[ACTIONID] = @ActionID
       AND DPA.[ActionCode] IS NOT NULL
       AND FON.[TOTAL] = 0

    IF (SELECT COUNT(*) FROM @ErrorMsgTable) <> 0
      BEGIN
        SET @Continue =1
      END



  END
-- END IF (@Continue = 0)

/* now all the checks are done, we are going to make actual database changes. All this should
   be atomic so we wrap the whole lot into a transaction */
BEGIN TRANSACTION

BEGIN TRY
  BEGIN
    IF (@Continue = 0)
      BEGIN
        /* some date and time variables that may be used in several of the updates that follow */
          -- full date/time
        IF @HoldDate=0
            BEGIN
                SET @Now = GETDATE()
                -- date only, time SET to 00:00:00
                SET @NowDateOnly = convert(DATETIME, convert(VARCHAR, @Now, 112))
                -- Clarion compliant representation of the Time part of the date/time
                SET @NowClarionTime = convert(CHAR(10), [dbo].[ky_ConvertTimeToClarion](@Now))
                SET @NowClarionEndTime = convert(CHAR(10), [dbo].[ky_ConvertTimeToClarion](dateadd(mi, 30, @Now)))
            END
        ELSE
            BEGIN
                SET @Now = (SELECT [DATE] FROM Diary WHERE ACTIONID =@ActionID )
                -- date only, time SET to 00:00:00
                SET @NowDateOnly = convert(DATETIME, convert(VARCHAR, @Now, 112))
                -- Clarion compliant representation of the Time part of the date/time
                SET @NowClarionTime = convert(CHAR(10), [dbo].[ky_ConvertTimeToClarion](@Now))
                SET @NowClarionEndTime = convert(CHAR(10), [dbo].[ky_ConvertTimeToClarion](dateadd(mi, 30, @Now)))
            END


        SELECT
            @LocDel = DEL.[DELEGATE]
        FROM
            [dbo].[DiaryDelegations] DEL
        WHERE
            DEL.[ACTIONID] = @ActionID
        AND
            DEL.[HANDLER] = @CurFee
        AND
            ISNULL(DEL.[STATUS], 0) = 0

        IF (@@ERROR <> 0)
          BEGIN
            /* this will eventually lead to a rollback */
            SET @Continue = 1
          END
        -- END IF (@@ERROR <> 0)


        /* update all Diary delegation records that were assigned to the current handler */
        UPDATE
            DEL
        SET
            DEL.[DATER] = @NowDateOnly,
            DEL.[TIMER] = @NowClarionTime,
            DEL.[STATUS] = 1
        FROM
            [dbo].[DiaryDelegations] DEL
       WHERE
            DEL.[ACTIONID] = @ActionID
           AND DEL.[HANDLER] = @CurFee
           AND IsNull(DEL.[Status], 0) = 0

        IF (@@ERROR <> 0)
          BEGIN
            /* this will eventually lead to a rollback */
            SET @Continue = 1
          END
        -- END IF (@@ERROR <> 0)

        IF (@Owner = 1)
          BEGIN

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* Phone and E-mail records */
                UPDATE
                        DIA
                   SET
                        DIA.[STATUS] = 1,
                        DIA.[PROCESSSTATUS] = 0,
                        DIA.[FNCODE] = CASE WHEN @TakeOwnership = 1 THEN @CurFee ELSE DIA.[FNCODE] END,
                        DIA.[TEAMCODE] = CASE WHEN @TakeOwnership = 1 THEN @CurTeam ELSE DIA.[TEAMCODE] END
                  FROM
                        [dbo].[Diary] DIA
                 WHERE
                        DIA.[ACTIONID] = @ActionID
                 --AND
                 --       ISNULL(DIA.[ACTIONTYPE],'') NOT IN ('A','D','S') -- Pino 2015-10-12, add 'D' (Dictations) to exceptions

              IF (@@ERROR <> 0)
              BEGIN
                /* this will eventually lead to a rollback */
                SET @Continue = 1
              END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* If it is a normal Action, update some date information, too */
                UPDATE DIA
                   SET DIA.[STATUS] = 1,
                       DIA.[PROCESSSTATUS] = 0,
                       DIA.[DATE] = @Now,
                       DIA.[DYSTARTTIME] = @NowClarionTime,
                       DIA.[DYENDTIME] = @NowClarionEndTime,
                       DIA.[FNCODE] = CASE WHEN @TakeOwnership = 1 THEN @CurFee ELSE DIA.[FNCODE] END,
                       DIA.[TEAMCODE] = CASE WHEN @TakeOwnership = 1 THEN @CurTeam ELSE DIA.[TEAMCODE] END
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID
                  -- AND IsNull(DIA.[ACTIONTYPE], '') IN ('A', 'D','S')  -- Pino 2015-10-12, do this also for Dictations ('D')

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                SET @VCActionID = convert(VARCHAR(50), @ActionID)

                /* Better to keep these updates in-line since we're wrapping it all
                   into a transaction;
                   we don't want to introduce further complications with calls to
                   external procedures that update the database at this point.

                  Originally:
                  EXEC [dbo].[ky_SetLinkedAlarms] 'Actioned', 'Action', @VCActionID */

                UPDATE ALM
                   SET ALM.[Status] = @DisabledAlarmStatusID
                  FROM [dbo].[Alarms] ALM
                 WHERE ALM.[Type] = @ActionTypeID
                   AND ALM.[LinkID] = @VCActionID

                IF (@@ERROR <> 0)
              BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* When applicable, make sure that the Matter status reflects the status
                   of this completed action */
                --UPDATE MAT
                --   SET MAT.[Status] = TAC.[STATUS]
                --  FROM [dbo].[Diary] DIA
                --       INNER JOIN [dbo].[matters] MAT
                --               ON MAT.[Code] = DIA.[CASECODE]
                --       INNER JOIN [dbo].[TemplateActions] TAC
                --               ON TAC.[ACTIONCODE] = DIA.[ACTIONCODE]
                --              AND ISNULL(TAC.[STATUS], '') NOT IN ('NA', 'N/A', '')
                -- WHERE DIA.[ACTIONID] = @ActionID

               UPDATE MAT
                   SET MAT.[Status] = DIA.[ACTIONSTATUS]
                  FROM [dbo].[Diary] DIA
                       INNER JOIN [dbo].[matters] MAT
                               ON MAT.[Code] = DIA.[CASECODE]
                              AND ISNULL(DIA.[ACTIONSTATUS], '') NOT IN ('NA', 'N/A', '')
                 WHERE DIA.[ACTIONID] = @ActionID




                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* Update Case Master */
                UPDATE CSM
                   SET CSM.[CSDATELASTACN_DATE] = @NowDateOnly
                  FROM [dbo].[Diary] DIA
                       INNER JOIN [dbo].[CaseMaster] CSM
                               ON CSM.[CSCODE] = DIA.[CASECODE]
                 WHERE DIA.[ACTIONID] = @ActionID

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* Example of @NextActionsXML:
                   <NA>
                     <NextAction>
                       <Process>Y</Process>
                       <Decision>Do</Decision>
                       <Code>XXX</Code>
                       <Date>XXX</Date>
                     </NextAction>
                     <NextAction>
                       <Process>Y</Process>
                       <Decision>Do not</Decision>
                       <Code>YYY</Code>
                       <Date>YYY</Date>
                     </NextAction>
                     <NextAction>
                       <Process>N</Process>
                        <Decision>Do</Decision>
                       <Code>ZZZ</Code>
                       <Date>ZZZ</Date>
                     </NextAction>
                   </NA>
                */
                EXEC sp_xml_preparedocument @idoc OUTPUT, @NextActionsXML

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

                IF (@Continue = 0)
                  BEGIN
                    SELECT @Continue = COUNT(1)
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [Date]      DATETIME) NA
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[TemplateActions] TAC
                                   ON TAC.[ACTIONCODE] = NA.[Code]
                                  AND TAC.[AssignActionTo] = 'P'
                           INNER JOIN [dbo].[Handlers] HAN
                                   ON HAN.[CODE] = @CurFee
                           INNER JOIN [dbo].[matters] MAT
                                      INNER JOIN [dbo].[Contacts] CNT
                                              ON CNT.[Code] = MAT.[ClientCode]
                                   ON MAT.[Code] = DIA.[CASECODE]
                                  AND RTRIM(ISNULL(MAT.[Partner], '')) = ''
                     WHERE NA.[Process] = 'Y'
                       AND NA.[Decision] = 'Do'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */
                    -- Delete next actions flagged AS "Do Not". First, Diary Delegations:
                    DELETE DSL
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [Date]      DATETIME) BLCH
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[Diary] DS
                                      INNER JOIN [dbo].[DiaryDelegations] DSL
                                              ON DSL.[ACTIONID] = DS.[ACTIONID]
                                   ON DS.[CASECODE] = DIA.[CASECODE]
                                  AND DS.[ACTIONCODE] = BLCH.[Code]
                                  AND DS.[STATUS] = 0
                     WHERE BLCH.[Process] = 'Y'
                       AND BLCH.[Decision] = 'Do not'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */
                    -- Delete next actions flagged AS "Do Not". Second, OlApptXRef:
                    DELETE DOL
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [Date]      DATETIME) BLCH
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[Diary] DS
                                      INNER JOIN [dbo].[OLApptXref] DOL
                                              ON DOL.[ACTIONID] = DS.[ACTIONID]
                                   ON DS.[CASECODE] = DIA.[CASECODE]
                                  AND DS.[ACTIONCODE] = BLCH.[Code]
                                  AND DS.[STATUS] = 0
                     WHERE BLCH.[Process] = 'Y'
                       AND BLCH.[Decision] = 'Do not'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */
                    -- Delete next actions flagged AS "Do Not". Third, DiaryAttachments:
                    DELETE DAT
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [Date]      DATETIME) BLCH
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[Diary] DS
                                      INNER JOIN [dbo].[DiaryAttachments] DAT
                                              ON DAT.[DiaryID] = DS.[ACTIONID]
                                   ON DS.[CASECODE] = DIA.[CASECODE]
                                  AND DS.[ACTIONCODE] = BLCH.[Code]
                                  AND DS.[STATUS] = 0
                     WHERE BLCH.[Process] = 'Y'
                       AND BLCH.[Decision] = 'Do not'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */
                    -- Delete next actions flagged AS "Do Not". Fourth, DiaryLinks:
                    DELETE DLK
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [Date]      DATETIME) BLCH
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[Diary] DS
                                      INNER JOIN [dbo].[DiaryLinks] DLK
                                              ON DLK.[ACTIONID] = DS.[ACTIONID]
                                   ON DS.[CASECODE] = DIA.[CASECODE]
                                  AND DS.[ACTIONCODE] = BLCH.[Code]
                                  AND DS.[STATUS] = 0
                     WHERE BLCH.[Process] = 'Y'
                       AND BLCH.[Decision] = 'Do not'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */
                    -- Delete next actions flagged AS "Do Not". Fifth, DiaryTemp:
                    DELETE DTM
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [Date]      DATETIME) BLCH
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[Diary] DS
                                      INNER JOIN [dbo].[DiaryTemp] DTM
                                              ON DTM.[ACTIONID] = DS.[ACTIONID]
                                   ON DS.[CASECODE] = DIA.[CASECODE]
                                  AND DS.[ACTIONCODE] = BLCH.[Code]
                                  AND DS.[STATUS] = 0
                     WHERE BLCH.[Process] = 'Y'
                       AND BLCH.[Decision] = 'Do not'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */

                    -- Delete next actions flagged AS "Do Not". Second, the actual Diary entries:
                    DELETE DS
                      FROM OPENXML(@idoc, 'NA/NextAction', 2)
                              WITH([Process]   VARCHAR(1)    'Process',
                                   [Decision]  VARCHAR(10)   'Decision',
                                   [Code]      VARCHAR(5)    'Code',
                                   [DATE]      DATETIME) BLCH
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[Diary] DS
                                   ON DS.[CASECODE] = DIA.[CASECODE]
                                  AND DS.[ACTIONCODE] = BLCH.[Code]
                                  AND DS.[STATUS] = 0
                     WHERE BLCH.[Process] = 'Y'
                       AND BLCH.[Decision] = 'Do not'

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)
                  END
                -- END IF (@Continue = 0)

                /* Create new Actions based on the TemplateNextAction entries that are
                   flagged AS "Do"s.

                   As this involves a number of steps, we'll use a temporary table @NA
                   (nextactions) that will hold the newly created Action IDs.
                   We can then use that AS a basis for all following INSERT and UPDATE
                   statements ensuring that all Diary / DiaryDelegation (etc) entries are
                   correctly linked within this transaction.
                */
                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */

                    --Pino 2015-09-30 Start
                    EXEC @MaxActionID = [dbo].[KEYHM_GetNextActionID]
                    SET @MaxActionID = @MaxActionID - 1
                    --SELECT @MaxActionID = IsNull(MAX(DIA.[ActionID]), 0)
                    --  FROM [dbo].[Diary] DIA
                    --Pino 2015-09-30 Start

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)

                    IF (@Continue = 0)
                      BEGIN
                        INSERT
                          INTO @NA
                              ([ActionID],
                               [Code],
                               [Date])
                        SELECT @MaxActionID,
                               BLCH.[Code],
                               [Date]
                          FROM OPENXML(@idoc, 'NA/NextAction', 2)
                                  WITH(Process   VARCHAR(1)    'Process',
                                       Decision  VARCHAR(10)   'Decision',
                                       Code      VARCHAR(5)    'Code',
                                       [Date]    DATETIME) BLCH
                         WHERE BLCH.[Process] = 'Y'
                           AND BLCH.[Decision] = 'Do'

                        IF (@@ERROR <> 0)
                          BEGIN
                            /* this will eventually lead to a rollback */
                            SET @Continue = 1
                          END
                        -- END IF (@@ERROR <> 0)

                      END
                    -- END IF (@Continue = 0)

                  END
                -- END IF (@Continue = 0)

                EXEC sp_xml_removedocument @idoc

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */

                    UPDATE @NA SET [ActionID] = [ActionID] + [ID]

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)

                  END
                -- END IF (@Continue = 0)

                IF (@Continue = 0)
                  BEGIN
                    /* top condition: (@Owner = 1) / NextActions */

                    /* The following is based on the original Clarion
                       AddDiaryStep procedure (in CaseFun)

                       Based on the NextActions in the temporary @NA table this code will:
                       - Create new Diary entries,
                       - Add their DiaryDelegation records,
                       - Set the Linked Alarm
                       - Update CaseMaster with the last added Diary Work Type

                       ADDDIARYSTEP - START
                    */
                    INSERT
                      INTO [dbo].[Diary]
                          ([ActionID],
                           [CASECODE],
                           [DATE],
                           [STATUS],
                           [ACTIONSTATUS],
                           [ACTIONCODE],
                           [ACTIONTYPE],
                           [FnCode],
                           [TeamCode],
                           [Text1],
                           [Displaytext],
                           [DYStartTime],
                           [DYEndTime],
                           [DueDate],
                           [ImageNo],
                           [Publish],
                           [Priority],
                           [Highlighted],
                           [Billable],
                           [ProcessStatus],
                           [BillDescription],
                           [MILESTEONETYPE],
                           [ORGINALACTIONID],
                           [DraftBillNo],
                           [Subject])
                    SELECT NA.[ActionID],
                           DIA.[CASECODE] AS [CASECODE],
                           --[dbo].[ky_WDGetDate](@Now,
                           --                     TNA.[WHENTYPE],
                           --                     TNA.[WHEN]) AS [DATE],
                            NA.[Date] AS [DATE],
                           0 AS [STATUS],
                           TAC.[STATUS] AS [ACTIONSTATUS],
                           NA.[Code] AS [ACTIONCODE],
                           TAC.[ACTIONCATEGORY] AS [ACTIONTYPE],
                           CASE TAC.[AssignActionTo]
                                WHEN 'C'
                                     THEN MAT.[FECode]
                                WHEN 'P'
                                     THEN MAT.[Partner]
                                WHEN 'F'
                                     THEN CNT.[FE]
                                WHEN 'O'
                                     THEN TAC.[ASSIGNHANDLER]
                                ELSE @CurFee END AS [FnCode],
                           CASE TAC.[AssignTeamActionTo]
                                WHEN 'O'
                                     THEN TAC.[ASSIGNTEAM]
                                ELSE HAN.[TEAM] END AS [TeamCode],
                           TAC.[DESC] AS [Text1],
                           [dbo].[KEYHM_FN_RemoveSpuriousWhitespace](ISNULL(CONVERT(VARCHAR(MAX), TAC.[DESC]), ''), 200) AS [Displaytext],
                           @NowClarionTime AS [DYStartTime],
                           @NowClarionEndTime AS [DYEndTime],
                           --[dbo].[ky_WDGetDate](@NowDateOnly,
                           --                     TNA.[WHENTYPE],
                           --                     TNA.[WHEN]) AS [DueDate],
                           NA.[Date] AS [DueDate],
                           0 As [ImageNo],
                           TAC.[PUBLISHER] AS [Publish],
                           IsNull(SUBSTRING(TAC.[PRIORITY], 1, 1), 'N') As [Priority],
                           TAC.[HIGHLIGHTED] As [Highlighted],
                           CASE TAC.[BILLABLE]
                                WHEN 'Y'
                                     THEN 1
                                ELSE 0 END As [Billable],
                           0 As [ProcessStatus],
                           TAC.[BILLDESCRIPTION] AS [BillDescription],
                           CASE TAC.[AssignActionTo]
                                WHEN 'C'
                                     THEN MAT.[FECode]
                                WHEN 'P'
                                     THEN MAT.[Partner]
                                WHEN 'F'
                                     THEN CNT.[FE]
                                WHEN 'O'
                                     THEN TAC.[ASSIGNHANDLER]
                                ELSE @CurFee END AS [MilestoneType],
                           @ActionID As [OriginalActionID],
                           0 As [DraftBillNo],
                           CASE WHEN SUBSTRING(TAC.[DESC],0,CHARINDEX (CHAR(13),TAC.[DESC]))= '' THEN TAC.[DESC]
                                ELSE SUBSTRING(TAC.[DESC],0,CHARINDEX (CHAR(13),TAC.[DESC]))
                                END

                      FROM @NA NA
                           INNER JOIN [dbo].[Diary] DIA
                                   ON DIA.[ACTIONID] = @ActionID
                           INNER JOIN [dbo].[TemplateActions] TAC
                                   ON TAC.[ACTIONCODE] = NA.[Code]
                           INNER JOIN [dbo].[TemplateNextActions] TNA
                                   ON TNA.[ACTION] = DIA.[ACTIONCODE]
                                  AND TNA.[NEXTACTION] = NA.[Code]
                           INNER JOIN [dbo].[Handlers] HAN
                                   ON HAN.[CODE] = @CurFee
                           INNER JOIN [dbo].[matters] MAT
                                      INNER JOIN [dbo].[Contacts] CNT
                                              ON CNT.[Code] = MAT.[ClientCode]
                                   ON MAT.[Code] = DIA.[CASECODE]

                    IF (@@ERROR <> 0)
                      BEGIN
                        /* this will eventually lead to a rollback */
                        SET @Continue = 1
                      END
                    -- END IF (@@ERROR <> 0)

                    --Pino 2015-09-30 Start
                    --reseed
                    EXEC [dbo].[KEYHM_ReseedActionID]
                    --EXEC @MaxActionID = [dbo].[KEYHM_GetNextActionID]
                    --Pino 2015-09-30 Start

                    IF (@Continue = 0)
                      BEGIN
                        /* top condition: (@Owner = 1) / NextActions / AddDiaryStep */

                        INSERT
                          INTO [dbo].[DiaryDelegations]
                              ([ACTIONID],
                               [HANDLER],
                               [TEAM],
                               [DATE],
                               [TIME],
                               [DUEDATE],
                               [DUETIME],
                               [STATUS],
                               [OWNER],
                               [DELEGATE],
                               [ACTIONTYPE],
                               [DelType],
                               [FromHandler])
                        SELECT DIA.[ACTIONID] AS [ACTIONID],
                               CASE WHEN @TakeOwnership = 1 THEN @CurFee ELSE DIA.[FNCODE] END AS [HANDLER],
                               CASE WHEN @TakeOwnership = 1 THEN @CurTeam ELSE DIA.[TEAMCODE] END AS [TEAM],
                               DIA.[DUEDATE] AS [DATE],
                               @NowClarionTime AS [TIME],
                               DIA.[DUEDATE] AS [DUEDATE],
                               @NowClarionTime AS [DUETIME],
                               DIA.[STATUS] AS [STATUS],
                               'Y' AS [OWNER],
                               DIA.[FNCODE] AS [DELEGATE],
                               DIA.[ACTIONTYPE] AS [ACTIONTYPE],
                               'Created' AS [DelType],
                               DIA.[FNCODE] AS [FromHandler]
                          FROM @NA NA
                               INNER JOIN [dbo].[Diary] DIA
                                       ON DIA.[ACTIONID] = NA.[ActionID]

                        IF (@@ERROR <> 0)
                          BEGIN
                            /* this will eventually lead to a rollback */
                            SET @Continue = 1
                          END
                        -- END IF (@@ERROR <> 0)

                      END
                    -- END IF (@Continue = 0)

                    IF (@Continue = 0)
                      BEGIN
                        /* top condition: (@Owner = 1) / NextActions / AddDiaryStep */

                        INSERT
                          INTO [dbo].[Alarms]
                              ([ID],
                               [HandlerCode],
                               [MatterRef],
                               [LinkID],
                               [OriginalDate],
                               [DeferredDate],
                               [Title],
                               [Message],
                               [Type],
                               [Status])
                        SELECT convert(VARCHAR(38), newid()) AS [ID],
                               DEL.[HANDLER] AS [Handler],
                               DIA.[CASECODE] As [MatterRef],
                               convert(VARCHAR(50), NA.[ActionID]) AS [LinkID],
                               DIA.[DATE] As [OriginalDate],
                               DIA.[DATE] As [DeferredDate],
                               CASE WHEN DIA.[ActionType] <> 'E'
                                         THEN ISNULL(RTRIM(SUBSTRING(DIA.[TEXT1], 1, 255)), '')
                                    WHEN DIA.[ProcessType] = 'I'
                                         THEN RTRIM(SUBSTRING(  'Email From:'
                                                              + RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), ''))
                                                              + ' - '
                                                              + ISNULL(SUBSTRING(DIA.[Subject],
                                                                                 1,
                                                                                 255), ''),
                                                    1,
                                                    255))
                                    ELSE RTRIM(SUBSTRING(  'Email To:'
                                                         + RTRIM(ISNULL(SUBSTRING(DIA.[AddressTo],
                                                                                  1,
                                                                                  255), ''))
                                                         + ' - '
                                                         + ISNULL(SUBSTRING(DIA.[Subject],
                                                                            1,
                                                                            255), ''),
                                                         1,
                                                         255)) END AS [Title],
                               RTRIM(SUBSTRING(DIA.[Text1], 1, 8000)) AS [Message],
                               @AlarmType As [Type],
                               ALS.[StatusID] AS [Status]
                          FROM @NA NA
                               INNER JOIN [dbo].[Diary] DIA
                                       ON DIA.[ACTIONID] = NA.[ActionID]
                               INNER JOIN [dbo].[DiaryDelegations] DEL
                                       ON DEL.[ACTIONID] = NA.[ActionID]
                               INNER JOIN [dbo].[AlarmStatus] ALS
                                       ON ALS.[Description] = 'Attention'

                        IF (@@ERROR <> 0)
                          BEGIN
                            /* this will eventually lead to a rollback */
                            SET @Continue = 1
                          END
                        -- END IF (@@ERROR <> 0)

                      END
                    -- END IF (@Continue = 0)

                    IF (@Continue = 0)
                      BEGIN
                        /* top condition: (@Owner = 1) / NextActions / AddDiaryStep */
                        IF NOT ((SELECT RTRIM(ISNULL(T.HoldCasePlan,'N')) FROM templateactions T INNER JOIN Diary D on T.ACTIONCODE = D.ACTIONCODE WHERE D.ACTIONID = @ActionID) = 'Y')
                        BEGIN
                            UPDATE CSM
                            SET CSM.[CSWKTCODE] = TAC.[WKTCODE]
                            FROM ( SELECT MAX(NA.[ActionID]) AS [MaxActionID]
                                   FROM @NA NA) LAID
                               INNER JOIN [dbo].[Diary] DIA
                                          INNER JOIN [dbo].[TemplateActions] TAC
                                                  ON TAC.[ACTIONCODE] = DIA.[ACTIONCODE]
                                       ON DIA.[ACTIONID] = LAID.[MaxActionID]
                               INNER JOIN [dbo].[CaseMaster] CSM
                                       ON CSM.[CSCODE] = DIA.[CASECODE]
                        END
                      END
                    -- END IF (@Continue = 0)

                    /*
                       ADDDIARYSTEP - END
                    */

                  END
            -- END IF (@Continue = 0)
              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* Complete the diary delegations */
                UPDATE DEL
                   SET DEL.[STATUS] = 1,
                       DEL.[HANDLER] = CASE WHEN @TakeOwnership = 1 THEN @CurFee ELSE DEL.[HANDLER] END,
                       DEL.[TEAM] = CASE WHEN @TakeOwnership = 1 THEN @CurTeam ELSE DEL.[TEAM] END,
                       DEL.[DelType] = CASE WHEN (@TakeOwnership = 1) AND (DEL.[DelType] = 'Released') AND (DEL.[FromHandler] = @CurFee) THEN 'Completed' ELSE DEL.[DelType] END
                  FROM [dbo].[DiaryDelegations] DEL
                 WHERE DEL.[ACTIONID] = @ActionID
                   AND IsNull(DEL.[STATUS], 0) <> 1

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 1) */

                /* Write new 'Completed' row to Diary Delegations */
                INSERT
                  INTO [dbo].[DiaryDelegations]
                      ([ACTIONID],
                       [HANDLER],
                       [TEAM],
                       [FromHandler],
                       [ReturnedBy],
                       [DELEGATE],
                       [DATE],
                       [TIME],
                       [STATUS],
                       [DELEGATESTATUS],
                       [DelType])
                SELECT DIA.[ACTIONID],
                       DIA.[FNCODE],
                       DIA.[TEAMCODE],
                       DIA.[FNCODE],
                       DIA.[FNCODE],
                       DIA.FNCODE,
                       @NowDateOnly,
                       @NowClarionTime,
                       1,
                       1,
                       'Completed'
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                   SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)
          END
        -- END IF (@Owner = 1)

        IF (@Owner = 0)
          BEGIN

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 0) */

                /* Return Action */
                UPDATE DIA
                   SET DIA.[DELEGATEDFNR] = @LocDel,
                       DIA.[PROCESSSTATUS] = 0,
                       DIA.[DELEGATIONSTATUS] = CASE WHEN @LocDel = DIA.[FNCODE]
                                                          THEN 2
                                                     ELSE DIA.[DELEGATIONSTATUS] END
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 0) */

                IF (@WorkProcess = 0)
                  BEGIN
                    INSERT
                      INTO [dbo].[DiaryDelegations]
                          ([ACTIONID],
                           [HANDLER],
                           [TEAM],
                           [DATE],
                           [TIME],
                           [TIMER],
                           [DUETIME],
                           [REVIEW],
                           [STATUS],
                           [OWNER],
                           [DELEGATE],
                           [DELEGATESTATUS],
                           [ActionType],
                           [FromHandler],
                           [ReturnedBy],
                           [DelType])
                    SELECT DEL.[ACTIONID],
                           @CurFee As [HANDLER],
                           @CurTeam AS [TEAM],
                           @Now,
                           @NowClarionTime,
                           NULL AS [TIMER],
                           '' AS [DUETIME],
                           '' AS [REVIEW],
                           1 AS [STATUS],
                           '' AS [OWNER],
                           @CurFee AS [DELEGATE],
                           1 As [DELEGATESTATUS],
                           '' AS [ActionType],
                           @CurFee AS [FromHandler],
                           @CurFee AS [ReturnedBy],
                           'Processed' AS [DelType]
                      FROM [dbo].[DiaryDelegations] DEL
                     WHERE DEL.[ACTIONID] = @ActionID
                       AND DEL.[HANDLER] = @LocDel
                       AND DEL.[STATUS] = 0

                    UPDATE DIA
                       SET DIA.[WorkProcess] = 1
                      FROM [dbo].[Diary] DIA
                     WHERE DIA.[ActionID] = @ActionID
                  END

                INSERT
                  INTO [dbo].[DiaryDelegations]
                      ([ACTIONID],
                       [ActionType],
                       [DATE],
                       [DATER],
                       [DELEGATE],
                       [DELEGATESTATUS],
                       [DUEDATE],
                       [DUETIME],
                       [DelType],
                       [FromHandler],
                       [HANDLER],
                       [OWNER],
                       [REVIEW],
                       [ReturnedBy],
                       [STATUS],
                       [TEAM],
                       [TIME],
                       [TIMER])
                SELECT DEL.[ACTIONID],
                       DEL.[ActionType],
                       @Now,
                       @NowDateOnly AS [DATER],
                       DEL.[DELEGATE],
                       2 As [DELEGATESTATUS],
                       DEL.[DUEDATE],
                       DEL.[DUETIME],
                       'Returned' AS [DelType],
                       DEL.[FromHandler],
                       DEL.[HANDLER],
                       DEL.[OWNER],
                       DEL.[REVIEW],
                       @CurFee AS [ReturnedBy],
                       1 AS [STATUS],
                       DEL.[TEAM],
                       @NowClarionTime,
                       @NowClarionTime AS [TIMER]
                  FROM [dbo].[DiaryDelegations] DEL
                 WHERE DEL.[ACTIONID] = @ActionID
                   AND DEL.[HANDLER] = @LocDel
                   AND DEL.[STATUS] = 0

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

            IF (@Continue = 0)
              BEGIN
                /* top condition: (@Owner = 0) */

                UPDATE DEL
                   SET DEL.[DELEGATESTATUS] = 2,
                       DEL.[DATER] = @NowDateOnly,
                       DEL.[TIMER] = @NowClarionTime,
                       DEL.[ReturnedBy] = @CurFee
                  FROM [dbo].[DiaryDelegations] DEL
                 WHERE DEL.[ACTIONID] = @ActionID
                   AND DEL.[HANDLER] = @LocDel
                   AND DEL.[STATUS] = 0

                IF (@@ERROR <> 0)
                  BEGIN
                    /* this will eventually lead to a rollback */
                    SET @Continue = 1
                  END
                -- END IF (@@ERROR <> 0)

              END
            -- END IF (@Continue = 0)

          END
        -- END IF (@Owner = 0)

      END
    -- END IF (@Continue = 0)
  END
END TRY
BEGIN CATCH
  SET @Continue = 1
END CATCH

IF (@Continue = 0)
  BEGIN
    BEGIN TRY
      IF EXISTS (SELECT TOP 1 1
                   FROM [dbo].[DiaryDelegations] [DEL]
                  WHERE [DEL].[ACTIONID] = @ActionID
                    AND [DEL].[STATUS] = 0
                    AND [DEL].[OWNER] = 'Y')
        BEGIN
          UPDATE [DEL]
             SET [DEL].[OWNER] = ''
            FROM [dbo].[DiaryDelegations] [DEL]
           WHERE [DEL].[ACTIONID] = @ActionID
             AND [DEL].[STATUS] = 1
             AND [DEL].[OWNER] = 'Y'
        END
    END TRY
    BEGIN CATCH
      SET @Continue = 1
    END CATCH
  END

IF (@Continue = 0)
  BEGIN
    COMMIT
   SELECT ErrorMsg FROM @ErrorMsgTable
  END
ELSE -- ELSE (IF (@Continue = 0))
  BEGIN
    ROLLBACK
    SELECT ErrorMsg FROM @ErrorMsgTable
  END
-- END IF (@Continue = 0)

IF NOT (@Arrangement = '')
  BEGIN
    UPDATE [MAT]
       SET [MAT].[ChargeArrangement] = @Arrangement,
           [MAT].[CollectingBalance] = 0
      FROM [dbo].[Diary] [DIA]
           INNER JOIN [dbo].[matters] [MAT]
                   ON [MAT].[Code] = [DIA].[CASECODE] 
     WHERE [DIA].[ACTIONID] = @ActionID
END

SET NoCount OFF
END

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

CREATE PROCEDURE [dbo].[KEYHM_TaskGetNextActionCode]  
(  
    @ActionId    AS    INT  
)  
AS  
/*******************************************************************************************************
* This procedure is used to get net Action Code based on the given Action ID.						   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_TaskGetNextActionCode]										   *
* Copied from			: [dbo].[Ky_NETTaskGetNextActionCode]										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN  
 -- SET NOCOUNT ON added to prevent extra result sets from  
 -- interfering with SELECT statements.  
 SET NOCOUNT ON;  
  
  SELECT RTRIM(ISNULL(TNA.[DECISION], ''))							AS [Decision],  
         RTRIM(ISNULL(TNA.[NEXTACTION], ''))						AS [NextAction],  
         TNAC.[DESC]												AS [NextActionDescription],  
         TAC.[NEXTACTIONOPTIONAL]									AS NextActionOptional,  
         CASE WHEN DPA.[TimeFrame] = 'Any Time'  
				THEN CONVERT(DATETIME, '18010101')  
              WHEN DPA.[TimeFrame] = 'Day(s)'  
                THEN DATEADD(DD, -DPA.[TimeFramAmount], DIA.[DATE])  
              WHEN DPA.[TimeFrame] = 'Week(s)'  
                THEN DATEADD(WK, -DPA.[TimeFramAmount], DIA.[DATE])  
              WHEN DPA.[TimeFrame] = 'Month(s)'  
                THEN DATEADD(MM, -DPA.[TimeFramAmount], DIA.[DATE])  
              WHEN DPA.[TimeFrame] = 'Year(s)'  
                THEN DATEADD(YY, -DPA.[TimeFramAmount], DIA.[DATE])  
              ELSE CONVERT(DATETIME, '18010101')   
         END														AS [TimeFrame],  
         [dbo].[ky_WDGetDate](GETDATE(),TNA.[WHENTYPE],TNA.[WHEN])  AS [On]  
    FROM [diary] DIA  
		  INNER JOIN [TemplateActions] TAC 
				ON TAC.[ACTIONCODE] = DIA.[ACTIONCODE]  
		  INNER JOIN [TemplateNextActions] TNA  
		  INNER JOIN [TemplateActions] TNAC 
				ON TNAC.[ACTIONCODE] = TNA.[NEXTACTION] 
				ON TNA.[ACTION] = TAC.[ACTIONCODE]  
		  LEFT JOIN TemplateDependentActions DPA 
				ON DPA.DependentActionCode = TNA.ACTION  
   WHERE [ACTIONID] = @ActionId   
END  
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_TaskScalarDelegatedToHandler'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_TaskScalarDelegatedToHandler]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_TaskScalarDelegatedToHandler]
      (@Handler           VARCHAR(10),
       @ActionID          INT)
AS
/*******************************************************************************************************
* Checks whether an action is delegated to a particular handler. Returns 0 if not, 1 otherwise.		   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_TaskScalarDelegatedToHandler]									   *
* Copied from			: [dbo].[ky_NETTaskScalarDelegatedToHandler]	                               *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-26    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN

  DECLARE @IsAssigned INT

  SELECT @IsAssigned = CASE 
						WHEN COUNT(1) = 0 
							THEN 0 
						ELSE 1 
					   END
    FROM [dbo].[DiaryDelegations] DEL
   WHERE DEL.[ACTIONID] = @ActionID
     AND DEL.[HANDLER] = @Handler
     AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned', 'Created')
     AND DEL.[STATUS] = 0
     AND ISNULL(DEL.[OWNER], 'N') <> 'Y'

  SET @IsAssigned = ISNULL(@IsAssigned, 0)

  RETURN @IsAssigned
END

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

 CREATE FUNCTION
        [dbo].[KEYHM_TF_GetDocFolders3]
       (@parentid         INT,
        @fulltree         BIT,
        @includeparent    BIT)
RETURNS @DocFolders TABLE
       ([seq]                 INT              IDENTITY (1, 1)       NOT NULL PRIMARY KEY,
        [id]                  INT                                    NOT NULL,
        [parent]              INT                                    NOT NULL,
        [foldername]          VARCHAR(500)                           NOT NULL,
        [foldericon]          INT                                    NOT NULL,
        [foldershared]        BIT                                    NOT NULL,
        [folderisours]        BIT                                    NOT NULL)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * Stored Procedure Name : KEYHM_TF_GetDocFolders3                                                            *
 * Copied From           : [dbo].[ky_NETTFGetDocFolders3]                                                    *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              - ky_NETTFGetDocFolders2                                 *   *
 *   * First compatible version:                - 5.5.1.2                                                *   *
 *   * Last compatible software version:        - 5.5.3.9                                                *   *
 *   * Superseded by:                           - ky_NETTFGetDocFolders4                                 *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Retrieve a document folder tree                                                                           *
 * @parentid       - the ID of the root folder                                                               *
 * @fulltree       - get the complete tree for @parentid                                                     *
 *                   0 - get only the first level child nodes                                                *
 *                   1 - get all child nodes                                                                 *
 * @includeparent  - include the parent node itself                                                          *
 *                   0 - the top level returned are the child nodes                                          *
 *                   1 - the top level returned is the parent node                                           *
 *                                                                                                           *
 * Modification History:                                                                                     *
 * 2016-04-20    Pino Carafa      Created                                                                    *
 * 2016-05-12    Pino Carafa      Added Folder Icon                                                          *
 * 2017-06-26    Pino Carafa      Add outer join for folder sharing                                          *
 * 2017-07-12    Pino Carafa      Add indicator to show whether the share is ours or we're linking to it     *
 * 2017-09-04    Pino Carafa      Corrected code to check whether a share is ours.                           *
 * 2019-08-27    Vinodhan         Created KAAS_TF_GetDocFolders3                                             *
 *                                                                                                           *
 *************************************************************************************************************/
BEGIN
  DECLARE @DocFoldersX TABLE
         ([seq]                 INT            IDENTITY (0, 1)         NOT NULL PRIMARY KEY,
          [id]                  INT                                    NOT NULL,
          [parent]              INT                                    NOT NULL,
          [foldername]          VARCHAR(500)                           NOT NULL,
          [foldericon]          INT                                    NOT NULL,
          [foldershared]        BIT                                    NOT NULL,
          [folderisours]        BIT                                    NOT NULL)

  IF ISNULL(@parentid, 0) = 0
    BEGIN
      INSERT
          INTO @DocFoldersX
              ([id],
               [parent],
               [foldername],
               [foldericon],
               [foldershared],
               [folderisours])
        SELECT [DF].[id],
               0,
               [DF].[foldername],
               [DF].[foldericon],
               0,
               1
          FROM [dbo].[DocFolders] [DF]
         WHERE [DF].[parent] IS NULL
      ORDER BY [DF].[foldername],
               [DF].[id]
    END
  ELSE
    BEGIN
      IF @includeparent = 1
        BEGIN
            INSERT
              INTO @DocFoldersX
                  ([id],
                   [parent],
                   [foldername],
                   [foldericon],
                   [foldershared],
                   [folderisours])
            SELECT [DF].[id],
                   ISNULL([DF].[parent], 0),
                   [DF].[foldername],
                   [DF].[foldericon],
                   0,
                   1
              FROM [dbo].[DocFolders] [DF]
             WHERE [DF].[id] = @parentid
          ORDER BY [DF].[foldername],
                   [DF].[id]
        END
      ELSE
        BEGIN
            INSERT
              INTO @DocFoldersX
                  ([id],
                   [parent],
                   [foldername],
                   [foldericon],
                   [foldershared],
                   [folderisours])
            SELECT [DF].[id],
                   ISNULL([DF].[parent], 0),
                   [DF].[foldername],
                   [DF].[foldericon],
                   0,
                   1
              FROM [dbo].[DocFolders] [DF]
             WHERE [DF].[parent] = @parentid
          ORDER BY [DF].[foldername],
                   [DF].[id]
        END
    END

  UPDATE [DFX]
     SET [DFX].[foldershared] = [FSDF].[Shared],
         [DFX].[folderisours] = [IO].[IsOurs]
    FROM @DocFoldersX [DFX]
         INNER JOIN [dbo].[FileSharingDocFolders] [FSDF]
                    CROSS APPLY (SELECT CASE WHEN COUNT(CASE WHEN ISNULL([FSS].[CollabDocFolderID], 0) = 0
                                                                  THEN 1
                                                             ELSE NULL END) = 0
                                                  THEN 0
                                             ELSE 1 END AS [IsOurs]
                                   FROM [dbo].[FileSharingMapping] [FSM]
                                        INNER JOIN [dbo].[FileSharingServers] [FSS]
                                                ON [FSS].[id] = [FSM].[FileSharingServersID]
                                  WHERE [FSM].[FileSharingDocFoldersID] = [FSDF].[DocFolderID]) [IO]
                 ON [FSDF].[DocFolderID] = [DFX].[id]

  DECLARE @TOTAL INT
  DECLARE @ITEM INT

  SELECT @TOTAL = COUNT(1) FROM @DocFoldersX

  SET @ITEM = 0

  WHILE @ITEM < @TOTAL
    BEGIN
        DECLARE @id INT
        DECLARE @parent INT
        DECLARE @foldername VARCHAR(500)
        DECLARE @foldericon INT
        DECLARE @foldershared BIT
        DECLARE @folderisours BIT

        SELECT @id = [DFX].[id],
               @parent = [DFX].[parent],
               @foldername = [DFX].[foldername],
               @foldericon = [DFX].[foldericon],
               @foldershared = [DFX].[foldershared],
               @folderisours = [DFX].[folderisours]
          FROM @DocFoldersX [DFX]
         WHERE [DFX].[seq] = @ITEM

        INSERT
          INTO @DocFolders
              ([id],
               [parent],
               [foldername],
               [foldericon],
               [foldershared],
               [folderisours])
        SELECT @id,
               @parent,
               @foldername,
               @foldericon,
               @foldershared,
               @folderisours

        IF @fulltree = 1
          BEGIN
            INSERT
              INTO @DocFolders
                  ([id],
                   [parent],
                   [foldername],
                   [foldericon],
                   [foldershared],
                   [folderisours])
            SELECT [DFC].[id],
                   [DFC].[parent],
                   [DFC].[foldername],
                   [DFC].[foldericon],
                   [DFC].[foldershared],
                   [DFC].[folderisours]
              FROM [dbo].[KEYHM_TF_GetDocFolders3](@id, 1, 0) [DFC]
          END

      SET @ITEM = @ITEM + 1
    END

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

CREATE PROCEDURE
       [dbo].[KEYHM_UpdateActionAlarm]
      (@LinkID varchar(50))
AS
/*******************************************************************************************************
* Set Keyhouse Risk Management Matter Alarm.														   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_UpdateActionAlarm]						   					   *
* Copied from			: [dbo].[ky_UpdateActionAlarm]												   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-22	Vinodhan K		Created  
* 2019-05-26	Kaushik		Created                                                            *
*******************************************************************************************************/
BEGIN
   DECLARE @MatterRef varchar(20)
   DECLARE @AlarmDateString varchar(23)
   DECLARE @AlarmDate datetime	
   DECLARE @Date datetime
   DECLARE @DYSTARTTIME char(10)
   DECLARE @NUMVAL int
   DECLARE @TimeFromDate varchar(12)
   DECLARE @HourVal varchar(2)
   DECLARE @MinuteVal varchar(2)
   DECLARE @SecondVal varchar(2)
   DECLARE @MilliSecondVal varchar(3)
   DECLARE @Title NVARCHAR(255)
   DECLARE @Message NVARCHAR(max)
   DECLARE @ActionID INT

   DECLARE @NLinkID INT

   IF RTRIM(ISNULL(@LinkID, '')) = ''
     BEGIN
       SET @NLinkID = 0
     END
   ELSE
     IF (ISNUMERIC(@LinkID) = 0)
     OR (CHARINDEX('.', @LinkID) > 0)
     OR (CHARINDEX(',', @LinkID) > 0)
     OR (CHARINDEX(':', @LinkID) > 0)
     OR (CHARINDEX('D', @LinkID) > 0)
       BEGIN
         SET @NLinkID = 0
       END
     ELSE
       BEGIN
         SET @NLinkID = CONVERT(INT, @LinkID)     
       END

   IF (@NLinkID <> 0)
     BEGIN
       select @ActionID = DIA.[ActionID],
              @Date = DIA.[date],
              @DYSTARTTIME = DIA.[DYSTARTTIME],
              @NUMVAL = case when isnumeric(isnull(DIA.[DYSTARTTIME], '')) = 0
                                  then 0
                             when convert(int, DIA.[DYSTARTTIME]) > 8640000
                                  then 0
                             else convert(int, DIA.[DYSTARTTIME]) - 1 END,
              @TimeFromDate = convert(varchar, DIA.[date], 114),
              @MatterRef = DIA.[CaseCode],
              @Title = CONVERT(NVARCHAR(255),
                               CASE WHEN DIA.[ActionType] <> 'E' 
                                         THEN RTRIM(substring(DIA.[TEXT1], 1, 255))
                                    WHEN DIA.[ProcessType] = 'I'
                                         THEN RTRIM(substring('Email From:' + RTrim(DIA.[EmailAddress]) + ' - ' + substring(DIA.[Subject], 1, 255), 1, 255))
                                    ELSE RTRIM(substring('Email To:' + RTrim(substring(DIA.[AddressTo], 1, 255)) + ' - ' + substring(DIA.[Subject], 1, 255), 1, 255)) end),
              @Message = CONVERT(NVARCHAR(MAX), DIA.[TEXT1])
         from [dbo].[diary] DIA
        where DIA.[ActionID] = @NLinkID

       SET @HourVal = Right('00' + convert(varchar(2), FLOOR(@NUMVAL / 360000)), 2)
       SET @MinuteVal = Right('00' + convert(varchar(2), FLOOR((@NUMVAL - (360000 * FLOOR(@NUMVAL / 360000))) / 6000)), 2)
       SET @SecondVal = Right('00' + convert(varchar(2), FLOOR((@NUMVAL - (6000 * FLOOR(@NUMVAL / 6000))) / 100)), 2)
       SET @MilliSecondVal = Right('000' + convert(varchar(3), FLOOR((@NUMVAL - (100 * FLOOR(@NUMVAL / 100))) * 10)), 3)

       SET @AlarmDateString = CONVERT(VARCHAR, @DATE, 112)
                            + ' '
                            + case when @TimeFromDate <> '00:00:00:000'
                                        then @TimeFromDate
                                   when   @HourVal + ':'
                                        + @MinuteVal + ':'
                                        + @SecondVal + ':'
                                        + @MilliSecondVal <> '00:00:00:000'
                                        then   @HourVal + ':'
                                             + @MinuteVal + ':' 
                                             + @SecondVal + ':'
                                             + @MilliSecondVal
                                   when isNull(@DYSTARTTIME, '*') = '*'
                                        then '00:00:00:000'
                                   when isnumeric(isnull(@DYSTARTTIME, '')) = 1
                                        then '00:00:00:000'
                                   when isdate(isnull(@DYSTARTTIME, '')) = 0
                                        then '00:00:00:000'
                                   else convert(varchar, convert(datetime, @DYSTARTTIME), 114) End

       SET @AlarmDate = convert(datetime, @AlarmDateString)

       DELETE ALM
         FROM [dbo].[AlarmTypes] ALT
              INNER JOIN [dbo].[Alarms] ALM
                         LEFT OUTER JOIN [dbo].[DiaryDelegations] DEL
                                      ON DEL.[ActionID] = @ActionID
                                     AND DEL.[Handler] = ALM.[HandlerCode]
                      ON ALM.[Type] = ALT.[TypeID]
        WHERE ALT.[Description] = 'Action'
          AND ALM.[LinkID] = @LinkID
          AND (   DEL.[ActionID] is null
               OR DEL.[Status] = 1) 

       UPDATE ALM
          SET ALM.[OriginalDate] = case when @AlarmDate > ALM.[DeferredDate]
                                             then @AlarmDate
                                        else ALM.[OriginalDate] end,
              ALM.[DeferredDate] = case when @AlarmDate > ALM.[DeferredDate]
                                             then @AlarmDate
                                        else ALM.[DeferredDate] end,
              ALM.[Title] = @Title,
              ALM.[Message] = @Message
         FROM [dbo].[AlarmTypes] ALT
              INNER JOIN [dbo].[Alarms] ALM
                      ON ALM.[Type] = ALT.[TypeID]
        WHERE ALT.[Description] = 'Action'
          AND ALM.[LinkID] = @LinkID 
     END
END
GO
IF OBJECT_ID(N'KEYHM_UpdateCaseInformation',N'P')IS NOT NULL
    DROP PROCEDURE [dbo].[KEYHM_UpdateCaseInformation]
GO

CREATE PROCEDURE [dbo].[KEYHM_UpdateCaseInformation]      
				 (@ActionId    INT,    
				  @Text1       VARCHAR(MAX),
				  @DATE        DATETIME)      
AS    
/*******************************************************************************************************
* This procedure is used to Update Case Info in [dbo].[Diary].										   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_UpdateCaseInformation]										   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/    
BEGIN    
  IF EXISTS(SELECT TOP 1 1 FROM Diary WHERE ACTIONID = @ActionId)    
 BEGIN    
  UPDATE [dbo].[Diary]    
     SET [TEXT1] =	@Text1,
         [DATE]	 =	@DATE    
   WHERE ACTIONID	=	@ActionId    
 END    
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_UpdateRecentHandlerList'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_UpdateRecentHandlerList]
  END
GO
CREATE PROCEDURE [dbo].[KEYHM_UpdateRecentHandlerList] (
	@HandlerCode	VARCHAR(10),
	@AccessedBy		VARCHAR(10))
AS
/*******************************************************************************************************
*																				                       *
* Updates the recently selected handler by the currently logged in user                                *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_UpdateRecentHandlerList]								           *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-08-02    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN
SET NOCOUNT ON
 IF EXISTS(SELECT TOP 1 1 FROM sys.objects WHERE [Name] = 'RecentHandlerList') AND EXISTS (SELECT TOP 1 1 FROM [RecentHandlerList] WHERE [Code] = @HandlerCode AND [AccessedBy] = @AccessedBy)
 BEGIN
 	DELETE FROM [RecentHandlerList] WHERE [Code] = @HandlerCode AND [AccessedBy] = @AccessedBy
 END
 
 IF EXISTS(SELECT TOP 1 1 FROM sys.objects WHERE [Name] = 'RecentHandlerList') AND NOT EXISTS (SELECT TOP 1 1 FROM [RecentHandlerList] WHERE [Code] = @HandlerCode AND [AccessedBy] = @AccessedBy)
 BEGIN
 	INSERT INTO [RecentHandlerList] VALUES(@HandlerCode, @AccessedBy, GETDATE())
 END
SET NOCOUNT OFF
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_UpdateRecentMatterList'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_UpdateRecentMatterList]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_UpdateRecentMatterList]
      (@HANDLER varchar(10),
       @MATTER  varchar(20))
AS
/*******************************************************************************************************
*																									   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_UpdateRecentMatterList]										   *
* Copied from			: [dbo].[ky_UpdateRecentMatterList]		    	                               *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-26    Vinodhan K        Created                                                              *
*******************************************************************************************************/

BEGIN
  EXEC [dbo].[KEYHM_SetMostRecentMatter] @HANDLER, @MATTER
END

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

CREATE PROCEDURE
       [dbo].[KEYHM_UpdateTimeDayBook]
      (@Matter        VARCHAR(20),
       @FeeEarn       VARCHAR(10),
       @Date          DATETIME,
       @Time          INT,
       @Rate          DECIMAL(10,2),
       @Charge        DECIMAL(10,2),
       @Task          VARCHAR(10),
       @TimeOrCharge  CHAR(1),
       @IsChargable   CHAR(1),
       @Comment       VARCHAR(1000),
       @Ncccode       VARCHAR(10) = NULL,
       @RecordID      INT,
       @Post          CHAR(1) = 'Y')
AS

/*******************************************************************************************************
*																									   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_UpdateTimeDayBook]											   *
* Copied from			: [dbo].[ky_NETUpdateTimeDayBook]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-11	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

BEGIN

SET @Post = CASE WHEN @Post IS NULL THEN 'Y' ELSE @Post END

DECLARE @PERIOD AS INT
DECLARE @YEAR AS INT

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

IF @IsSAM4 = 0
    BEGIN
      SELECT @PERIOD = ISNULL(CL.[CURPER], 0),
             @YEAR = ISNULL(CL.[YEAR], 0)
        FROM [dbo].[CONTROL] CL
    END
ELSE
    BEGIN
      SET @PERIOD = (SELECT CNM.[NumValue] FROM [dbo].[CtrlNum] CNM WHERE CNM.[Code] = 'CurPeriod')
      SET @YEAR = (SELECT CNM.[numvalue] FROM [dbo].[CtrlNum] CNM WHERE CNM.[Code] = 'CurYear')
    END

SET @PERIOD = ISNULL(@PERIOD, 0)
SET @YEAR = ISNULL(@YEAR, 0)

DECLARE @ActualRate DECIMAL(18, 2)

SELECT @ActualRate = [dbo].[KEYHM_FN_GetDefaultRate](RTRIM(ISNULL(@Matter, '')),
                                                    RTRIM(ISNULL(@FeeEarn, '')),
                                                    RTRIM(ISNULL(@Ncccode, '')),
                                                    RTRIM(ISNULL(@Task, '')))

IF (@RecordID = 0)
  BEGIN
    INSERT
      INTO [dbo].[TimeDayBook]
          ([MATTER],
           [FEEEARN],
           [DATE],
           [TIME],
           [RATE],
           [Charge],
           [Charged],
           [TASK],
           [TimeOrCharge],
           [COMMENT],
           [NCCCode],
           [Rec_Irr],
           [Post],
           [StopwatchStatus],
           [Period],
           [Year],
           [MatterLevel],
           [TaskLevel],
           [ChargedMins],
           [FeeRate],
           [EntryDate],
           [ModifyDate])
    SELECT NW.[MATTER],
           NW.[FEEEARN],
           NW.[DATE],
           NW.[TIME],
           NW.[RATE],
           NW.[CHARGE],
           NW.[CHARGE],
           NW.[TASK],
           NW.[TimeOrCharge],
           NW.[COMMENT],
           NW.[NCCCode],
           NW.[Rec_Irr],
           NW.[Post],
           NW.[StopwatchStatus],
           NW.[Period],
           NW.[Year],
           MAT.[ChargeLevel],
           TSC.[ChargeLevel],
           NW.[TIME],
           NW.[FEERATE],
           NW.[EntryDate],
           NW.[EntryDate]
      FROM (SELECT @Matter AS [MATTER],
                   @FeeEarn AS [FEEEARN],
                   @Date AS [DATE],
                   @Time AS [TIME],
                   @Rate AS [RATE],
                   @Charge AS [CHARGE],
                   @Task AS [TASK],
                   @TimeOrCharge AS [TimeOrCharge],
                   @Comment AS [COMMENT],
                   @Ncccode AS [NCCCode],
                   @IsChargable AS [Rec_Irr],
                   @Post AS [Post],
                   1 AS [StopwatchStatus],
                   @PERIOD AS [Period],
                   @YEAR AS [Year],
                   ISNULL(@ActualRate, @Rate) AS [FEERATE],
                   CONVERT(DATETIME, CONVERT(VARCHAR, GetDate(), 112)) AS [EntryDate]) NW
           LEFT OUTER JOIN [dbo].[matters] MAT
                        ON MAT.[Code] = NW.[MATTER]
           LEFT OUTER JOIN [dbo].[TasksCodes] TSC
                        ON TSC.[CODE] = NW.[TASK]

  END
ELSE
  BEGIN
    UPDATE TDB
       SET TDB.[MATTER]         = @Matter,
           TDB.[FEEEARN]        = @FeeEarn,
           TDB.[DATE]           = @Date,
           TDB.[TIME]           = @Time,
           TDB.[RATE]           = @Rate,
           TDB.[Charge]         = @Charge,
           TDB.[Charged]        = @Charge,
           TDB.[TASK]           = @Task,
           TDB.[TIMEORCHARGE]   = @TimeOrCharge,
           TDB.[REC_IRR]        = @IsChargable,
           TDB.[COMMENT]        = @Comment,
           TDB.[Ncccode]        = @Ncccode,
           TDB.[Post]           = @Post,
           TDB.[MatterLevel]    = CASE ISNULL(TDB.[MatterLevel], '')
                                       WHEN '' THEN MAT.[ChargeLevel]
                                  ELSE TDB.[MatterLevel] END,
           TDB.[TaskLevel]      = CASE ISNULL(TDB.[TaskLevel], '')
                                       WHEN '' THEN TSC.[ChargeLevel]
                                  ELSE TDB.[TaskLevel] END,
           TDB.[FeeRate]        = ISNULL(TDB.[FeeRate], @ActualRate),
           TDB.[ChargedMins]    = @Time
      FROM [dbo].[TimeDayBook] TDB
           LEFT OUTER JOIN [dbo].[matters] MAT
                        ON MAT.[Code] = TDB.[MATTER]
           LEFT OUTER JOIN [dbo].[TasksCodes] TSC
                        ON TSC.[CODE] = TDB.[TASK]
     WHERE TDB.[RecordID]       =  @RecordID

  END
END

GO

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


CREATE PROCEDURE
       [dbo].[KEYHM_UpdateTimeEntryFromDayBook]
      (@HANDLER        VARCHAR(10),
       @UPDByHandler   VARCHAR(10),
       @User           NVARCHAR(128))
AS

/*******************************************************************************************************
* Update TimeEntry values																			   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_UpdateTimeEntryFromDayBook]									   *
* Copied from			: [dbo].[ky_NETUpdateTimeEntryFromDayBook]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN

SET @UPDByHandler = RTRIM(ISNULL(@UPDByHandler, ''))
SET @User = RTRIM(ISNULL(@User, N''))

DECLARE @NCOMMAND NVARCHAR(MAX)

SET @NCOMMAND = N'INSERT
  INTO [dbo].[TimeEntryLogNew]
      ([MATTER],
       [FEEEARN],
       [DATE],
       [TIME],
       [RATE],
       [CHARGE],
       [TASK],
       [TIMEORCHARGE],
       [COMMENT],
       [BILLED],
       [NCCODE],
       [DOCKET],
       [TEAM],
       [TRACKREF],
       [REC_IRR],
       [SHOULDHAVE],
       [INVOICENO],
       [PERIOD],
       [YEAR],
       [BILLINGPERIOD],
       [BILLINGYEAR],
       [OPENINV],
       [RECORDID],
       [ActionId],
       [StageCode],
       [Leave],
       [BilledAmount],
       [IncludeInBill],
       [BILLINGDATE],
       [AxleNumber],
       [WriteOffDT],
       [WriteOffID],
       [LogFor]'

IF @Handler <> ''
  BEGIN
    SET @NCOMMAND = @NCOMMAND + N',
       [HandlerLogFor]'
  END

IF @User <> N''
  BEGIN
    SET @NCOMMAND = @NCOMMAND + N',
       [LoginLogFor]'
  END

SET @NCOMMAND = @NCOMMAND + N')
SELECT [TIE].[MATTER],
       [TIE].[FEEEARN],
       [TIE].[DATE],
       [TIE].[TIME],
       [TIE].[RATE],
       [TIE].[CHARGE],
       [TIE].[TASK],
       [TIE].[TIMEORCHARGE],
       [TIE].[COMMENT],
       [TIE].[BILLED],
       [TIE].[NCCODE],
       [TIE].[DOCKET],
       [TIE].[TEAM],
       [TIE].[TRACKREF],
       [TIE].[REC_IRR],
       [TIE].[SHOULDHAVE],
       [TIE].[INVOICENO],
       [TIE].[PERIOD],
       [TIE].[YEAR],
       [TIE].[BILLINGPERIOD],
       [TIE].[BILLINGYEAR],
       [TIE].[OPENINV],
       [TIE].[RECORDID],
       [TIE].[ActionId],
       [TIE].[StageCode],
       [TIE].[Leave],
       [TIE].[BilledAmount],
       [TIE].[IncludeInBill],
       [TIE].[BILLINGDATE],
       [TIE].[AxleNumber],
       [TIE].[WriteOffDT],
       [TIE].[WriteOffID],
       ''C'''

IF @UPDByHandler <> ''
  BEGIN
    SET @NCOMMAND = @NCOMMAND + N',
       @UPDByHandler'
  END

IF @User <> ''
  BEGIN
    SET @NCOMMAND = @NCOMMAND + N',
       @User'
  END

SET @NCOMMAND = @NCOMMAND + N'
  FROM [dbo].[WDNTEID] [NTEID]
       INNER JOIN [dbo].[TimeEntry] [TIE]
               ON [TIE].[RecordId] = NTEID.[NEWID]
 WHERE [NTEID].[HANDLER] = @Handler'

EXEC sp_executesql @NCOMMAND, N'@Handler VARCHAR(10), @UPDByHandler VARCHAR(10), @User NVARCHAR(128)', @Handler, @UPDByHandler, @User

UPDATE TIE
   SET TIE.[Charge]  = CASE WHEN RTRIM(ISNULL(TIE.[MATTER], '~')) <> '~'
                                 THEN TDB.[CHARGE]
                            ELSE 0 END,
       TIE.[REC_IRR] = CASE WHEN RTRIM(ISNULL(TIE.[MATTER], '~')) <> '~'
                                 THEN TIE.[REC_IRR]
                            WHEN RTRIM(ISNULL(TIE.[REC_IRR], '')) = ''
                                 THEN 'C'
                            ELSE TIE.[REC_IRR] END,
       TIE.[Units] = TDB.[Units],
       TIE.[MatterLevel] = TDB.[MatterLevel],
       TIE.[FEERate] = TDB.[FEERate],
       TIE.[ChargedMins] = TDB.[ChargedMins],
       TIE.[FEECost] = TDB.[FEECost],
       TIE.[TaskLevel] = TDB.[TaskLevel],
       TIE.[EntryDate] = TDB.[EntryDate],
       TIE.[ModifyDate] = TDB.[ModifyDate],
       TIE.[Leave] = TDB.[Leave],
       TIE.[TEAM] = HAN.[TEAM],
       TIE.[INVOICENO] = (CASE WHEN ISNULL(MAT.[OpenInvoiceNo], 0) <> 0
                                    THEN MAT.[OpenInvoiceNo]
                               ELSE 0 END),
       TIE.[OPENINV] = (CASE WHEN ISNULL(MAT.[OpenInvoiceNo], 0) <> 0
                                  THEN 'Y'
                             ELSE 'N' END),
       TIE.[BilledAmount] = (CASE WHEN ISNULL(MAT.[OpenInvoiceNo], 0) <> 0
                                       THEN TDB.[Charge]
                                  ELSE 0 END),
       TIE.[IncludeInBill] = (CASE WHEN ISNULL(MAT.[OpenInvoiceNo], 0) <> 0
                                        THEN 1
                                   ELSE 0 END),
       TIE.[AxleNumber] = 0
  FROM [dbo].[WDNTEID] NTEID
       INNER JOIN [dbo].[TimeDayBook] TDB
               ON TDB.[RECORDID] = NTEID.[RECORDID]
       INNER JOIN [dbo].[TimeEntry] TIE
               ON TIE.[RecordId] = NTEID.[NEWID]
       LEFT OUTER JOIN [dbo].[matters] MAT
                    ON MAT.[Code] = TIE.[MATTER]
       INNER JOIN [dbo].[Handlers] HAN
               ON HAN.[CODE] = TIE.[FEEEARN]
 WHERE NTEID.[HANDLER] = @Handler

UPDATE MAT
   SET MAT.[ChargeBal] =   MAT.[ChargeBal]
                         + CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                WHEN 0 THEN TDB.[Charge]
                                ELSE 0 END,
       MAT.[TimeBal] =   MAT.[TimeBal] --2018-02-22 WAS MAT.[ChargeBal] !
                       + CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                              WHEN 0 THEN TDB.[Time]
                              ELSE 0 END
  FROM [dbo].[WDNTEID] NTEID
       INNER JOIN [dbo].[TimeDayBook] TDB
               ON TDB.[RECORDID] = NTEID.[RECORDID]
              AND TDB.[REC_IRR] = 'C'
       LEFT OUTER JOIN [dbo].[matters] MAT
                    ON MAT.[Code] = TDB.[MATTER]
 WHERE NTEID.[HANDLER] = @HANDLER

END

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

CREATE PROCEDURE [dbo].[KEYHM_UserCanPostTime](
                @MATTER   VARCHAR(20),
                @HANDLER  VARCHAR(20),
                @RECORDID VARCHAR(20)
)
AS
/*******************************************************************************************************
* Please look at [dbo].[KEYHM_FN_UserCanPostTime] for details on how the function works,				   *
* as this is just a wrapper procedure which calls the function.				   				   		   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_UserCanPostTime]						     					   *
* Copied from			: [dbo].[ky_NETUserCanPostTime]		       								       *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-05-17	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
BEGIN
	DECLARE @ID INT
	
	IF (@RECORDID IS NOT NULL AND ISNUMERIC(@RECORDID) = 1)
	BEGIN
		SET @ID = CONVERT(INT, @RECORDID)
	END

	SELECT
		ISNULL([dbo].[KEYHM_FN_UserCanPostTime](@MATTER, @HANDLER, @ID), 0) AS [CODE]
END
GO
IF EXISTS
  (SELECT *
     FROM sys.[objects] SO
    WHERE SO.[name] = 'KEYHM_WDTimeDayBookWithAxleErrors'
      AND SO.[type] = 'TF')
BEGIN
  DROP FUNCTION [dbo].[KEYHM_WDTimeDayBookWithAxleErrors]
END
GO

/**************************************************************************************
 *
 * KEYHM_WDTimeDayBookWithAxleErrors
 *
 * Lists the current Day Book Entries plus information about Axle errors
 *
 2020-03-10   Rajesh   Copied from ky_WDTimeDayBookWithAxleErrors
 **************************************************************************************/
Create Function
       [dbo].[KEYHM_WDTimeDayBookWithAxleErrors]
      (@HSEClientGroup        varchar(20),
       @Handler               varchar(10))
RETURNS @TDBWA TABLE
       ([IsAxleError]       varchar(1),
        [AxleError]         varchar(255),
        [Matter]            varchar(20),
        [FEEEARN]           varchar(10),
        [DATE]              datetime,
        [TIME]              int,
        [RATE]              decimal(10,2),
        [CHARGE]            decimal(10,2),
        [TASK]              varchar(10),
        [TIMEORCHARGE]      varchar(1),
        [STARTTIME]         int,
        [COMMENT]           varchar(1000),
        [NCCCODE]           varchar(10),
        [TEAM]              varchar(10),
        [TRACKREF]          int,
        [DOCKET]            varchar(8),
        [REC_IRR]           varchar(1),
        [PERIOD]            int,
        [YEAR]              int,
        [RECORDID]          int,
        [ActionId]          int,
        [Leave]             varchar(1),
        [StageCode]         varchar(10),
        [Post]              varchar(1))
AS
BEGIN
  INSERT
    INTO @TDBWA
        ([IsAxleError],
         [AxleError],
         [Matter],
         [FEEEARN],
         [DATE],
         [TIME],
         [RATE],
         [CHARGE],
         [TASK],
         [TIMEORCHARGE],
         [STARTTIME],
         [COMMENT],
         [NCCCODE],
         [TEAM],
         [TRACKREF],
         [DOCKET],
         [REC_IRR],
         [PERIOD],
         [YEAR],
         [RECORDID],
         [ActionId],
         [Leave],
         [StageCode],
         [Post])
  SELECT CASE WHEN RTRIM(ISNULL(TDB.[matter], '')) = ''
                   -- Admin entries can't cause an Axle error
                   THEN 'N'
              WHEN RTRIM(ISNULL(TDB.[matter], '')) = '~'
                   -- Admin entries can't cause an Axle error
                   THEN 'N'
              WHEN MAT.[Code] IS NULL
                   -- Missing matter. This is an error
                   THEN 'Y'
              WHEN RTRIM(IsNull(CON.[ClientGroup], '')) <> @HSEClientGroup
                   -- If it's not an HSE Client it can't cause an Axle Error
                   THEN  'N'
              WHEN RTRIM(ISNULL(WTY.[CODE], '')) = ''
                   -- Missing Worktype. This is an error
                   THEN 'Y'
              WHEN RTRIM(ISNULL(WTY.[ChildCare], '')) <> 'Y'
                   -- If it's not a ChildCare matter it can't cause an Axle Error
                   THEN  'N'
              WHEN RTRIM(ISNULL(TAC.[CODE], '')) = ''
                   -- Missing Task. This is an error
                   THEN 'Y'
              WHEN RTRIM(ISNULL(TAC.[AxleTask], '')) <> 'Y'
                   -- This is not a Child Care task. This is an error
                   THEN 'Y'
              WHEN LEN(RTRIM(ISNULL(TDB.[COMMENT], ''))) < 10
                   -- Comment must be at least 10 characters. This is an error.
                   THEN 'Y'
              WHEN TDB.[TIME] > 1440
                   -- Task is too long! Must be less than 1440 minutes (i.e. 24 hours)
                   THEN 'Y'
              ELSE 'N'
          END AS [IsAxleError],
         CASE WHEN RTRIM(ISNULL(TDB.[matter], '')) = ''
                   -- Admin entries can't cause an Axle error
                     THEN ''
              WHEN MAT.[Code] IS NULL
                   -- Missing matter. This is an error
                   THEN 'Matter: ' + RTRIM(ISNULL(TDB.[MATTER], '')) + ' not found.'
              WHEN RTRIM(IsNull(CON.[ClientGroup], '')) <> @HSEClientGroup
                   -- If it's not an HSE Client it can't cause an Axle Error
                   THEN  ''
              WHEN RTRIM(ISNULL(WTY.[CODE], '')) = ''
                   -- Missing Worktype. This is an error
                   THEN 'Matter Work Type ' + RTRIM(IsNull(MAT.[WType], '')) + ' was not found for matter: ' + RTRIM(ISNULL(TDB.[MATTER], ''))
              WHEN RTRIM(ISNULL(WTY.[ChildCare], '')) <> 'Y'
                   -- If it's not a ChildCare matter it can't cause an Axle Error
                   THEN  ''
              WHEN RTRIM(ISNULL(TAC.[CODE], '')) = ''
                   -- Missing Task. This is an error
                   THEN 'Task ' + RTRIM(IsNull(TAC.[CODE], '')) + ' was not found for matter: ' + RTRIM(ISNULL(TDB.[MATTER], ''))
              WHEN RTRIM(ISNULL(TAC.[AxleTask], '')) <> 'Y'
                   -- This is not a Child Care task. This is an error
                   THEN 'Task ' + RTRIM(IsNull(TAC.[CODE], '')) + ' is not a Child Care task for matter: ' + RTRIM(ISNULL(TDB.[MATTER], ''))
              WHEN LEN(RTRIM(ISNULL(TDB.[COMMENT], ''))) < 10
                   -- Comment must be at least 10 characters. This is an error.
                   THEN 'Comment should be at least 10 characters for matter: ' + RTRIM(ISNULL(TDB.[MATTER], ''))
              WHEN TDB.[TIME] > 1440
                   -- Task is too long! Must be less than 1440 minutes (i.e. 24 hours)
                   THEN 'Time should be less than 24 hours for matter: ' + RTRIM(ISNULL(TDB.[MATTER], ''))
              ELSE 'N'
          END AS [AxleError],
         RTRIM(IsNULL(TDB.[MATTER], '')) AS [Matter],
         RTRIM(IsNULL(TDB.[FEEEARN], '')) AS [Feeearn],
         TDB.[DATE],
         ISNULL(TDB.[TIME], 0) AS [TIME],
         Case When IsNull(MAT.[ChargeOutRateInd], 'N') = 'Y'
                   THEN IsNull(MCR.[Rate], 0)
              When IsNull(CON.[ChargeOutRateInd], 'N') = 'Y'
                   THEN IsNull(CCR.[Rate], 0)
              ELSE IsNull(FEP.[ChargeFct], 1.00) * FER.[Rate] END,
         Convert(numeric(8, 2),
                 (  (  IsNull(TDB.[Time], 0)
                     * Case When IsNull(MAT.[ChargeOutRateInd], 'N') = 'Y'
                                 THEN IsNull(MCR.[Rate], 0)
                            When IsNull(CON.[ChargeOutRateInd], 'N') = 'Y'
                                 THEN IsNull(CCR.[Rate], 0)
                            ELSE IsNull(FEP.[ChargeFct], 1.00) * FER.[Rate] END)
                     / 60)),
         RTRIM(IsNULL(TDB.[TASK], '')) AS [TASK],
         RTRIM(IsNULL(TDB.[TIMEORCHARGE], '')) AS [TIMEORCHARGE],
         ISNULL(TDB.[STARTTIME], 0) AS [STARTTIME],
         RTRIM(IsNULL(TDB.[COMMENT], '')) AS [COMMENT],
         RTRIM(IsNULL(TDB.[NCCCODE], '')) AS [NCCCODE],
         RTRIM(IsNULL(TDB.[TEAM], '')) AS [TEAM],
         ISNULL(TDB.[TRACKREF], 0) AS [TRACKREF],
         RTRIM(IsNULL(TDB.[DOCKET], '')) AS [DOCKET],
         RTRIM(IsNULL(TDB.[REC_IRR], '')) AS [REC_IRR],
         ISNULL(TDB.[PERIOD], 0) AS [PERIOD],
         ISNULL(TDB.[YEAR], 0) AS [YEAR],
         ISNULL(TDB.[RECORDID], 0) AS [RECORDID],
         ISNULL(TDB.[ActionId], 0) AS [ActionId],
         RTRIM(IsNULL(TDB.[Leave], '')) AS [Leave],
         RTRIM(IsNULL(TDB.[StageCode], '')) AS [StageCode],
         RTRIM(IsNULL(TDB.[Post], '')) AS [Post]
    FROM [dbo].[TimeDayBook] TDB
         LEFT OUTER JOIN [dbo].[matters] MAT
                         INNER JOIN [dbo].[Contacts] CON
                                 ON CON.[Code] = MAT.[ClientCode]
                         LEFT OUTER JOIN [dbo].[WorkTypes] WTY
                                      ON WTY.[CODE] = MAT.[WType]
                      ON MAT.[Code] = TDB.[MATTER]
         LEFT OUTER JOIN [dbo].[TasksCodes] TAC
                      on TAC.[CODE] = TDB.[TASK]
         OUTER APPLY (SELECT MCOR.[Rate]
                        FROM [dbo].[MatterChargeOutRates] MCOR
                       WHERE MCOR.[FeCode] = TDB.[FEEEARN]
                         AND MCOR.[MatterCode] = TDB.[MATTER]) MCR   
         OUTER APPLY (SELECT CCOR.[Rate]
                        FROM [dbo].[ClientChargeOutRates] CCOR
                       WHERE CCOR.[FeCode] = TDB.[FEEEARN]
                         AND CCOR.[ClientCode] = MAT.[CLIENTCODE]) CCR
         CROSS APPLY (SELECT CASE IsNull(MAT.[ChargeLevel], 3)
                                  WHEN 1 THEN IsNull(HDL.[RATE1], 0)
                                  WHEN 2 THEN IsNull(HDL.[RATE2], 0)
                                  WHEN 3 THEN IsNull(HDL.[RATE3], 0)
                                  WHEN 4 THEN IsNull(HDL.[RATE4], 0)
                                  WHEN 5 THEN IsNull(HDL.[RATE5], 0)
                                  ELSE IsNull(HDL.[RATE], 0) END AS [RATE]
                        FROM [dbo].[Handlers] HDL
                       WHERE HDL.[CODE] = TDB.[FEEEARN]) FER
         OUTER APPLY (SELECT CASE IsNull(TAC.[ChargeLevel], 'C')
                                  WHEN 'A' THEN 0.33
                                  WHEN 'B' THEN 0.67
                                  WHEN 'C' THEN 1.00
                                  WHEN 'D' THEN 1.33
                                  WHEN 'E' THEN 1.67
                                  ELSE 1.00 END AS [ChargeFct]
                        FROM [dbo].[TasksCodes] TAC
                       WHERE TAC.[CODE] = CASE RTrim(IsNull(TDB.MATTER, ''))
                                               WHEN '' THEN TDB.[NCCCODE]
                                               ELSE TDB.[TASK] END) FEP
   WHERE TDB.[FEEEARN] = @Handler
  RETURN
END
GO
IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KEYHM_XMLAddTimeDayBook'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KEYHM_XMLAddTimeDayBook]
  END
GO

CREATE PROCEDURE
       [dbo].[KEYHM_XMLAddTimeDayBook]
      (@XML NVARCHAR(MAX))
AS
BEGIN
/*******************************************************************************************************
* Used to add new Timedaybook entry																	   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_XMLAddTimeDayBook]											   *
* Copied from			: [dbo].[ky_NETSPXMLAddTimeDayBook]											   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-24	Vinodhan K		Created                                                                *
 *******************************************************************************************************/
DECLARE @iSL                  INT
DECLARE @Matter               VARCHAR(20)
DECLARE @FeeEarner            VARCHAR(10)
DECLARE @Minutes              INT
DECLARE @StopwatchStatus      INT
DECLARE @RecordID             INT
DECLARE @UpdateByPass         BIT
DECLARE @DeleteByPass         BIT
DECLARE @AddNew               BIT
DECLARE @Task                 VARCHAR(6)
DECLARE @Comment              VARCHAR(1000)
DECLARE @ChargeDefault        DECIMAL(10, 2)

BEGIN TRY
EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
END TRY
BEGIN CATCH
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<tdb/>'
END CATCH

SELECT @Matter                            = [SRC].[Matter],
       @FeeEarner                         = [SRC].[FeeEarner],
       @Minutes                           = [SRC].[Minutes],
       @StopwatchStatus                   = [SRC].[StopwatchStatus],
       @RecordID                          = [SRC].[RecordID],
       @UpdateByPass                      = [SRC].[UpdateByPass],
       @DeleteByPass                      = [SRC].[DeleteByPass],
       @AddNew                            = [SRC].[AddNew],
       @Task                              = [SRC].[Task],
       @Comment                           = [SRC].[Comment]
  FROM OPENXML(@iSL, N'tdb')
  WITH ([Matter]           VARCHAR(20)     '@matter',
        [FeeEarner]        VARCHAR(10)     '@feeearner',
        [Minutes]          INT             '@minutes',
        [StopwatchStatus]  INT             '@stopwatchstatus',
        [RecordID]         INT             '@recordid',
        [UpdateByPass]     INT             '@updatebypass',
        [DeleteByPass]     INT             '@deletebypass',
        [AddNew]           INT             '@addnew',
        [Task]             VARCHAR(6)      '@task',
        [Comment]          VARCHAR(1000)   '@comment') [SRC]

EXEC sp_xml_removedocument @iSL

--Original defaults
SET @Minutes = ISNULL(@Minutes, 0)
SET @StopwatchStatus = ISNULL(@StopwatchStatus, 1)
SET @RecordID = ISNULL(@RecordID, 0)
SET @UpdateByPass = ISNULL(@UpdateByPass, 0)
SET @DeleteByPass = ISNULL(@DeleteByPass, 0)
SET @AddNew = ISNULL(@AddNew, 0)

IF EXISTS
  (SELECT TOP 1 1
     FROM [dbo].[matters] [MAT]
          INNER JOIN [dbo].[ChargingMatrix] [CMX]
                  ON [CMX].[ARRANGEMENTCODE] = [MAT].[ChargeArrangement]
                 AND [CMX].[CHARGECODE] = @Task
    WHERE [MAT].[Code] = @matter)
  BEGIN
    SELECT TOP 1
           @Task = RTRIM(ISNULL([CMX].[CHARGECODE], '')),
           @ChargeDefault = CONVERT(DECIMAL(10, 2), ISNULL([CMX].[BAND1RATE], 0)),
           @Comment = RTRIM(ISNULL([CMX].[DESCRIPTION], ''))
      FROM [dbo].[matters] [MAT]
           INNER JOIN [dbo].[ChargingMatrix] [CMX]
                   ON [CMX].[ARRANGEMENTCODE] = [MAT].[ChargeArrangement]
                  AND [CMX].[CHARGECODE] = @Task
     WHERE [MAT].[Code] = @matter
  END
ELSE IF NOT EXISTS
  (SELECT TOP 1 1
     FROM [dbo].[TasksCodes] [TC] WITH (nolock)
    WHERE [TC].[CODE] = @Task)
  BEGIN
    SET @Task = ''
    
    -- If "AutoDefaultTaskTime" is enabled in the settings then use the handler's default task
    IF (SELECT TOP 1 ISNULL(CFG.[KeyValue], 'False')
          FROM [dbo].[Settings] AS [CFG] WITH (nolock)
         WHERE [CFG].[KeyName] = 'AutoDefaultTaskTime') = 'True'
    BEGIN
      SELECT @Task = ISNULL([HAN].[DEFAULTTASK], ''),
             @Comment = RTRIM(ISNULL([TSK].[DESC], ''))
        FROM [dbo].[Handlers] AS [HAN] WITH (nolock)
             INNER JOIN [dbo].[TasksCodes] AS [TSK] WITH (nolock)
                     ON [HAN].[DEFAULTTASK] = [TSK].[CODE]
		 WHERE [HAN].[Code] = @FeeEarner
    END
  END
ELSE
  BEGIN
    SELECT @TASK = RTRIM([TC].[CODE]),
           @ChargeDefault = CONVERT(DECIMAL(10, 2), ISNULL([TC].[CHARGEAMT], 0))
      FROM [dbo].[TasksCodes] [TC] WITH (nolock)
     WHERE [TC].[CODE] = @TASK
  END

IF @UpdateByPass = 0
  BEGIN
    UPDATE [TDB]
       SET [TDB].[StopwatchStatus] = 1
      FROM [dbo].[TimeDayBook] [TDB]
     WHERE [TDB].[FeeEarn] = @FeeEarner
  END

IF @DeleteByPass = 0
  BEGIN --IF @DeleteByPass = 0
    IF(@Minutes=0)
      BEGIN
        DELETE [TDB]
          FROM [dbo].[TimeDayBook] [TDB]
         WHERE [TDB].[FeeEarn] = @FeeEarner
           AND ISNULL([TDB].[Time], 0) = 0
           AND [TDB].[Matter] <> ''
           AND [TDB].[TimeOrCharge] = 'T'
           AND RTRIM(ISNULL([TDB].[Task], '')) = '' --KEYD-5221
           AND RTRIM(ISNULL([TDB].[Comment], '')) = '' --KEYD-5221
         --AND [TDB].[Matter] <> @Matter
      END
    ELSE
      BEGIN
        DELETE [TDB]
          FROM [dbo].[TimeDayBook] [TDB]
         WHERE [TDB].[FeeEarn] = @FeeEarner
           AND ISNULL([TDB].[Time], 0) = 0
           AND [TDB].[Matter] NOT IN ('' , @Matter)
           AND [TDB].[TimeOrCharge] = 'T'
           AND RTRIM(ISNULL([TDB].[Task], '')) = '' --KEYD-5221
           AND RTRIM(ISNULL([TDB].[Comment], '')) = '' --KEYD-5221
      END
  END  --IF @DeleteByPass = 0

IF @RecordID <> 0
  BEGIN -- IF @RecordID <> 0
    UPDATE [TDB]
       SET [TDB].[StopwatchStatus] = @StopwatchStatus,
           [TDB].[Time] = @Minutes,
           [TDB].[Charge] = (ISNULL([TDB].[Rate], 0) * (@Minutes / 60.0)),
           [TDB].[Charged] = (ISNULL([TDB].[Rate], 0) * (@Minutes / 60.0)),
           [TDB].[Post] = 'Y'
      FROM [dbo].[TimeDayBook] [TDB]
     WHERE [TDB].[RecordID] = @RecordID

    SELECT TOP 1
           [TDB].[RecordID],
           ISNULL([TDB].[Time], 0) AS [Minutes]
      FROM [dbo].[TimeDayBook] [TDB] WITH (nolock)
     WHERE [TDB].[RecordID] = @RecordID
  END --IF @RecordID <> 0
ELSE -- ELSE CONDITION: IF @RecordID <> 0
  BEGIN -- ELSE CONDITION: IF @RecordID <> 0
    -- 2018-05-25 START - Try to prevent deadlocks using a CASE WHEN construct that should
    --                    avoid table access on the first two conditions rather than the
    --                    original IF with OR statements that still evaluates all 3 conditions
    IF CASE WHEN @Matter = ''
                 THEN 1
            WHEN @AddNew = 1
                 THEN 1
            WHEN NOT EXISTS
                    (SELECT TOP 1 1
                       FROM [dbo].[TimeDayBook] [TDB] WITH (nolock)
                      WHERE [TDB].[FeeEarn] = @FeeEarner
                        AND RTRIM([TDB].[Matter]) = @Matter
                        --AND [TDB].[TIMEORCHARGE]='T' KEYD-5124 - "C" type timers used to not be re-startable. But there is no need for that.
                        AND [TDB].[Post] = 'Y')
                 THEN 1
            ELSE 0 END = 1 --Insert conditions
    -- 2018-05-25 END
      BEGIN --Insert conditions
        DECLARE @PERIOD AS INT
        DECLARE @YEAR AS INT

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

        IF @IsSAM4 = 0
          BEGIN
            SELECT @PERIOD = [CL].[CURPER],
                   @YEAR = [CL].[YEAR]
              FROM [dbo].[control] [CL] WITH (nolock)
          END
        ELSE
          BEGIN
            SELECT @PERIOD = [CL].[numvalue]
              FROM [dbo].[CtrlNum] [CL] WITH (nolock)
             WHERE [CL].[code] = 'CurPeriod'

            SELECT @YEAR = [CL].[numvalue]
              FROM [dbo].[CtrlNum] [CL] WITH (nolock)
             WHERE [CL].[code] = 'CurYear'
          END

        SET @PERIOD = ISNULL(@PERIOD, 0)
        SET @YEAR = ISNULL(@YEAR, 0)

        DECLARE @IsChargeable VARCHAR(1)
        SELECT @IsChargeable = [HAN].[ISChargeable]
          FROM [dbo].[Handlers] [HAN] WITH (nolock)
         WHERE [HAN].[CODE] = @FeeEarner

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

        DECLARE @MatterBillingMethod CHAR(1)
        DECLARE @ClientBillingMethod CHAR(1)
        DECLARE @DefaultBillingMethod CHAR(1)

        SELECT @MatterBillingMethod = RTRIM(ISNULL([MAT].[BillingMethod], '')),
               @ClientBillingMethod = RTRIM(ISNULL([CON].[BillingMethod], ''))
          FROM [dbo].[Matters] [MAT] WITH (nolock)
               LEFT OUTER JOIN [dbo].[Contacts] [CON] WITH (nolock)
                            ON [CON].[Code] = [MAT].[ClientCode]
         WHERE [MAT].[Code] = @Matter

        SET @MatterBillingMethod = ISNULL(@MatterBillingMethod, '')
        SET @ClientBillingMethod = ISNULL(@ClientBillingMethod, '')

        IF(@MatterBillingMethod <> '')
          BEGIN
            SET @DefaultBillingMethod = @MatterBillingMethod
          END
        ELSE IF(@ClientBillingMethod <> '')
          BEGIN
            SET @DefaultBillingMethod = @ClientBillingMethod
          END
        ELSE
          BEGIN
            SET @DefaultBillingMethod = 'T'
          END
        
		    -- John 2018-03-16 Only allow VALID methods
		    If ISNULL(@DefaultBillingMethod, '') NOT IN ('T', 'C')
		    BEGIN
			    SET @DefaultBillingMethod = 'T'
		    END
        
        INSERT
          INTO [dbo].[TimeDayBook]
              ([Matter],
               [FeeEarn],
               [Date],
               [Time],
               [Task],
               [TimeOrCharge],
               [Rec_Irr],
               [Post],
               [StopwatchStatus],
               [Period],
               [Year],
               [MatterLevel],
               [Comment],
               [Rate],
               [Charge],
               [Charged],
               [EntryDate],
               [ModifyDate])
        SELECT [NW].[MATTER],
               [NW].[FeeEarn],
               [NW].[Date],
               [NW].[Time],
               [NW].[Task],
               [NW].[TimeOrCharge],
               @IsChargeable,
               [NW].[Post],
               [NW].[StopwatchStatus],
               [NW].[Period],
               [NW].[Year],
               [MAT].[ChargeLevel],
               [NW].[Comment],
               CASE WHEN @DefaultBillingMethod = 'T'
                         THEN CONVERT(DECIMAL(10, 2), 0)
                    WHEN ISNULL(@ChargeDefault, 0) = 0
                         THEN CONVERT(DECIMAL(10, 2), 0)
                    ELSE CONVERT(DECIMAL(10, 2), @ChargeDefault) END,
               CASE WHEN @DefaultBillingMethod = 'T'
                         THEN CONVERT(DECIMAL(10, 2), 0)
                    WHEN ISNULL(@ChargeDefault, 0) = 0
                         THEN CONVERT(DECIMAL(10, 2), 0)
                    ELSE CONVERT(DECIMAL(10, 2), @ChargeDefault) END,
               CASE WHEN @DefaultBillingMethod = 'T'
                         THEN CONVERT(DECIMAL(10, 2), 0)
                    WHEN ISNULL(@ChargeDefault, 0) = 0
                         THEN CONVERT(DECIMAL(10, 2), 0)
                    ELSE CONVERT(DECIMAL(10, 2), @ChargeDefault) END,
               CONVERT(DATETIME, CONVERT(VARCHAR, GetDate(), 112)),
               CONVERT(DATETIME, CONVERT(VARCHAR, GetDate(), 112))
          FROM (SELECT @Matter AS [MATTER],
                       @FeeEarner AS [FeeEarn],
                       CONVERT(VARCHAR(12), GETDATE(), 112) AS [Date],
                       @Minutes AS [Time],
                       @Task AS [Task],
                       @DefaultBillingMethod AS [TimeOrCharge],
                       'Y' AS [Post],
                       @StopwatchStatus AS [StopwatchStatus],
                       @PERIOD AS [Period],
                       @YEAR As [Year],
                       @Comment AS [Comment]) [NW]
               LEFT OUTER JOIN [dbo].[matters] [MAT] WITH (nolock)
                            ON [MAT].[Code] = [NW].[MATTER]

        SELECT SCOPE_IDENTITY() AS [RecordID],
               0 AS [Minutes]
      END --Insert conditions
    ELSE --(ELSE CONDITION) Insert conditions
      BEGIN --(ELSE CONDITION) Insert conditions
        SET @RecordID = NULL

          SELECT TOP 1
                 @RecordID = [TDB2].[RecordID]
            FROM [dbo].[TimeDayBook] [TDB2] WITH (nolock)
           WHERE [TDB2].[FEEEARN] = @FeeEarner
             AND [TDB2].[MATTER] = @Matter
             --AND [TDB2].[TIMEORCHARGE] = 'T' KEYD-5124
        ORDER BY [TDB2].[RecordID] DESC

        IF @RecordID IS NOT NULL
          BEGIN
            UPDATE [TDB]
               SET [TDB].[StopwatchStatus] = @StopwatchStatus,
                   [TDB].[Post] = 'Y'
              FROM [dbo].[TimeDayBook] [TDB]
             WHERE [TDB].[RecordID] = @RecordID

            SELECT [TDB].[RecordID],
                   ISNULL([TDB].[Time], 0) AS [Minutes]
              FROM [dbo].[TimeDayBook] [TDB] WITH (nolock)
             WHERE [TDB].[RecordID] = @RecordID
          END
      END --(ELSE CONDITION) Insert conditions

  END -- ELSE CONDITION: IF @RecordID <> 0
END

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

CREATE PROCEDURE [dbo].[KEYHM_XMLDiaryDelegation]
(
	@DEL VARCHAR(MAX)
)
AS  
/*******************************************************************************************************
* Performs a diary delegation based on the XML string passed in.									   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_XMLDiaryDelegation]											   *
* Copied from			: [dbo].[ky_NETSPXMLDiaryDelegation]										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN  
  DECLARE @Return INT  
  
  EXEC @Return = [dbo].[KEYHM_ScalarXMLDiaryDelegation] @DEL  
  
  SELECT ISNULL(@Return, -4)  
END
GO

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

CREATE PROCEDURE
       [dbo].[KEYHM_XMLFlagDayBookEntriesForAdHocPosting]
      (@XML NVARCHAR(MAX))
AS
/*******************************************************************************************************
* Flags entries for Ad Hoc posting																	   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KEYHM_XMLFlagDayBookEntriesForAdHocPosting]							   *
* Copied from			: [dbo].[ky_NETXMLFlagDayBookEntriesForAdHocPosting]						   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2019-04-12	Vinodhan K		Created                                                                *
 *******************************************************************************************************/

BEGIN

	DECLARE @iSL INT

	BEGIN TRY
		EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
	END TRY
	BEGIN CATCH
		EXEC sp_xml_preparedocument @iSL OUTPUT, N'<AdHocPostDayBook/>'
	END CATCH

	UPDATE [TDB]
	   SET [TDB].[AdHocPosting] = 1
	   FROM OPENXML(@iSL, N'AdHocPostDayBook/DayBookItem')
	   WITH ([RecordID]             VARCHAR(10)     '@id') [SRC]
		   INNER JOIN [dbo].[TimeDayBook] [TDB]
				   ON [TDB].[RecordID] = [SRC].[RecordID]

	BEGIN TRY
		EXEC sp_xml_removedocument @iSL
	END TRY
	BEGIN CATCH
	END CATCH
END

GO

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

CREATE PROCEDURE      
       [dbo].[KEYHM_XMLMatterSearch]      
      (@Search        NVARCHAR(MAX),    
	   @PageNumber    INT,    
       @PageSize      INT,
	   @ColumnNames   VARCHAR(50) = '',
	   @FilterValues  VARCHAR(50) = '')      
AS      
/*******************************************************************************************************
* Performs a matter search based on search criteria passed in in XML format through @Search.           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_XMLMatterSearch]												   *
* Copied from			: [dbo].[ky_NETSPXMLMatterSearch2]											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
* 2020-02-25    Prabhu V          Applied Custom Filter Changes with Fetching the Closed Matter        *
*								  details as well                                                      *
* 2020-06-12    Arun V            Closed matter check have added in recent matter list                 *
 *******************************************************************************************************/
BEGIN      
      
DECLARE @closed                 NCHAR(1)      
DECLARE @orderby                NVARCHAR(50)      
DECLARE @order                  NVARCHAR(4)      
DECLARE @howmany                INT      
DECLARE @handler                NVARCHAR(10)      
DECLARE @which                  INT      
DECLARE @BitWiseID              BIGINT      
DECLARE @searchtext             VARCHAR(MAX)      
DECLARE @searchonlycode         VARCHAR(3)      
DECLARE @departmentdesc         VARCHAR(50)      
DECLARE @department             VARCHAR(5)      
DECLARE @worktypedesc           VARCHAR(50)      
DECLARE @worktype               VARCHAR(5)      
DECLARE @filecolourdesc         VARCHAR(20)      
DECLARE @filecolour             VARCHAR(3)      
DECLARE @feecode                VARCHAR(10)      
      
DECLARE @includename            BIT      
DECLARE @includedescription     BIT      
DECLARE @includeaddress         BIT      
DECLARE @includeemail           BIT      
DECLARE @includecode            BIT      
DECLARE @includeoldref          BIT      
DECLARE @includeuser1           BIT      
      
DECLARE @andorname              VARCHAR(3)      
DECLARE @andornamevalue         VARCHAR(200)      
DECLARE @andordescription       VARCHAR(3)      
DECLARE @andordescriptionvalue  VARCHAR(200)      
DECLARE @andoraddress           VARCHAR(3)      
DECLARE @andoraddressvalue      VARCHAR(200)      
DECLARE @andorcode              VARCHAR(3)      
DECLARE @andorcodevalue         VARCHAR(200)      
DECLARE @andorfeecode           VARCHAR(3)      
DECLARE @andorfeecodevalue      VARCHAR(200)      
DECLARE @andoroldref            VARCHAR(3)      
DECLARE @andoroldrefvalue       VARCHAR(200)      
DECLARE @andordept              VARCHAR(3)      
DECLARE @andordeptvalue         VARCHAR(200)      
DECLARE @andoruser1             VARCHAR(3)      
DECLARE @andoruser1value        VARCHAR(200)      
DECLARE @andoruser2             VARCHAR(3)      
DECLARE @andoruser2value        VARCHAR(200)      
DECLARE @andoruser3             VARCHAR(3)      
DECLARE @andoruser3value        VARCHAR(200)      
DECLARE @andoryourref           VARCHAR(3)      
DECLARE @andoryourrefvalue      VARCHAR(200)      
DECLARE @andorwtype             VARCHAR(3)      
DECLARE @andorwtypevalue        VARCHAR(200)      
      
DECLARE @iSL INT      
    
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   
      
BEGIN TRY      
EXEC sp_xml_preparedocument @iSL OUTPUT, @Search      
END TRY      
BEGIN CATCH      
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<search/>'      
END CATCH      
      
SELECT @closed = CASE ISNULL(SRC.[closed], N'N')      
                      WHEN N'Y' THEN N'Y'   
                      WHEN N'B' THEN N'B'      
                       END,      
       @orderby = ISNULL(SRC.[orderby], N''),      
       @order = CASE ISNULL(SRC.[order], N'DESC')
                     WHEN N'DESC'      
                          THEN N'DESC'      
                     ELSE N'ASC' END,      
       @howmany = ISNULL(SRC.[howmany], 500),      
       @handler = ISNULL(SRC.[handler], N''),      
       @which = CASE ISNULL(SRC.[which], 0)      
                     WHEN 1 THEN 1 --My Matters      
                     WHEN 2 THEN 2 --Recent Matters      
                     ELSE 0 END,   --All Matters      
       @searchtext = ISNULL(SRC.[search], ''),      
       @searchonlycode = ISNULL(SRC.[searchonlycode], ''),      
       @departmentdesc = ISNULL(SRC.[dept], ''),      
       @worktypedesc = ISNULL(SRC.[wtype], ''),      
       @filecolourdesc = ISNULL(SRC.[colour], ''),      
       @feecode = ISNULL(SRC.[feecodefilter], ''),      
       @includeaddress = ISNULL(SRC.[includeaddress], 0),      
       @includeemail = ISNULL(SRC.[includeemail], 0),      
       @includecode = ISNULL(SRC.[includecode], 0),      
       @includedescription = ISNULL(SRC.[includedescription], 0),      
       @includename = ISNULL(SRC.[includename], 0),      
       @includeoldref = ISNULL(SRC.[includeoldref], 0),      
       @includeuser1 = ISNULL(SRC.[includeuser1], 0),      
       @andorname = ISNULL(SRC.[andorname], ''),      
       @andornamevalue = ISNULL(SRC.[andornamevalue], ''),      
       @andordescription = ISNULL(SRC.[andordescription], ''),      
       @andordescriptionvalue = ISNULL(SRC.[andordescriptionvalue], ''),      
       @andoraddress = ISNULL(SRC.[andoraddress], ''),      
       @andoraddressvalue = ISNULL(SRC.[andoraddressvalue], ''),      
       @andorcode = ISNULL(SRC.[andorcode], ''),      
       @andorcodevalue = ISNULL(SRC.[andorcodevalue], ''),      
       @andorfeecode = ISNULL(SRC.[andorfeecode], ''),      
       @andorfeecodevalue = ISNULL(SRC.[andorfeecodevalue], ''),      
       @andoroldref = ISNULL(SRC.[andoroldref], ''),      
       @andoroldrefvalue = ISNULL(SRC.[andoroldrefvalue], ''),      
       @andordept = ISNULL(SRC.[andordept], ''),      
       @andordeptvalue = ISNULL(SRC.[andordeptvalue], ''),      
       @andoruser1 = ISNULL(SRC.[andoruser1], ''),      
       @andoruser1value = ISNULL(SRC.[andoruser1value], ''),      
       @andoruser2 = ISNULL(SRC.[andoruser2], ''),      
       @andoruser2value = ISNULL(SRC.[andoruser2value], ''),      
       @andoruser3 = ISNULL(SRC.[andoruser3], ''),      
       @andoruser3value = ISNULL(SRC.[andoruser3value], ''),      
       @andoryourref = ISNULL(SRC.[andoryourref], ''),      
       @andoryourrefvalue = ISNULL(SRC.[andoryourrefvalue], ''),      
       @andorwtype = ISNULL(SRC.[andorwtype], ''),      
       @andorwtypevalue = ISNULL(SRC.[andorwtypevalue], '')      
  FROM OPENXML(@iSL, N'search')      
  WITH ([closed]                   NCHAR(1)        '@closed',      
        [orderby]                  NVARCHAR(50)    '@orderby',      
        [order]                    NVARCHAR(4)     '@order',      
        [howmany]                  INT             '@howmany',      
        [handler]                  NVARCHAR(10)    '@handler',      
        [which]                    INT             '@which',      
        [search]                   VARCHAR(MAX)    '@search',      
        [searchonlycode]           VARCHAR(3)      '@searchonlycode',      
        [dept]                     VARCHAR(50)     '@departmentfilter',      
        [wtype]                    VARCHAR(50)     '@worktypefilter',      
        [colour]                   VARCHAR(20)     '@filecolourfilter',      
        [feecodefilter]            VARCHAR(10)     '@feecodefilter',      
        [includeaddress]           BIT             'include/includefield[@name="address"]',      
        [includecode]              BIT             'include/includefield[@name="code"]',      
        [includedescription]       BIT             'include/includefield[@name="description"]',      
        [includename]              BIT             'include/includefield[@name="name"]',      
        [includeoldref]            BIT             'include/includefield[@name="oldref"]',      
        [includeuser1]             BIT             'include/includefield[@name="user1"]',      
        [includeemail]             BIT             'include/includefield[@name="email"]',      
        [andorname]                VARCHAR(3)      'andor/andorfield[@name="name"]/@andor',      
        [andornamevalue]           VARCHAR(100)    'andor/andorfield[@name="name"]/@search',      
        [andordescription]         VARCHAR(3)      'andor/andorfield[@name="description"]/@andor',      
        [andordescriptionvalue]    VARCHAR(100)    'andor/andorfield[@name="description"]/@search',      
        [andoraddress]             VARCHAR(3)      'andor/andorfield[@name="address"]/@andor',      
        [andoraddressvalue]        VARCHAR(100)    'andor/andorfield[@name="address"]/@search',      
        [andorcode]                VARCHAR(3)      'andor/andorfield[@name="code"]/@andor',      
        [andorcodevalue]           VARCHAR(100)    'andor/andorfield[@name="code"]/@search',      
        [andorfeecode]             VARCHAR(3)      'andor/andorfield[@name="feecode"]/@andor',      
        [andorfeecodevalue]        VARCHAR(100)    'andor/andorfield[@name="feecode"]/@search',      
        [andoroldref]              VARCHAR(3)      'andor/andorfield[@name="oldref"]/@andor',      
        [andoroldrefvalue]         VARCHAR(100)    'andor/andorfield[@name="oldref"]/@search',      
        [andordept]                VARCHAR(3)      'andor/andorfield[@name="dept"]/@andor',      
        [andordeptvalue]           VARCHAR(100)    'andor/andorfield[@name="dept"]/@search',      
        [andoruser1]               VARCHAR(3)      'andor/andorfield[@name="user1"]/@andor',      
        [andoruser1value]          VARCHAR(100)    'andor/andorfield[@name="user1"]/@search',      
        [andoruser2]               VARCHAR(3)      'andor/andorfield[@name="user2"]/@andor',      
        [andoruser2value]          VARCHAR(100)    'andor/andorfield[@name="user2"]/@search',      
        [andoruser3]               VARCHAR(3)      'andor/andorfield[@name="user3"]/@andor',      
        [andoruser3value]          VARCHAR(100)    'andor/andorfield[@name="user3"]/@search',      
        [andoryourref]             VARCHAR(3)      'andor/andorfield[@name="yourref"]/@andor',      
        [andoryourrefvalue]        VARCHAR(100)    'andor/andorfield[@name="yourref"]/@search',      
        [andorwtype]               VARCHAR(3)      'andor/andorfield[@name="wtype"]/@andor',      
        [andorwtypevalue]          VARCHAR(100)    'andor/andorfield[@name="wtype"]/@search') SRC      
      
IF @filecolourdesc <> ''      
  BEGIN      
    SELECT @filecolour = FC.[COLOURCODE]      
      FROM [dbo].[FileColours] FC WITH (NOLOCK)      
     WHERE FC.[COLOURDESC] = @filecolourdesc      
  END      
      
SET @filecolour = ISNULL(@filecolour, '')      
      
IF @departmentdesc <> ''      
  BEGIN      
    SELECT @department = DP.[CODE]      
      FROM [dbo].[Departments] DP WITH (NOLOCK)      
     WHERE DP.[DESCRIPTION] = @departmentdesc      
  END      
      
SET @department = ISNULL(@department, '')      
      
IF @worktypedesc <> ''      
  BEGIN      
    IF @worktypedesc LIKE 'Unknown Worktype: %'      
      BEGIN      
        SELECT @worktype = WT.[CODE]      
          FROM [dbo].[WorkTypes] WT WITH (NOLOCK)      
         WHERE 'Unknown Worktype: ' + WT.[CODE] = @worktypedesc      
            OR WT.[DESC] = @worktypedesc      
      END      
    ELSE      
      BEGIN      
        SELECT @worktype = WT.[CODE]      
          FROM [dbo].[WorkTypes] WT WITH (NOLOCK)      
         WHERE WT.[DESC] = @worktypedesc      
      END      
  END      
      
SET @worktype = ISNULL(@worktype, '')      
      
SET @feecode = ISNULL(@feecode, '')      
      
EXEC sp_xml_removedocument @iSL      
      
DECLARE @NCOMMAND NVARCHAR(MAX)      
DECLARE @HasWhere BIT      
      
SET @HasWhere = 0      
      
SET @handler = CASE WHEN RTRIM(ISNULL(@handler, '')) = '' THEN 'ADM' ELSE RTRIM(@handler) END      
      
SELECT @BitWiseID = HNG.[BitWiseID]      
  FROM HandlerNETGroupMembership HNG WITH (NOLOCK)      
 WHERE HNG.[HANDLER] = CONVERT(VARCHAR(10), @handler)      
      
SET @BitWiseID = ISNULL(@BitWiseID, [dbo].[KEYHM_FN_GetOldPermissions](RTRIM(ISNULL(@handler, ''))))      
      
IF (@handler = 'ADM')      
  BEGIN      
    SET @BitWiseID = CONVERT(BIGINT, -1)      
  END     
  
  -- Custom Filter Start
SET @NCOMMAND = N'   
DECLARE @StatusCount INT = 0;
IF @ColumnNames <> ''''
BEGIN
DECLARE @CustomFilter TABLE
       ([Status]     VARCHAR(20))	

	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  

	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 = ''Closed'')
		INSERT INTO @CustomFilter ([Status]) VALUES (@FilterValue)	   

	   SET @lptcnt = @lptcnt + 1;   

	END
	
	SET @StatusCount = (SELECT COUNT(1) FROM @CustomFilter WHERE [Status] IS NOT NULL AND [Status] <>'''')	
END '
-- Custom Filter End

SET @NCOMMAND = @NCOMMAND + N'      
  --SELECT ''How Many: '' + CONVERT(VARCHAR(10), @HowMany)      
  --SELECT ''Handler: '' + @Handler      
  --SELECT ''BitWise ID: '' + CONVERT(VARCHAR(10), @BitWiseID)      
      
DECLARE @Result TABLE      
       ([id]                    INT                       IDENTITY(1, 1) PRIMARY KEY CLUSTERED,      
        [Time]                  VARCHAR(5)                NOT NULL,      
        [Code]                  VARCHAR(20)               NOT NULL,      
        [FileColour]            VARCHAR(20)               NOT NULL,      
        [FileColour_Fld]        VARCHAR(20)               NOT NULL,      
        [BackgroundColour]      VARCHAR(30)               NOT NULL,      
        [TextColour]            VARCHAR(30)               NOT NULL,      
        [Name]                  VARCHAR(256)              NOT NULL,      
        [Description]           VARCHAR(200)              NOT NULL,      
        [Fe]                    VARCHAR(30)               NOT NULL,      
        [FeeCode]               VARCHAR(10)               NOT NULL,      
        [FeeEarner]             VARCHAR(30)               NOT NULL,      
        [User1]                 VARCHAR(100)              NOT NULL,      
        [User2]                 VARCHAR(100)              NOT NULL,      
        [User3]                 VARCHAR(100)              NOT NULL,      
        [Started]               DATETIME                  NOT NULL,      
        [Dept]                  VARCHAR(50)               NOT NULL,      
        [WorkType]              VARCHAR(50)               NOT NULL,      
        [Privileges]            BIGINT                    NOT NULL,      
        [OldRef]                VARCHAR(12)               NOT NULL,      
        [Address]               VARCHAR(500)              NOT NULL,      
        [Email]                 VARCHAR(50)               NOT NULL,      
        [Closed]                CHAR(1)                   NOT NULL,      
        [OrgCloseDate]          DATETIME                      NULL,      
        [CloseDate]             DATETIME                      NULL,      
        [FileRGBColour]         INT                       NOT NULL,      
        [LastAccessed]          DATETIME                      NULL,      
        [PhoneNumber]           VARCHAR(50)               NOT NULL,      
        [FileNum]               INT                       NOT NULL,      
        [ClientCode]            VARCHAR(10)               NOT NULL,      
        [DepartmentCode]        VARCHAR(5)                NOT NULL,      
        [FeeEarnerTeam]         VARCHAR(10)               NOT NULL,      
        [TeamName]              VARCHAR(30)               NOT NULL,      
        [YourRef]               VARCHAR(100)              NOT NULL,      
        [CaseStatusCode]        VARCHAR(6)                NOT NULL,      
        [CaseStatusDesc]        VARCHAR(50)               NOT NULL)      
      
  INSERT      
    INTO @Result      
        ([Time],      
         [Code],      
         [FileColour],      
         [FileColour_Fld],      
         [BackgroundColour],      
         [TextColour],      
         [Name],      
         [Description],      
         [Fe],      
         [FeeCode],      
         [FeeEarner],      
         [User1],      
         [User2],      
         [User3],      
         [Started],      
         [Dept],      
         [WorkType],      
  [Privileges],      
         [OldRef],      
         [Address],      
         [Email],      
         [Closed],      
         [OrgCloseDate],      
         [CloseDate],      
         [FileRGBColour],      
         [LastAccessed],      
         [PhoneNumber],      
         [FileNum],      
         [ClientCode],      
         [DepartmentCode],      
         [FeeEarnerTeam],      
         [TeamName],      
         [YourRef],      
         [CaseStatusCode],      
         [CaseStatusDesc])      
    
  SELECT      
         CASE WHEN TTT.[TOTALTIME] = ''00:00''      
                   THEN ''''      
              ELSE TTT.[TOTALTIME] END													  AS [Time],      
         SM.[Code]                                                                        AS [Code],      
         SM.[FileColourDescription]                                                       AS [FileColour],      
         SM.[FileColourDescription]                                                       AS [FileColour_Fld],      
         SM.[FileBackgroundColour]                                                        AS [BackgroundColour],      
         SM.[TextColour]                                                                  AS [TextColour],      
         SM.[Name]                                                                        AS [Name],      
         SM.[Description]                                                                 AS [Description],      
         SM.[HandlerName]                                                                 AS [Fe],      
         SM.[FECode]                                                                      AS [FeeCode],      
         SM.[HandlerName]                                                                 AS [FeeEarner],      
         SM.[User1]                                                                       AS [User1],      
         SM.[User2]                                                                       AS [User2],      
         SM.[User3]                                                                       AS [User3],      
         SM.[Started]                                                                     AS [Started],      
         SM.[DeptDescription]                                                             AS [Dept],      
         SM.[WTypeDescription]                                                            AS [WorkType],      
         SM.[Privileges]                                                                  AS [Privileges],      
         SM.[OldRef]                                                                      AS [OldRef],      
         SM.[Address]                                                                     AS [Address],      
         SM.[Email]                                                                       AS [Email],      
         CASE WHEN SM.[Closed] = 0 THEN ''N'' ELSE ''Y'' END                              AS [Closed],      
         SM.[OrgClosedDate]                                                               AS [OrgCloseDate],      
         SM.[CloseDate]                                                                   AS [CloseDate],      
         SM.[FileRGBColour]                                                               AS [FileRGBColour],      
         CASE WHEN YEAR(ISNULL(RML.[DateField], CONVERT(DATETIME, ''18000101''))) < 1901      
                   THEN NULL      
              ELSE ISNULL(RML.[DateField], CONVERT(DATETIME, ''18000101'')) END           AS [LastAccessed],      
         SM.[PhoneNumber]                                                                 AS [PhoneNumber],      
         SM.[FileNum]                                                                     AS [FileNum],      
         SM.[ClientCode]                                                                  AS [ClientCode],      
         SM.[Dept]                                                                        AS [DepartmentCode],      
         SM.[Team]                                                                        AS [FeeEarnerTeam],      
         SM.[TeamName]                                                                    AS [TeamName],      
         SM.[YourRef]                                                                     AS [YourRef],      
         SM.[MatterStatus]                                                                AS [CaseStatusCode],      
         SM.[MatterStatusDescription]                                                     AS [CaseStatusDesc]
    FROM [dbo].[SearchMatters] SM WITH (NOLOCK)      
         CROSS APPLY (SELECT SUBSTRING(CONVERT(VARCHAR, DATEADD(minute, ISNULL(SUM(ISNULL(TDB.[time], 0)), 0), ''19000101''), 108), 1, 5) AS [TOTALTIME]      
                        FROM [dbo].[TimeDayBook] TDB WITH (NOLOCK)      
                       WHERE TDB.[FeeEarn] = @Handler      
                         AND TDB.[matter] = SM.[code]
					     ) TTT'      
      
SET @NCOMMAND = @NCOMMAND + N'      
         LEFT OUTER JOIN [dbo].[RecentMatterList] RML WITH (NOLOCK)      
                      ON RML.[FEE] = @handler      
                     AND RML.[MATTER] = SM.[Code]
	      WHERE (@StatusCount = 0 OR SM.[Closed] 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 [Status] FROM @CustomFilter WHERE [Status] IS NOT NULL and [Status] <>''''),'','',''</RowData><RowData>'') + ''</RowData></XMLRoot>'' AS XML) AS x
																)t
																CROSS APPLY x.nodes(''/XMLRoot/RowData'')m(n)) FILTERVALUETBLFnl)) '      
      
IF (@BitWiseID = 0)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   AND (   SM.[Privileges] = 0      
          OR SM.[Privileges] = -1)'      
  END      
ELSE IF (@BitWiseID = -1)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   AND 1 = 1'      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   AND SM.[Privileges] & @BitWiseID <> 0'      
  END      
      
IF (@which = 1)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode] = @handler'      
  END      
      
IF (@closed = 'N')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Closed] = 0'      
  END      
      
IF (@closed = 'Y')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Closed] = 1'      
  END      
      
IF (@worktype <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[WType] = @WorkType'      
  END      
      
IF (@department <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Dept] = @department'      
  END      
      
IF (@filecolour <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FileColour] = @filecolour'      
  END      
      
IF (@feecode <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode] = @feecode'      
  END      
      
DECLARE @SearchIncludes NVARCHAR(MAX)      
      
SET @SearchIncludes = N''      
      
IF (@searchtext <> '')      
  BEGIN      
    IF SUBSTRING(@searchtext, 1, 1) <> '%'      
      BEGIN      
        SET @searchtext = '%' + @searchtext      
      END      
      
    IF SUBSTRING(@searchtext, LEN(@searchtext), 1) <> '%'      
      BEGIN      
        SET @searchtext = @searchtext + '%'      
      END      
      
    SET @searchtext = @searchtext COLLATE SQL_Latin1_General_Cp1251_CS_AS      
          
     IF (@includeaddress = 0)       
    AND (@includecode = 0)      
    AND (@includedescription = 0)      
    AND (@includename = 0)      
    AND (@includeoldref = 0)      
    AND (@includeuser1 = 0)      
    AND (@includeemail = 0)      
      BEGIN      
        -- This is the standard call - not from Advanced Matter Search, so we search in everything      
        IF @SearchIncludes <> N''      
          BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
          END      
      
        IF @searchonlycode <> 'yes'      
          BEGIN      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]         LIKE @searchtext      
          OR SM.[Code]                     LIKE @searchtext      
          OR SM.[User1]                    LIKE @searchtext      
          OR SM.[User2]                    LIKE @searchtext      
          OR SM.[User3]                    LIKE @searchtext      
          OR SM.[OldRef]                   LIKE @searchtext      
          OR SM.[YourRef]                  LIKE @searchtext      
          OR SM.[NCName]                   LIKE @searchtext      
          OR SM.[NCAddress]                LIKE @searchtext      
          OR SM.[Email]                    LIKE @searchtext      
          OR SM.[NCHandlerName]            LIKE @searchtext      
          OR SM.[NCPartnerName]            LIKE @searchtext      
          OR SM.[DeptDescription]          LIKE @searchtext      
          OR SM.[WTypeDescription]         LIKE @searchtext      
          OR SM.[FileColourDescription]    LIKE @searchtext      
          OR SM.[MatterStatusDescription]  LIKE @searchtext'      
          END      
        ELSE      
          BEGIN      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Code]                  LIKE @searchtext'      
          END      
      
      END      
    ELSE      
      BEGIN      
        IF (@includeaddress = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCAddress]             LIKE @searchtext'      
          END      
      
        IF (@includecode = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Code]                  LIKE @searchtext'      
          END      
      
        IF (@includedescription = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]         LIKE @searchtext'      
          END      
      
        IF (@includename = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCName]                LIKE @searchtext'      
          END      
      
        IF (@includeoldref = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[OldRef]                LIKE @searchtext'      
          END      
      
        IF (@includeuser1 = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[User1]                 LIKE @searchtext'      
          END      
      
        IF (@includeemail = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Email]                 LIKE @searchtext'      
          END      
      
      END      
                  
  END      
      
IF @andoraddress = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoraddressvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = '%' + @andoraddressvalue       
      END      
      
    IF SUBSTRING(@andoraddressvalue, LEN(@andoraddressvalue), 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = @andoraddressvalue + '%'      
      END      
      
    SET @andoraddressvalue = @andoraddressvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCAddress]					LIKE @andoraddressvalue'      
  END      
      
IF @andorcode = 'OR'      
  BEGIN      
    IF CHARINDEX('%', @andorcodevalue, 1) = 0      
      BEGIN      
        IF SUBSTRING(@andorcodevalue, 1, 1) <> '%'      
          BEGIN      
            SET @andorcodevalue = '%' + @andorcodevalue       
          END      
      
        IF SUBSTRING(@andorcodevalue, LEN(@andorcodevalue), 1) <> '%'      
          BEGIN      
            SET @andorcodevalue = @andorcodevalue + '%'      
          END      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[Code]							LIKE @andorcodevalue'      
  END      
      
IF @andordept = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[Dept]= @andordeptvalue'      
  END      
      
IF @andordescription = 'OR'      
  BEGIN      
    IF SUBSTRING(@andordescriptionvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = '%' + @andordescriptionvalue       
      END      
      
    IF SUBSTRING(@andordescriptionvalue, LEN(@andordescriptionvalue), 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = @andordescriptionvalue + '%'      
      END      
      
    SET @andordescriptionvalue = @andordescriptionvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]			LIKE @andordescriptionvalue'      
  END      
      
IF @andorfeecode = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[FECode] = @andorfeecodevalue'      
  END      
      
IF @andorname = 'OR'      
  BEGIN      
    IF SUBSTRING(@andornamevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andornamevalue = '%' + @andornamevalue       
      END      
      
    IF SUBSTRING(@andornamevalue, LEN(@andornamevalue), 1) <> '%'      
      BEGIN      
        SET @andornamevalue = @andornamevalue + '%'      
      END      
      
    SET @andornamevalue = @andornamevalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCName]							LIKE @andornamevalue'      
  END      
      
IF @andoroldref = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoroldrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = '%' + @andoroldrefvalue       
      END      
      
    IF SUBSTRING(@andoroldrefvalue, LEN(@andoroldrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = @andoroldrefvalue + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[OldRef]							LIKE @andoroldrefvalue'      
  END      
      
IF @andoruser1 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser1value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser1value = '%' + @andoruser1value       
      END      
      
   IF SUBSTRING(@andoruser1value, LEN(@andoruser1value), 1) <> '%'      
      BEGIN      
        SET @andoruser1value = @andoruser1value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User1]						  LIKE @andoruser1value'      
  END      
      
IF @andoruser2 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser2value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser2value = '%' + @andoruser2value       
      END      
      
    IF SUBSTRING(@andoruser2value, LEN(@andoruser2value), 1) <> '%'      
      BEGIN      
        SET @andoruser2value = @andoruser2value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User2]						   LIKE @andoruser2value'      
  END      
      
IF @andoruser3 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser3value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser3value = '%' + @andoruser3value       
      END      
      
    IF SUBSTRING(@andoruser3value, LEN(@andoruser3value), 1) <> '%'      
      BEGIN      
        SET @andoruser3value = @andoruser3value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User3]						   LIKE @andoruser3value'      
  END      
      
IF @andorwtype = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[WType] = @andorwtypevalue'      
  END      
      
IF @andoryourref = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoryourrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = '%' + @andoryourrefvalue       
      END      
      
    IF SUBSTRING(@andoryourrefvalue, LEN(@andoryourrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = @andoryourrefvalue + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[YourRef]							LIKE @andoryourrefvalue'      
  END      
      
--SELECT @SearchIncludes      
      
IF @SearchIncludes <> ''      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND (   ' + @SearchIncludes + N')'      
  END      
      
IF @andoraddress = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoraddressvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = '%' + @andoraddressvalue       
      END      
      
    IF SUBSTRING(@andoraddressvalue, LEN(@andoraddressvalue), 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = @andoraddressvalue + '%'      
      END      
      
    SET @andoraddressvalue = @andoraddressvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCAddress]             LIKE @andoraddressvalue'      
  END      
      
IF @andorcode = 'AND'      
  BEGIN      
    IF SUBSTRING(@andorcodevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andorcodevalue = '%' + @andorcodevalue       
      END      
      
    IF SUBSTRING(@andorcodevalue, LEN(@andorcodevalue), 1) <> '%'      
      BEGIN      
        SET @andorcodevalue = @andorcodevalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Code]                  LIKE @andorcodevalue'      
  END      
      
IF @andordept = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Dept]              = @andordeptvalue'      
  END      
      
IF @andordescription = 'AND'      
  BEGIN      
    IF SUBSTRING(@andordescriptionvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = '%' + @andordescriptionvalue       
      END      
      
    IF SUBSTRING(@andordescriptionvalue, LEN(@andordescriptionvalue), 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = @andordescriptionvalue + '%'      
      END      
      
    SET @andordescriptionvalue = @andordescriptionvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCDescription]         LIKE @andordescriptionvalue'      
  END      
      
IF @andorfeecode = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode]                = @andorfeecodevalue'      
  END      
      
IF @andorname = 'AND'      
  BEGIN      
    IF SUBSTRING(@andornamevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andornamevalue = '%' + @andornamevalue       
      END      
      
IF SUBSTRING(@andornamevalue, LEN(@andornamevalue), 1) <> '%'      
      BEGIN      
        SET @andornamevalue = @andornamevalue + '%'      
      END      
      
    SET @andornamevalue = @andornamevalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCName]                LIKE @andornamevalue'      
  END      
      
IF @andoroldref = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoroldrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = '%' + @andoroldrefvalue       
      END      
      
    IF SUBSTRING(@andoroldrefvalue, LEN(@andoroldrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = @andoroldrefvalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[OldRef]                LIKE @andoroldrefvalue'      
  END      
      
IF @andoruser1 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser1value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser1value = '%' + @andoruser1value       
      END      
      
    IF SUBSTRING(@andoruser1value, LEN(@andoruser1value), 1) <> '%'      
      BEGIN      
        SET @andoruser1value = @andoruser1value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User1]                 LIKE @andoruser1value'      
  END      
      
IF @andoruser2 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser2value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser2value = '%' + @andoruser2value       
      END      
      
    IF SUBSTRING(@andoruser2value, LEN(@andoruser2value), 1) <> '%'      
      BEGIN      
        SET @andoruser2value = @andoruser2value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User2]                 LIKE @andoruser2value'      
  END      
      
IF @andoruser3 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser3value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser3value = '%' + @andoruser3value       
      END      
      
    IF SUBSTRING(@andoruser3value, LEN(@andoruser3value), 1) <> '%'      
      BEGIN      
        SET @andoruser3value = @andoruser3value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User3]                 LIKE @andoruser3value'      
  END      
      
IF @andorwtype = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[WType]                 = @andorwtypevalue'      
  END      
      
IF @andoryourref = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoryourrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = '%' + @andoryourrefvalue       
      END      
      
    IF SUBSTRING(@andoryourrefvalue, LEN(@andoryourrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = @andoryourrefvalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[YourRef]               LIKE @andoryourrefvalue'      
  END      
      

SET @NCOMMAND = @NCOMMAND + N'      
ORDER BY ' + CASE @orderby      
                  WHEN N'description'      
                       THEN N'CASE WHEN SM.[Description] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Description] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Code'      
                       THEN N'CASE WHEN SM.[Code] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Code] ' + @order      
                  WHEN N'Name'      
                       THEN N'CASE WHEN SM.[Name] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Name] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Address'      
                       THEN N'CASE WHEN SM.[Address] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Address] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Email'      
                       THEN N'CASE WHEN SM.[Email] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Email] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'PhoneNumber'      
                       THEN N'CASE WHEN SM.[PhoneNumber] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[PhoneNumber] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'user1'      
                      THEN N'CASE WHEN SM.[User1] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User1] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'user2'      
                       THEN N'CASE WHEN SM.[User2] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User2] ' + @order + N',      
         SM.[Code] ' + @order      
    WHEN N'user3'      
                       THEN N'CASE WHEN SM.[User3] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User3] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'yourref'      
                       THEN N'CASE WHEN SM.[YourRef] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[YourRef] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'OldRef'      
                       THEN N'CASE WHEN SM.[OldRef] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[OldRef] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileNum'      
                       THEN N'CASE WHEN SM.[FileNum] = 0      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileNum] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'department'      
                       THEN N'CASE WHEN SM.[DeptDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[DeptDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Dept'      
                       THEN N'CASE WHEN SM.[DeptDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[DeptDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'worktype'      
                       THEN N'CASE WHEN SM.[WTypeDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[WTypeDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FeeCode'      
                       THEN N'CASE WHEN SM.[FECode] = ''''      
                   THEN 2      
              WHEN SM.[FECode] = ''ADM''      
                   THEN 1      
 ELSE 0 END,      
         SM.[FECode] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FeeEarner'      
                       THEN N'CASE WHEN SM.[HandlerName] = '''' AND SM.[FECode] = ''''      
                   THEN 3      
              WHEN SM.[HandlerName] = ''''      
                   THEN 2      
              WHEN SM.[HandlerName] = ''Admin''      
                   THEN 1      
              ELSE 0 END,      
         SM.[HandlerName] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileColour_Fld'      
                       THEN N'CASE WHEN SM.[FileColourDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileColourDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileColour'      
                       THEN N'CASE WHEN SM.[FileColourDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileColourDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'started'      
                       THEN N'SM.[Started] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'LastAccessed'      
                       THEN N'CASE WHEN RML.[DateField] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         RML.[DateField] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'closedate'      
                       THEN N'CASE WHEN SM.[CloseDate] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[CloseDate] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'orgcloseddate'      
                       THEN N'CASE WHEN SM.[orgcloseddate] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[orgcloseddate] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'casestatusdesc'      
                       THEN N'CASE WHEN SM.[MatterStatusDescription] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[MatterStatusDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  ELSE CASE WHEN @Which <> 2      
                                 THEN N'SM.[Code] ' + @order      
                            ELSE N'CASE WHEN RML.[DateField] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         RML.[DateField] DESC,      
         SM.[Code] ' + @order END END      
      
SET @NCOMMAND = @NCOMMAND + N'    
      
  SELECT * FROM(    
  SELECT ROW_NUMBER() OVER(ORDER BY [Res].[id]) AS [RowNumber],    
   [RES].[id],      
         [RES].[Time],      
         [RES].[Code],      
         [RES].[FileColour],      
         [RES].[FileColour_Fld],      
         [RES].[BackgroundColour],      
         [RES].[TextColour],      
         [RES].[Name],      
         [RES].[Description],      
         [RES].[Fe],      
         [RES].[FeeCode],      
         [RES].[FeeEarner],      
         [RES].[User1],      
         [RES].[User2],      
         [RES].[User3],      
         [RES].[Started],      
         [RES].[Dept],      
         [RES].[WorkType],      
         [RES].[Privileges],      
         [RES].[OldRef],      
         [RES].[Address],      
         [RES].[Email],      
         [RES].[Closed],      
         [RES].[OrgCloseDate],      
         [RES].[CloseDate],      
         [RES].[FileRGBColour],      
         [RES].[LastAccessed],      
         [RES].[PhoneNumber],      
         [RES].[FileNum],      
         [RES].[ClientCode],      
         [RES].[DepartmentCode],      
         [RES].[FeeEarnerTeam],      
         [RES].[TeamName],      
         [RES].[YourRef],      
         [RES].[CaseStatusCode],      
         [RES].[CaseStatusDesc]      
    FROM @Result [RES])AS MatterTable WHERE [Closed]=''N'' AND  MatterTable.[RowNumber] BETWEEN @StartRow AND @EndRow ORDER BY MatterTable.[id] ASC      
      
	SELECT  
		COUNT([RES].[id]) AS [TotalRecord]  
	FROM  
		@Result [RES]  
	WHERE
		 [Closed]=''N''
  
    SELECT
		USERPROMPT1 AS [UserPrompt1],
		USERPROMPT2 AS [UserPrompt2],
		USERPROMPT3 AS [UserPrompt3],
		YourRef     AS [YourRef]
    FROM
	    [Control]'

EXECUTE sp_executesql @NCOMMAND,      
                      N'@HowMany               INT,      
                        @BitWiseID             BIGINT,      
                        @Handler               VARCHAR(10),      
                        @WorkType              VARCHAR(5),      
                        @department            VARCHAR(5),      
                        @filecolour            VARCHAR(3),      
                        @feecode               VARCHAR(10),      
                        @searchtext            VARCHAR(MAX),      
                        @andoraddressvalue     VARCHAR(200),      
                        @andorcodevalue        VARCHAR(200),      
                        @andordeptvalue        VARCHAR(200),      
                        @andordescriptionvalue VARCHAR(200),      
                        @andorfeecodevalue     VARCHAR(200),      
                        @andornamevalue        VARCHAR(200),      
                        @andoroldrefvalue      VARCHAR(200),      
                        @andoruser1value       VARCHAR(200),      
                        @andoruser2value       VARCHAR(200),      
                        @andoruser3value       VARCHAR(200),      
                        @andorwtypevalue       VARCHAR(200),      
                        @andoryourrefvalue     VARCHAR(200),    
					    @StartRow			   INT,    
					    @EndRow                INT,
					    @ColumnNames           VARCHAR(50),
					    @FilterValues          VARCHAR(50)',      
                      @Howmany,      
                      @BitWiseID,      
                      @handler,      
                      @worktype,      
                      @department,      
                      @filecolour,      
                      @feecode,      
                      @searchtext,      
                      @andoraddressvalue,      
                      @andorcodevalue,      
                      @andordeptvalue,      
                      @andordescriptionvalue,      
                      @andorfeecodevalue,      
                      @andornamevalue,      
                      @andoroldrefvalue,      
                      @andoruser1value,      
                      @andoruser2value,      
                      @andoruser3value,      
                      @andorwtypevalue,      
                      @andoryourrefvalue,    
					  @StartRow,    
					  @EndRow,
					  @ColumnNames,
					  @FilterValues    
END

GO

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

CREATE PROCEDURE [dbo].[KEYHM_XMLPostDayBook] (@XML NVARCHAR(MAX))
AS
/*******************************************************************************************************
* Posts valid entries from the Time Day Book into the Time Entry.									   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KEYHM_XMLPostDayBook]												   *
* Copied from			: [dbo].[ky_NETXMLPostDayBook]												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2019-04-24    Vinodhan K        Created                                                              *
 *******************************************************************************************************/
BEGIN

DECLARE @iSL INT
DECLARE @Handler           VARCHAR(10)
DECLARE @HSEClientGroup    VARCHAR(20)
DECLARE @UPDByHandler      VARCHAR(10)
DECLARE @User              NVARCHAR(128)
DECLARE @UpdateRestriction INT

BEGIN TRY
EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
END TRY
BEGIN CATCH
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<PostDayBook/>'
END CATCH

SELECT @Handler           = [SRC].[Handler],
       @HSEClientGroup    = [SRC].[HSEClientGroup],
       @UPDByHandler      = [SRC].[UPDByHandler],
       @User              = [SRC].[User],
       @UpdateRestriction = [SRC].[UpdateRestriction]
FROM OPENXML(@iSL, N'PostDayBook')
WITH ([Handler]             VARCHAR(10)     '@handler',
      [HSEClientGroup]      VARCHAR(20)     '@hseclientgroup',
      [UPDByHandler]        VARCHAR(10)     '@updbyhandler',
      [User]                NVARCHAR(128)   '@user',
      [UpdateRestriction]   INT             '@updaterestriction') [SRC]

BEGIN TRY
EXEC sp_xml_removedocument @iSL
END TRY
BEGIN CATCH
END CATCH

SET @Handler            = ISNULL(@Handler, '')
SET @HSEClientGroup     = ISNULL(@HSEClientGroup, '')
SET @UPDByHandler       = ISNULL(@UPDByHandler, '')
SET @User               = ISNULL(@User, N'')
SET @UpdateRestriction  = ISNULL(@UpdateRestriction, 0)

  DECLARE @MAXID int
  DECLARE @Continue int
  DECLARE @COMMAND int
  DECLARE @AxleErrors int
  DECLARE @PERIOD INT
  DECLARE @YEAR INT
  DECLARE @IsSAM4 BIT
  DECLARE @TUTNUMVALUE DECIMAL(17, 2)
  DECLARE @RoundupUnits BIT

  SET @RoundupUnits = 0

  SELECT @RoundupUnits = [SET].[KeyValue]
    FROM [dbo].[Settings] [SET]
   WHERE [SET].[KeyName] = 'RoundupUnits'

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

  IF @IsSAM4 = 0
    BEGIN
      SELECT @PERIOD=ISNULL(CURPER,0),
             @YEAR=ISNULL(CL.[YEAR],0)
        FROM [CONTROL] CL
    END
  ELSE
    BEGIN
      SET @PERIOD=(SELECT ISNULL(numvalue,0) FROM CtrlNum WHERE code='CurPeriod')
      SET @YEAR=(SELECT ISNULL(numvalue,0) FROM CtrlNum WHERE code='CurYear')
    END

  SET @PERIOD = ISNULL(@PERIOD, 0)
  SET @YEAR = ISNULL(@YEAR, 0)

  IF (@RoundupUnits = 0)
    BEGIN
      SET @TUTNUMVALUE = 1
    END
  ELSE
    BEGIN
      IF @IsSAM4 = 1
        BEGIN
          SELECT @TUTNUMVALUE = CTN.[NumValue]
            FROM [dbo].[CtrlNum] CTN
           WHERE CTN.[Code] = 'TimeUnit'
        END

      SET @TUTNUMVALUE = CASE WHEN ISNULL(@TUTNUMVALUE, 0) = 0 THEN 6 ELSE @TUTNUMVALUE END
    END

  DECLARE @NTEID TABLE
         ([ID]            int      identity(1, 1),
          [NEWID]         int,
          [RECORDID]      int)

  DECLARE @PDMAT TABLE
         ([ID]            int      identity(1, 1),
          [CODE]          varchar(20))

  DECLARE @RDUP TABLE
         ([RECORDID]      int)

  SELECT @AxleErrors = COUNT(1)
    FROM [dbo].[KEYHM_WDTimeDayBookWithAxleErrors]
        (@HSEClientGroup,
         @Handler) AXER
   WHERE AXER.[IsAxleError] = 'Y'

      SELECT @MAXID = ISNULL(MAX(TIE.[RECORDID]), 0)
        FROM [dbo].[TimeEntry] TIE

      INSERT
        INTO @NTEID
            ([NEWID],
             [RECORDID])
      SELECT @MAXID,
             TDB.[RECORDID]
        from [dbo].[TimeDayBook] [TDB]
             LEFT OUTER JOIN [dbo].[matters] MAT
                             INNER JOIN [dbo].[Contacts] CON
                                     ON CON.[Code] = MAT.[ClientCode]
                             LEFT OUTER JOIN [dbo].[WorkTypes] WTY
                                          ON WTY.[CODE] = MAT.[WType]
                          ON MAT.[Code] = TDB.[MATTER]
             LEFT OUTER JOIN [dbo].[TasksCodes] TAC
                          ON TAC.[CODE] = TDB.[TASK]
       WHERE TDB.[FEEEARN] = @Handler
         AND [dbo].[KEYHM_FN_UserCanPostTime](TDB.[Matter], @Handler, TDB.[RECORDID]) = 0
         AND (   [TDB].[TimeOrCharge] <> 'T'        --KEYD-5185
              OR [TDB].[Time] <> 0)                 --KEYD-5185
         AND CASE WHEN RTRIM(ISNULL(TDB.[matter], '')) = ''
                       -- Admin entries can't cause an Axle error
                       THEN 'N'
                  WHEN RTRIM(ISNULL(TDB.[matter], '')) = '~'
                       -- Admin entries can't cause an Axle error
                       THEN 'N'
                  WHEN MAT.[Code] IS NULL
                       -- Missing matter. This is an error
                       THEN 'Y'
                  WHEN RTRIM(IsNull(CON.[ClientGroup], '')) <> ''
                       -- If it's not an HSE Client it can't cause an Axle Error
               THEN  'N'
                  WHEN RTRIM(IsNull(CON.[ClientGroup], '')) <> ISNULL(@HSEClientGroup, '')
                       -- If it's not an HSE Client it can't cause an Axle Error
                       THEN  'N'
                  WHEN RTRIM(ISNULL(WTY.[CODE], '')) = ''
                       -- Missing Worktype. This is an error
                       THEN 'Y'
                  WHEN RTRIM(ISNULL(WTY.[ChildCare], '')) <> 'Y'
                       -- If it's not a ChildCare matter it can't cause an Axle Error
                       THEN  'N'
                  WHEN RTRIM(ISNULL(TAC.[CODE], '')) = ''
                       -- Missing Task. This is an error
                       THEN 'Y'
                  WHEN RTRIM(ISNULL(TAC.[AxleTask], '')) <> 'Y'
                       -- This is not a Child Care task. This is an error
                       THEN 'Y'
                  WHEN LEN(RTRIM(ISNULL(TDB.[COMMENT], ''))) < 10
                       -- Comment must be at least 10 characters. This is an error.
                       THEN 'Y'
                  WHEN TDB.[TIME] > 1440
                       -- Task is too long! Must be less than 1440 minutes (i.e. 24 hours)
                       THEN 'Y'
                  ELSE 'N'
              END = 'N'
         AND (   @UpdateRestriction = 0
              OR (    @UpdateRestriction = 1
                  AND [TDB].[AdHocPosting] = 1)
              OR (    @UpdateRestriction = 2
                  AND [TDB].[Date] < CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112))))

      -- Please Note that AdHocPosting should only be evaluated ONCE - Start
      UPDATE [TDB]
         SET [TDB].[AdHocPosting] = 0
        FROM [dbo].[TimeDayBook] [TDB]
       WHERE [TDB].[FeeEarn] = @Handler
         AND [TDB].[AdHocPosting] <> 0
      -- Please Note that AdHocPosting should only be evaluated ONCE - End

      INSERT
        INTO @PDMAT
            ([CODE])
      SELECT DISTINCT
             TDB.[MATTER]
        FROM [dbo].[TimeDayBook] TDB
             LEFT OUTER JOIN [dbo].[matters] MAT        --2015-09-01
                          ON MAT.CODE = TDB.Matter
       WHERE TDB.[FEEEARN] = @Handler
         AND ISNULL(MAT.Closed,'N')<>'Y'

      UPDATE NTEID
         SET NTEID.[NEWID] = NTEID.[ID] + NTEID.[NEWID]
        FROM @NTEID NTEID

      --IF (@TUTNUMVALUE <> 1)    ----PINO 2015-08-25 - second fix
      --  BEGIN                   ----PINO 2015-08-25 - second fix
          -- Round all Time Daybook Values up to the nearest Unit.
          DECLARE @RECID INT

          INSERT
            INTO @RDUP
                ([RECORDID])
          SELECT TDB.[RecordID]
            FROM @NTEID NTEID
                 INNER JOIN [dbo].[TimeDayBook] TDB
                         ON TDB.[RECORDID] = NTEID.[RECORDID]
                        AND TDB.[TimeOrCharge] <> 'C'

          SELECT TOP 1 @RECID = RDUP.[RECORDID]
            FROM @RDUP RDUP

          WHILE (@RECID IS NOT NULL)
            BEGIN
              DELETE RDUP
                FROM @RDUP RDUP
               WHERE RDUP.[RECORDID] = @RECID

              EXEC [dbo].[KEYHM_SetTimeDaybookRateCharge] @RECID, @TUTNUMVALUE

              SET @RECID = NULL

              SELECT TOP 1 @RECID = RDUP.[RECORDID]
                FROM @RDUP RDUP
            END
        --END                     ----PINO 2015-08-25 - second fix

      SET IDENTITY_INSERT [dbo].[TimeEntry] ON

      INSERT
        INTO [dbo].[TimeEntry]
            ([MATTER],
             [FEEEARN],
             [DATE],
             [TIME],
             [RATE],
             [TASK],
             [TIMEORCHARGE],
             [COMMENT],
             [NCCODE],
             [DOCKET],
             [TEAM],
             [TRACKREF],
             [REC_IRR],
             [PERIOD],
             [YEAR],
             [BillingPeriod],
             [BillingYear],
             [ACTIONID],
      [StageCode],
             [Branch],
             [RECORDID])
      SELECT CASE WHEN RTRIM(ISNULL(TDB.[TASK], '')) <> ''
                       THEN TDB.[MATTER]
                  WHEN RTRIM(ISNULL(TDB.[MATTER], '')) <> ''
                       THEN TDB.[MATTER]
                  ELSE '~' END,
             TDB.[FEEEARN],
             TDB.[DATE],
             TDB.[TIME],
             TDB.[RATE],
             TDB.[TASK],
             TDB.[TIMEORCHARGE],
             TDB.[COMMENT],
             CASE WHEN RTRIM(ISNULL(TDB.[TASK], '')) <> ''
                       THEN ''
                  WHEN RTRIM(ISNULL(TDB.[MATTER], '')) = '~'
                       THEN TDB.[NCCCode]
                  WHEN RTRIM(ISNULL(TDB.[MATTER], '')) <> ''
                       THEN ''
                  ELSE TDB.[NCCCODE] END,
             CASE WHEN ISNUMERIC(RTRIM(ISNULL(TDB.[DOCKET],''))) = 1
                       THEN CONVERT(decimal(9,0), RTRIM(ISNULL(TDB.[DOCKET],'')))
                  ELSE 0 END,
             TDB.[TEAM],
             TDB.[TRACKREF],
             TDB.[REC_IRR],
             CASE WHEN ISNULL(TDB.[PERIOD], 0) = 0 THEN @PERIOD ELSE TDB.[PERIOD] END,
             CASE WHEN ISNULL(TDB.[YEAR], 0) = 0 THEN @YEAR ELSE TDB.[YEAR] END,
             0, --2015-08-27
             0, --2015-08-27
             TDB.[ACTIONID],
             TDB.[StageCode],
             CASE WHEN TDB.[Matter] = '~' THEN '' ELSE ISNULL(HAN.[BRANCH], '') END, -- 2015-09-01 John
             NTEID.[NEWID]
        FROM @NTEID NTEID
             INNER JOIN [dbo].[TimeDayBook] TDB
                     ON TDB.[RECORDID] = NTEID.[RECORDID]
             LEFT OUTER JOIN [dbo].[Handlers] HAN -- 2015-09-01 John
                          ON HAN.[CODE] = TDB.[FeeEarn]
             LEFT OUTER JOIN  [dbo].[Matters] MAT on MAT.Code = TDB.Matter



      SET IDENTITY_INSERT [dbo].[TimeEntry] OFF

      SELECT @MAXID = ISNULL(MAX(TIE.[RECORDID]), 0)
        FROM [dbo].[TimeEntry] TIE

      DBCC CHECKIDENT([TimeEntry], RESEED, @MAXID)

      DELETE [dbo].[WDNTEID]
       WHERE [handler] = @Handler

      INSERT
        INTO [dbo].[WDNTEID]
            ([Handler],
             [id],
             [NewId],
             [RECORDID])
      SELECT @Handler,
             [ID],
             [NEWID],
             [RECORDID]
        FROM @NTEID

      EXEC [dbo].[KEYHM_UpdateTimeEntryFromDayBook] @HANDLER, @UPDByHandler, @User

      EXEC [dbo].[KEYHM_CheckUnpostableEntries] @HANDLER

      DELETE TDB
        FROM @NTEID NTEID
             INNER JOIN [dbo].[TimeDayBook] TDB
                     ON TDB.[RECORDID] = NTEID.[RECORDID]
             INNER JOIN [dbo].[TimeEntry] TIE
                     ON TIE.[RECORDID] = NTEID.[NEWID]
             LEFT OUTER JOIN [dbo].[matters] MAT
                          ON MAT.[Code] = TIE.[MATTER]
       WHERE TIE.[MATTER] = '~'
          OR MAT.[Code] IS NOT NULL

      UPDATE MAT
         SET MAT.[ChargeBal] = ISNULL(TIE.[Charge], 0),
             MAT.[TimeBal] = ISNULL(TIE.[Time], 0)
        FROM @PDMAT PDM
             INNER JOIN [dbo].[Matters] MAT
                     ON MAT.[Code] = PDM.[CODE]
             LEFT OUTER JOIN (SELECT TIE.[Matter],
                                     SUM(ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0)) AS [Charge],
                                     SUM(ISNULL(TIE.[Time], 0)) AS [Time]
                                FROM [dbo].[TimeEntry] AS TIE
                               WHERE TIE.[TimeOrCharge] <> 'B'
                                 AND TIE.[Rec_Irr] = 'C'
                                 AND TIE.[IncludeInBill] <> 2
                                 AND CASE WHEN @IsSAM4 = 1 -- SAM4 doesn't use billedamount
                                           AND ISNULL(TIE.[InvoiceNo], 0) = 0
                                               THEN 1
                                          WHEN @IsSAM4 <> 1 -- SAM3 does
                                           AND ABS(ISNULL(TIE.[BilledAmount], 0)) < ABS(ISNULL(TIE.[Charge], 0))
                                               THEN 1
                                          ELSE 0 END = 1
                                     GROUP BY TIE.[Matter]) AS TIE
                          ON TIE.[Matter] = MAT.[Code]
       WHERE MAT.[Code] IS NOT NULL

  IF (@AxleErrors = 0)
    BEGIN
      SELECT COUNT(1) AS [TOTAL]
        from [dbo].[TimeDayBook] TDB
       WHERE TDB.[FEEEARN] = @Handler
    END
  ELSE
    BEGIN
      SELECT DISTINCT AXER.[AxleError]
        FROM [dbo].[ky_WDTimeDayBookWithAxleErrors]
            (@HSEClientGroup,
             @Handler) AXER
       WHERE AXER.[IsAxleError] = 'Y'
    END
  
  DECLARE @IsTimerRunning BIT
  SET @IsTimerRunning = 0;
  IF EXISTS(SELECT TOP 1 1 FROM TimeDayBook WHERE FeeEarn = @Handler AND StopwatchStatus = 0)
	BEGIN
		SET @IsTimerRunning = 1;
	END
  SELECT @IsTimerRunning AS [IsTimerRunning]
END
GO

