sp_configure 'show advanced options', 1
GO
RECONFIGURE;
GO

sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

sp_configure 'xp_cmdshell', 1;
GO
RECONFIGURE;
GO

/**************************************************************************************
 *
 * Fix SAM4 Collation issues
 *
 **************************************************************************************/
DECLARE @SAM4 int
DECLARE @Collation varchar(50)
DECLARE @DBCollation varchar(50)
DECLARE @COMMAND varchar(8000)

SELECT @SAM4 = SC.[length],
       @Collation = SC.[collation]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'
   
SET @DBCollation = convert(varchar(50), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))

IF ((@SAM4 = 17) AND (@Collation <> @DBCollation))
  BEGIN
    SET @COMMAND = 'DROP INDEX [IX_TimeEntry] ON [dbo].[TimeEntry]'
    
    EXEC (@COMMAND)

    SET @COMMAND = 'ALTER TABLE
      [dbo].[TimeEntry]
ALTER COLUMN 
      [MATTER] varchar(17) 
               COLLATE database_default'
    EXEC (@COMMAND)
    
    SET @COMMAND = 'CREATE NONCLUSTERED INDEX
       [IX_TimeEntry]
    ON [dbo].[TimeEntry]
      ([Matter] ASC,
       [DATE] ASC,
       [RecordId] ASC)
    ON [PRIMARY]'

    EXEC (@COMMAND)
        
  END
GO

DECLARE @SAM4 int
DECLARE @Collation varchar(50)
DECLARE @DBCollation varchar(50)
DECLARE @COMMAND varchar(8000)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeDayBook'
   AND SO.[xtype] = 'U'

SELECT @Collation = SC.[collation]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'TASK'
 WHERE SO.[name] = 'TimeDayBook'
   AND SO.[xtype] = 'U'
      
SET @DBCollation = convert(varchar(50), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))

IF ((@SAM4 = 17) AND (@Collation <> @DBCollation))
  BEGIN
    SET @COMMAND = 'ALTER TABLE
      [dbo].[TimeDayBook]
ALTER COLUMN 
      [TASK] varchar(6) 
               COLLATE database_default'
    EXEC (@COMMAND)
    
  END
GO

DECLARE @SAM4 int
DECLARE @Collation varchar(50)
DECLARE @DBCollation varchar(50)
DECLARE @COMMAND varchar(8000)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeDayBook'
   AND SO.[xtype] = 'U'

SELECT @Collation = SC.[collation]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'NCCCODE'
 WHERE SO.[name] = 'TimeDayBook'
   AND SO.[xtype] = 'U'
      
SET @DBCollation = convert(varchar(50), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))

IF ((@SAM4 = 17) AND (@Collation <> @DBCollation))
  BEGIN
    SET @COMMAND = 'ALTER TABLE
      [dbo].[TimeDayBook]
ALTER COLUMN 
      [NCCCODE] char(5) 
               COLLATE database_default'
    EXEC (@COMMAND)
    
  END
GO

DECLARE @SAM4 int
DECLARE @Collation varchar(50)
DECLARE @DBCollation varchar(50)
DECLARE @COMMAND varchar(8000)

SELECT @SAM4 = SC.[length],
       @Collation = SC.[collation]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'FeeEarn'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'
   
SET @DBCollation = convert(varchar(50), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))

IF ((@SAM4 = 5) AND (@Collation <> @DBCollation))
  BEGIN
    SET @COMMAND = 'ALTER TABLE
      [dbo].[TimeEntry]
ALTER COLUMN 
      [FeeEarn] varchar(5) 
               COLLATE database_default'
    EXEC (@COMMAND)
    
  END
GO

DECLARE @SAM4 int
DECLARE @Collation varchar(50)
DECLARE @DBCollation varchar(50)
DECLARE @COMMAND varchar(8000)
DECLARE @PRIMARYKEY varchar(50)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

SELECT @Collation = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'CODE'
 WHERE SO.[name] = 'TasksCodes'
   AND SO.[xtype] = 'U'

select @PRIMARYKEY = si.[name]
  from sysobjects so
       inner join sysindexes si 
               on si.[id] = so.[id]
              and si.[name] like 'PK%'
 where so.[name] like 'TasksCodes'
     
SET @DBCollation = convert(varchar(50), DATABASEPROPERTYEX(DB_NAME(), 'Collation'))

IF ((@SAM4 = 17) AND (@Collation <> @DBCollation))
  BEGIN
    SET @COMMAND = 'ALTER TABLE 
      [dbo].[TasksCodes] 
      DROP CONSTRAINT ' + @PRIMARYKEY
    
    EXEC (@COMMAND)

    SET @COMMAND = 'ALTER TABLE
      [dbo].[TasksCodes]
ALTER COLUMN 
      [CODE] varchar(6) 
               COLLATE database_default
               not null'
    EXEC (@COMMAND)
    
    SET @COMMAND = 'ALTER TABLE 
      [dbo].[TasksCodes] 
      ADD CONSTRAINT PK_TasksCodes PRIMARY KEY CLUSTERED 
     ([CODE] ASC)
   ON [PRIMARY]'

    EXEC (@COMMAND)
        
  END
GO

/**************************************************************************************
 *
 * TABLE TYPES
 *
 **************************************************************************************/
/*
IF NOT EXISTS(SELECT *
                FROM sys.table_types
               WHERE [name] = 'NTEID')
BEGIN
  CREATE
    TYPE NTEID 
      AS TABLE
        ([ID]       int   identity(1, 1),
         [NEWID]    int,
         [RECORDID] int)
  
END

DROP TYPE NTEID
*/

/**************************************************************************************
 *
 * New Tables and indexes.
 *
 **************************************************************************************/

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'HandlerImages')
BEGIN
  CREATE TABLE
         [dbo].[HandlerImages]
        ([Handler]             varchar(10)        NOT NULL,
         [ImageType]           int                NOT NULL,
         [Image]               image              NOT NULL,
         CONSTRAINT           [PK_HandlerImagesNew] 
                              PRIMARY KEY CLUSTERED
                             ([Handler] ASC,
                              [ImageType] ASC))
      ON [PRIMARY] 
END
GO

IF EXISTS(select so2.[name]
            from sysconstraints sc
                 inner join sysobjects so
                         on so.[id] = sc.[id]
                        and so.[name] = 'HandlerImages'
                 inner join sysobjects so2
                         on so2.[id] = sc.[constid]
                        and so2.[name] = 'PK_HandlerImages')
BEGIN
  ALTER 
  TABLE [dbo].[HandlerImages]
   DROP CONSTRAINT [PK_HandlerImages]
  
  ALTER
  TABLE [dbo].[HandlerImages] 
    ADD CONSTRAINT [PK_HandlerImagesNew]
        PRIMARY KEY CLUSTERED 
       ([Handler] ASC,
        [ImageType] ASC)
     ON [PRIMARY]
END

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'DefaultNoteTA')
BEGIN
  CREATE TABLE
         [dbo].[DefaultNoteTA]
        ([Action]             varchar(20)        NOT NULL,
         CONSTRAINT           [PK_DefaultNoteTA] 
                              PRIMARY KEY CLUSTERED
                             ([Action] ASC))
      ON [PRIMARY] 
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'DefaultPhoneTA')
BEGIN
  CREATE TABLE
         [dbo].[DefaultPhoneTA]
        ([Action]             varchar(20)        NOT NULL,
         CONSTRAINT           [PK_DefaultPhoneTA] 
                              PRIMARY KEY CLUSTERED
                             ([Action] ASC))
      ON [PRIMARY] 
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'DefaultEmailTA')
BEGIN
  CREATE TABLE
         [dbo].[DefaultEmailTA]
        ([Action]             varchar(20)        NOT NULL,
         CONSTRAINT           [PK_DefaultEmailTA] 
                              PRIMARY KEY CLUSTERED
                             ([Action] ASC))
      ON [PRIMARY] 
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'AlarmTypes')
BEGIN
  CREATE TABLE
         [dbo].[AlarmTypes]
        ([TypeID]             int                NOT NULL,
         [Description]        NVARCHAR(500)      NOT NULL,
         CONSTRAINT           [PK_AlarmTypes] 
                              PRIMARY KEY CLUSTERED
                             ([TypeID] ASC))
      ON [PRIMARY] 
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'Alarms')
BEGIN
CREATE TABLE
       [dbo].[Alarms]
      ([ID]                 VARCHAR(38)        NOT NULL,
       [HandlerCode]        VARCHAR(5)         NOT NULL,
       [MatterRef]          VARCHAR(17)            NULL,
       [LinkID]             VARCHAR(50)            NULL,
       [OriginalDate]       DATETIME           NOT NULL,
       [DeferredDate]       DATETIME           NOT NULL,
       [Title]              NVARCHAR(255)      NOT NULL,
       [Message]            NTEXT              NOT NULL,
       [Type]               int                NOT NULL,
       [Status]             int                NOT NULL,
       CONSTRAINT           [PK_Alarms] 
                            PRIMARY KEY CLUSTERED
                           ([ID] ASC))
    ON [PRIMARY] 
    TEXTIMAGE_ON [PRIMARY]
END
GO

IF NOT EXISTS(SELECT *
                FROM SYSUSERS SU
                     INNER JOIN SYSOBJECTS SO
                             ON SO.[uid] = SU.[uid] 
                            AND SO.[name] = 'FK_Alarms_AlarmTypes'
                            AND SO.[xtype] = 'F'
                WHERE SU.[name] = 'dbo')
BEGIN
ALTER TABLE 
      [dbo].[Alarms] 
 WITH CHECK 
  ADD CONSTRAINT [FK_Alarms_AlarmTypes] 
                 FOREIGN KEY([Type])
                 REFERENCES [dbo].[AlarmTypes]
                           ([TypeID])

  ALTER TABLE [dbo].[Alarms] 
        CHECK CONSTRAINT [FK_Alarms_AlarmTypes]

END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'AlarmStatus')
BEGIN
CREATE TABLE
       [dbo].[AlarmStatus]
      ([StatusID]           int                NOT NULL,
       [Description]        NVARCHAR(500)      NOT NULL,
       CONSTRAINT           [PK_AlarmStatus] 
                            PRIMARY KEY CLUSTERED
                           ([StatusID] ASC))
    ON [PRIMARY] 

END
GO

IF NOT EXISTS(SELECT *
                FROM SYSUSERS SU
                     INNER JOIN SYSOBJECTS SO
                             ON SO.[uid] = SU.[uid] 
                            AND SO.[name] = 'FK_Alarms_AlarmStatus'
                            AND SO.[xtype] = 'F'
                WHERE SU.[name] = 'dbo')
BEGIN
ALTER TABLE 
      [dbo].[Alarms] 
 WITH CHECK 
      ADD CONSTRAINT [FK_Alarms_AlarmStatus] 
                     FOREIGN KEY([Status])
                     REFERENCES [dbo].[AlarmStatus]
                               ([StatusID])

ALTER TABLE [dbo].[Alarms] 
            CHECK CONSTRAINT [FK_Alarms_AlarmStatus]

END
GO

IF NOT EXISTS(SELECT *
                FROM sysindexes SI
               WHERE SI.[name] = 'AlarmsByTypeAndLinkID')
BEGIN
CREATE NONCLUSTERED INDEX 
       [AlarmsByTypeAndLinkID]
    ON [dbo].[Alarms] 
      ([Type] ASC,
       [LinkID] ASC,
       [ID] ASC)
    ON [PRIMARY]
END
GO

IF NOT EXISTS(SELECT *
                FROM sysindexes SI
               WHERE SI.[name] = 'AlarmsByMatter')
BEGIN
CREATE NONCLUSTERED INDEX 
       [AlarmsByMatter]
    ON [dbo].[Alarms] 
      ([MatterRef] ASC,
       [ID] ASC)
    ON [PRIMARY]
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'PerformanceAlarmStatements')
BEGIN
CREATE TABLE
       [dbo].[PerformanceAlarmStatements]
      ([ID]          int,
       [PAName]      VARCHAR(200),
       [PACode]      VARCHAR(36),
       [PATotal]     TEXT,
       [PADetail]    TEXT,
       [PAHandler]   VARCHAR(5),
       [PATeam]      VARCHAR(5),
       [PAVersion]   VARCHAR(20)
       CONSTRAINT    [PK_PerformanceAlarmStatements] 
                     PRIMARY KEY CLUSTERED
                    ([ID] ASC))
    ON [PRIMARY] 
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'PerformanceAlarmConfig')
BEGIN
CREATE TABLE
       [dbo].[PerformanceAlarmConfig]
      ([ID]              int,
       [PACHandler]      VARCHAR(5),
       [PACStatementID]  int,
       [PACFrequency]    int,
       CONSTRAINT    [PK_PerformanceAlarmConfig] 
                     PRIMARY KEY CLUSTERED
                    ([ID] ASC))
    ON [PRIMARY] 
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'PerformanceAlarms')
BEGIN
CREATE TABLE
       [dbo].[PerformanceAlarms]
      ([ID]              int,
       [PAHandler]       VARCHAR(5),
       [PAStatementID]   int,
       [PAConfigID]      int,
       [PALastRun]       DATETIME,
       CONSTRAINT        [PK_PerformanceAlarms] 
                         PRIMARY KEY CLUSTERED
                        ([ID] ASC))
    ON [PRIMARY] 
END
GO

IF NOT EXISTS(SELECT *
                FROM sysindexes SI
               WHERE SI.[name] = 'PerformanceAlarmsNames')
BEGIN
CREATE NONCLUSTERED INDEX 
       [PerformanceAlarmsNames]
    ON [dbo].[PerformanceAlarmStatements] 
      ([PAName] ASC,
       [ID] ASC)
    ON [PRIMARY]
END
GO

IF NOT EXISTS(SELECT *
                FROM SYSUSERS SU
                     INNER JOIN SYSOBJECTS SO
                             ON SO.[uid] = SU.[uid] 
                            AND SO.[name] = 'FK_PAC_PAS'
                            AND SO.[xtype] = 'F'
                WHERE SU.[name] = 'dbo')
BEGIN
ALTER TABLE 
      [dbo].[PerformanceAlarmConfig] 
 WITH CHECK 
  ADD CONSTRAINT [FK_PAC_PAS] 
                 FOREIGN KEY([PACStatementID])
      REFERENCES [dbo].[PerformanceAlarmStatements]
                ([ID])

ALTER TABLE [dbo].[PerformanceAlarmConfig] 
      CHECK CONSTRAINT [FK_PAC_PAS]
END
GO

IF NOT EXISTS(SELECT *
                FROM SYSUSERS SU
                     INNER JOIN SYSOBJECTS SO
                             ON SO.[uid] = SU.[uid] 
                            AND SO.[name] = 'FK_PAC_PA'
                            AND SO.[xtype] = 'F'
                WHERE SU.[name] = 'dbo')
BEGIN
ALTER TABLE 
      [dbo].[PerformanceAlarms] 
      WITH CHECK 
       ADD CONSTRAINT [FK_PAC_PA] 
           FOREIGN KEY([PAConfigID])
           REFERENCES [dbo].[PerformanceAlarmConfig]
                     ([ID])


ALTER TABLE [dbo].[PerformanceAlarms] 
      CHECK CONSTRAINT [FK_PAC_PA]
END
GO

IF NOT EXISTS(SELECT *
                FROM SYSUSERS SU
                     INNER JOIN SYSOBJECTS SO
                             ON SO.[uid] = SU.[uid] 
                            AND SO.[name] = 'FK_PAS_PA'
                            AND SO.[xtype] = 'F'
                WHERE SU.[name] = 'dbo')
BEGIN
ALTER TABLE 
      [dbo].[PerformanceAlarms] 
 WITH CHECK 
      ADD CONSTRAINT [FK_PAS_PA] 
             FOREIGN KEY([PAStatementID])
                     REFERENCES [dbo].[PerformanceAlarmStatements]
                               ([ID])

ALTER TABLE [dbo].[PerformanceAlarms] 
            CHECK CONSTRAINT [FK_PAS_PA]
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'WDHandlerMailOptions')
BEGIN
  CREATE TABLE
         [dbo].[WDHandlerMailOptions]
        ([HANDLER]          varchar(10)          NOT NULL,
         [retain]           int,
         [savecompleted]    int,
         [deleteafter]      int,
         [recategoriseatt]  int,
         [donotaskagain]    int)
  
END
GO

IF NOT EXISTS(SELECT *
                FROM sysindexes SI
                     inner join sysobjects SO
                             ON SO.[id] = SI.[id]
                            AND SO.[name] = 'WDHandlerMailOptions'
               WHERE SI.[name] = '[REDACTED])
BEGIN
CREATE UNIQUE CLUSTERED INDEX
       [[REDACTED]
    ON [dbo].[WDHandlerMailOptions]
      ([HANDLER]       ASC)
    ON [PRIMARY]
END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'WDNTEID')
BEGIN
  CREATE TABLE
         [dbo].[WDNTEID]
        ([HANDLER]        varchar(10)          NOT NULL,
         [id]             int                  NOT NULL,
         [NEWID]          int,
         [RECORDID]       int)
  
END
GO

IF NOT EXISTS(SELECT *
                FROM sysindexes SI
                     inner join sysobjects SO
                             ON SO.[id] = SI.[id]
                            AND SO.[name] = 'WDNTEID'
               WHERE SI.[name] = 'pk_WDNTEID')
BEGIN
CREATE UNIQUE CLUSTERED INDEX
       [pk_WDNTEID]
    ON [dbo].[WDNTEID]
      ([HANDLER]       ASC,
       [id]            ASC)
    ON [PRIMARY]
END
GO

-- UNC Locations
IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'UNCAlias'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE [dbo].[UNCAlias]
                ([Drive]              [varchar](1)                      NOT NULL,
                 [UNC]                [varchar](200)                    NOT NULL)
              ON [PRIMARY]
  END
GO

-- Handlersettings
IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'HandlerSettings'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE [dbo].[HandlerSettings]
                ([Handler]            [varchar](10)                     NOT NULL,
                 [IMAP]               [varchar](2000)                   NOT NULL
                 CONSTRAINT [PK_HandlerSettings] 
                            PRIMARY KEY  CLUSTERED
                           ([HANDLER] ASC))
              ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
                     inner join syscolumns SC
                             on SC.[id] = SO.[id]
                            and SC.[name] = 'SMTP'
               where SO.[name] = 'HandlerSettings'
                 and SO.[xtype] = 'U')
BEGIN
   ALTER TABLE [dbo].[HandlerSettings]
           ADD [SMTP]     varchar(2000)
END
GO

-- ClientChargeoutRates
IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'ClientChargeOutRates'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE [dbo].[ClientChargeOutRates]
                ([RecordID]           [int]             IDENTITY (1, 1) NOT NULL,
                 [ClientCode]         [varchar](10)                     NOT NULL,
                 [FeCode]             [varchar](10)                     NOT NULL,
                 [Rate]               [decimal](18, 2)                      NULL,
                 [ModifyDate]         [datetime]                            NULL,
                 [ModifyBy]           [varchar](10)                         NULL,
                 [LastRate]           [decimal](18, 2)                      NULL
                 CONSTRAINT [PK_ClientChargeOutRates] 
                            PRIMARY KEY  CLUSTERED
                           ([RecordID] ASC))
              ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
                     inner join sysindexes SI
                              on SI.[id] = SO.[id]
                             and SI.[name] = 'FEClientKey'
               where SO.[name] = 'ClientChargeOutRates')
  BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX
           [FEClientKey]
        ON [dbo].[ClientChargeOutRates]
          ([FeCode]      ASC,
           [ClientCode]    ASC)
        ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
                     inner join sysindexes SI
                              on SI.[id] = SO.[id]
                             and SI.[name] = 'ClientFEKey'
               where SO.[name] = 'ClientChargeOutRates')
  BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX
           [ClientFEKey]
        ON [dbo].[ClientChargeOutRates]
          ([ClientCode]    ASC,
           [FeCode]      ASC)
        ON [PRIMARY]
  END
GO

-- MatterChargeoutRates
IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'MatterChargeOutRates'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE [dbo].[MatterChargeOutRates]
                ([RecordID]           [int]             IDENTITY (1, 1) NOT NULL,
                 [ClientCode]         [varchar](10)                     NOT NULL,
                 [MatterCode]         [varchar](20)                     NOT NULL,
                 [FeCode]             [varchar](10)                     NOT NULL,
                 [Rate]               [decimal](18, 2)                      NULL,
                 [ModifyDate]         [datetime]                            NULL,
                 [ModifyBy]           [varchar](10)                         NULL,
                 [LastRate]           [decimal](18, 2)                      NULL
                 CONSTRAINT [PK_MatterChargeOutRates] 
                            PRIMARY KEY  CLUSTERED
                           ([RecordID] ASC))
              ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
                     inner join sysindexes SI
                              on SI.[id] = SO.[id]
                             and SI.[name] = 'KeyFeMatterChargeOutRates'
               where SO.[name] = 'MatterChargeOutRates')
  BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX
           [KeyFeMatterChargeOutRates]
        ON [dbo].[MatterChargeOutRates]
          ([FeCode]      ASC,
           [MatterCode]    ASC)
        ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
                     inner join sysindexes SI
                              on SI.[id] = SO.[id]
                             and SI.[name] = 'KeyMatterChargeOutRates'
               where SO.[name] = 'MatterChargeOutRates')
  BEGIN
    CREATE UNIQUE NONCLUSTERED INDEX
           [KeyMatterChargeOutRates]
        ON [dbo].[MatterChargeOutRates]
          ([MatterCode]    ASC,
           [FeCode]      ASC)
        ON [PRIMARY]
  END
GO

IF NOT Exists(SELECT *
                FROM sysindexes SI
                     INNER JOIN sysobjects SO
                             ON SO.[id] = SI.[id]
                            AND so.[name] = 'diary'
               WHERE SI.[name] = 'KeyEmailDates')
BEGIN
  CREATE NONCLUSTERED INDEX 
         [KeyEmailDates]
      ON [dbo].[diary] 
        ([EMAIL]          ASC,
         [TxmDate]        ASC,
         [DATE]           ASC)
      ON [PRIMARY]
END
GO

IF NOT Exists(SELECT *
                FROM sysindexes SI
                     INNER JOIN sysobjects SO
                             ON SO.[id] = SI.[id]
                            AND so.[name] = 'diary'
               WHERE SI.[name] = 'KeyEmailDates2')
BEGIN
  CREATE NONCLUSTERED INDEX 
         [KeyEmailDates2]
      ON [dbo].[diary] 
        ([EMAIL]          ASC,
         [DATE]           ASC,
         [TxmDate]        ASC)
      ON [PRIMARY]
END
GO

-- TimeEntryLog
IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'TimeEntryLog'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE 
           [dbo].[TimeEntryLog]
          ([Id]                [int] IDENTITY(1,1) NOT NULL,
           [TimeId]            [int] NULL,
           [FromMatter]        [varchar](17) NULL,
           [ToMatter]          [varchar](17) NULL,
           [TrDate]            [datetime] NULL,
           [TrBy]              [varchar](8) NULL,
           CONSTRAINT [PK_TimeEntryLog]
                      PRIMARY KEY CLUSTERED 
                     ([Id] ASC)
                   ON [PRIMARY])
        ON [PRIMARY]
  END
GO

IF NOT EXISTS(select SI.*
                from sysobjects SO
                     INNER JOIN sysindexes SI
                             ON SI.[id] = SO.[id]
                            AND SI.[name] = 'CACode'
               where SO.[name] = 'CaseAssociatesContacts')
  BEGIN
    /****** Object:  Index [CACode]    Script Date: 03/30/2012 10:38:12 ******/
    CREATE UNIQUE NONCLUSTERED INDEX 
           [CACode] 
        ON [dbo].[CaseAssociatesContacts] 
          ([KEYID]             ASC,
           [NAMECODE]          ASC)
        ON [PRIMARY]
  END
GO

IF NOT EXISTS(select SI.*
                from sysobjects SO
                     INNER JOIN sysindexes SI
                             ON SI.[id] = SO.[id]
                            AND SI.[name] = 'CAMail'
               where SO.[name] = 'CaseAssociatesContacts')
  BEGIN
    /****** Object:  Index [CACode]    Script Date: 03/30/2012 10:38:12 ******/
    CREATE NONCLUSTERED INDEX 
           [CAMail] 
        ON [dbo].[CaseAssociatesContacts] 
          ([EMAIL]             ASC,
           [KEYID]             ASC)
        ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'DiaMailCandidates'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE [dbo].[DiaMailCandidates]
                ([handler]     varchar(10)            NOT NULL,
                 [id]          int                    NOT NULL,
                 [date]        datetime                   NULL,
                 [from]        varchar(150)               NULL,
                 [fromname]    varchar(150)               NULL,
                 [subject]     varchar(200)               NULL,
                 [actionid]    int                    NOT NULL,
                 [casecode]    varchar(20)                NULL,
                 [diasubject]  varchar(200)               NULL,
                 [diaemail]    varchar(150)               NULL
                 CONSTRAINT [PK_DiaMailCandidates] 
                            PRIMARY KEY  CLUSTERED
                           ([handler]  ASC,
                            [id]       ASC,
                            [actionid] ASC))
              ON [PRIMARY]
  END
GO

-- HandlerBrowserPreferences
IF NOT EXISTS(select *
                from sysobjects 
               where [name] = 'HandlerBrowserPreferences'
                 and [xtype] = 'U')
  BEGIN
    CREATE TABLE [dbo].[HandlerBrowserPreferences]
                ([Handler]            [varchar](10)                     NOT NULL,
                 [Platform]           int                               NOT NULL,
                 [Browser]            [varchar](200)                    NOT NULL,
                 [ListPref]           int                               NOT NULL
                 CONSTRAINT [PK_HandlerBrowserPreferences] 
                            PRIMARY KEY  CLUSTERED
                           ([HANDLER]    ASC,
                            [Platform]   ASC,
                            [Browser]    ASC))
              ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
               WHERE so.[name] = 'HandlerOPE')
BEGIN
  CREATE TABLE
         [dbo].[HandlerOPE]
        ([Handler]            varchar(10)        NOT NULL,
         [OPE_NUMBER]         int                NOT NULL,
         CONSTRAINT           [PK_HandlerOPE] 
                              PRIMARY KEY CLUSTERED
                             ([Handler] ASC))
      ON [PRIMARY] 
END
GO

IF NOT EXISTS(SELECT *
                FROM sysindexes SI
                     inner join sysobjects SO
                             ON SO.[id] = SI.[id]
                            AND SO.[name] = 'HandlerOPE'
               WHERE SI.[name] = 'OPE_HandlerOPE')
BEGIN
CREATE UNIQUE NONCLUSTERED INDEX
       [OPE_HandlerOPE]
    ON [dbo].[HandlerOPE]
      ([OPE_NUMBER]       ASC)
    ON [PRIMARY]
END
GO

/*
The ADMIN Logon is essential for WebDev. Create it now if it doesn't already exist.
*/
IF NOT EXISTS(SELECT * 
                FROM [dbo].[Handlers]
               WHERE [CODE] = 'ADM')
BEGIN
  INSERT 
    INTO [dbo].[Handlers]
        ([CODE],
         [TEAM],
         [TEAMCODE],
         [TYPE],
         [NAME],
         [LOGON],
         [TIMECOSTER],
         [NORECENTMATTERS],
         [OutlookView])
  select 'ADM' AS [CODE],
         'ADM' AS [TEAM],
         'Y' AS [TEAMCODE],
         'S' AS [TYPE],
         'Admin' As [NAME],
         'ADMIN' AS [LOGON],
         'N' AS [TIMECOSTER],
         30 AS [NOCRECENTMATTERS],
         'Y' AS [OutlookView]
    from (Select 'ADM' AS [CODE]) NEW
         LEFT OUTER JOIN Handlers HAN
                 ON HAN.[CODE] = NEW.[CODE]
   WHERE HAN.[CODE] IS NULL
END

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)

--Pre-populate the HandlerOPE table (Only run this if the table is completely empty)
IF NOT EXISTS (SELECT 1 FROM [dbo].[HandlerOPE])
BEGIN

  /* 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 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 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 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 [dbo].[HandlerOPE]
        ([Handler],
         [OPE_Number])
  select HAN.[code],
         LO.[OPE_NUMBER] 
    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]
   WHERE LO.[OPE_NUMBER] IS NOT NULL
  ORDER BY LO.[OPE_NUMBER] 

END
GO

/**************************************************************************************
 *
 * Add Table Columns.
 *
 **************************************************************************************/

-- Add DefaultMatterTab column
IF NOT EXISTS(SELECT SC.*
                FROM SYSOBJECTS SO
                     INNER JOIN SYSCOLUMNS SC
                             ON SC.[id] = SO.[id]
                            AND SC.[name] = 'DefaultMatterTab'
               WHERE SO.[name] = 'HandlerBrowserPreferences')
BEGIN
  ALTER TABLE [dbo].[HandlerBrowserPreferences]
          ADD [DefaultMatterTab] int
END
GO

-- Add Chargeout Rate Indicator (Contacts)
DECLARE @Found int
DECLARE @command varchar(8000)

SELECT @Found = COUNT(1)
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
 WHERE SO.[name] = 'Contacts'
   AND SC.[name] = 'ChargeOutRateInd'

IF @Found = 0
   BEGIN
               SET @command = 'ALTER TABLE [dbo].[Contacts]'
      + char(13) + char(10) + '  ADD [ChargeOutRateInd] char(1) NULL'

      EXEC (@command)

   END
GO


-- Add Chargeout Rate Indicator (Matters)
DECLARE @Found int
DECLARE @command varchar(8000)

SELECT @Found = COUNT(1)
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
 WHERE SO.[name] = 'Matters'
   AND SC.[name] = 'ChargeOutRateInd'

IF @Found = 0
   BEGIN
               SET @command = 'ALTER TABLE [dbo].[Matters]'
      + char(13) + char(10) + '  ADD [ChargeOutRateInd] char(1) NULL'

      EXEC (@command)

   END
GO

--Stopwatch Start Time
DECLARE @Found int
DECLARE @command varchar(8000)

SELECT @Found = COUNT(1)
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
 WHERE SO.[name] = 'TimeDayBook'
   AND SC.[name] = 'StopwatchStartTime'

IF @Found = 0
   BEGIN
               SET @command = 'ALTER TABLE [dbo].[TimeDayBook]'
      + char(13) + char(10) + '  ADD [StopwatchStartTime] datetime null'

      EXEC (@command)

   END
GO

--Stopwatch Status
DECLARE @Found int
DECLARE @command varchar(8000)

SELECT @Found = COUNT(1)
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
 WHERE SO.[name] = 'TimeDayBook'
   AND SC.[name] = 'StopwatchStatus'

IF @Found = 0
   BEGIN
               SET @command = 'ALTER TABLE [dbo].[TimeDayBook]'
      + char(13) + char(10) + '  ADD [StopwatchStatus] int null'

      EXEC (@command)

   END
GO

-- Add Write Off Date (TimeEntry)
DECLARE @Found int
DECLARE @command varchar(8000)

SELECT @Found = COUNT(1)
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
 WHERE SO.[name] = 'TimeEntry'
   AND SC.[name] = 'WriteOffDT'

IF @Found = 0
   BEGIN
               SET @command = 'ALTER TABLE [dbo].[TimeEntry]'
      + char(13) + char(10) + '  ADD [WriteOffDT] datetime NULL'

      EXEC (@command)

   END
GO

-- Add Write Off ID (TimeEntry)
DECLARE @Found int
DECLARE @command varchar(8000)

SELECT @Found = COUNT(1)
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
 WHERE SO.[name] = 'TimeEntry'
   AND SC.[name] = 'WriteOffID'

IF @Found = 0
   BEGIN
               SET @command = 'ALTER TABLE [dbo].[TimeEntry]'
      + char(13) + char(10) + '  ADD [WriteOffID] int NULL'

      EXEC (@command)

   END
GO

/**************************************************************************************
 *
 * (Re)create views.
 *
 **************************************************************************************/

IF EXISTS(SELECT *
            FROM sys.objects SO
           WHERE SO.[name] = 'WDOpenMatters'
             AND SO.[type] = 'V')
  BEGIN
    DROP VIEW [dbo].[WDOpenMatters]
  END
GO

DECLARE @command varchar(4000)
DECLARE @hasclosed int

SET @hasclosed = 0
IF exists(SELECT SC.[NAME]
            FROM sys.objects SO
                 inner join sys.columns SC
                         ON SC.[object_id] = so.[object_id]
                        and SC.[name] = 'CLOSED'
           WHERE SO.[name] = 'matters')
  BEGIN
    SET @hasclosed = 1
  END

SET @command = 'CREATE VIEW
       [dbo].[WDOpenMatters]
AS
select MAT.[Code]
  from [dbo].[matters] MAT' + CASE WHEN @hasclosed = 1 THEN '
 WHERE MAT.[Closed] <> ''Y''' ELSE '' END
 
EXEC (@command)
GO
/**************************************************************************************
 *
 * Create additional indexes.
 *
 **************************************************************************************/
IF NOT EXISTS(select *
                from sysobjects SO
                     inner join sysindexes SI
                              on SI.[id] = SO.[id]
                             and SI.[name] = 'IDX_Name'
               where SO.[name] = 'CaseContacts')
  BEGIN
    CREATE NONCLUSTERED INDEX
           [IDX_Name]
        ON [dbo].[CaseContacts]
          ([NAMECODE]    ASC,
           [CASECODE]    ASC,
           [CONTYPE]     ASC,
           [CONNUM]      ASC)
        ON [PRIMARY]
  END
GO

IF NOT EXISTS(select *
                from sysobjects SO
                     inner join sysindexes SI
                              on SI.[id] = SO.[id]
                             and SI.[name] = 'IDX_WriteOffs'
               where SO.[name] = 'TimeEntry')
  BEGIN
    CREATE NONCLUSTERED INDEX
           [IDX_WriteOffs]
        ON [dbo].[TimeEntry]
          ([WriteOffID]    ASC,
           [RecordID]      ASC)
        ON [PRIMARY]
  END
GO

/**************************************************************************************
 *
 * Add/alter constraints etc.
 *
 **************************************************************************************/
if not exists(select 1 
                from sys.objects so
                     inner join sys.objects sp
                             on sp.[object_id] = so.[parent_object_id]
                            and sp.[name] = 'HandlerBrowserPreferences'
               where so.[name] = 'df_ListPref')
BEGIN
  alter 
  table [dbo].[HandlerBrowserPreferences]
    add constraint [df_ListPref] 
           DEFAULT 1 
               for [ListPref]
END
GO

/**************************************************************************************
 *
 * DELETE Functions and Procedures that will be re-generated in this script.
 *
 **************************************************************************************/
IF EXISTS(SELECT *
            FROM sys.objects SO
           WHERE SO.[name] = 'WDMatterSearch'
             AND SO.[type] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[WDMatterSearch]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMatterSearch'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDMatterSearch]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDContactSearch'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDContactSearch]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMatSearch'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDMatSearch]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDAllCaseAssociates'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDAllCaseAssociates]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDAllClientContacts'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDAllClientContacts]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDAllContacts'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDAllContacts]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDAllMatterContacts'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDAllMatterContacts]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCopyTimeEntry'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCopyTimeEntry]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDReadTimeEntryLog'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDReadTimeEntryLog]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDStoreFileBlob'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDStoreFileBlob]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDGetTAList'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDGetTAList]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDGetEmailTAs'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDGetEmailTAs]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDGetPhoneTAs'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDGetPhoneTAs]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDGetNoteTAs'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDGetNoteTAs]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDeleteAction'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDDeleteAction]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSetTimeInvoiceNo'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDSetTimeInvoiceNo]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTimeWriteoff'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTimeWriteoff]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDRecentMatterList'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDRecentMatterList]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDUpdateMatterTimeBalance'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDUpdateMatterTimeBalance]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDUpdateAllMatterTimeBalances'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDUpdateAllMatterTimeBalances]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDListBills'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDListBills]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTimeEntryByRecordID'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTimeEntryByRecordID]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTimeEntry'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTimeEntry]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDayBook'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDDayBook]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDPopDayBook'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDPopDayBook]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDListMailAssociations2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDListMailAssociations2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDListMailAssociations'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDListMailAssociations]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCreateDiaryStep'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCreateDiaryStep]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCreateDiaryStep2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCreateDiaryStep2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDPushtask2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDPushtask2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDPushtask'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDPushtask]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDNextWhile'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDNextWhile]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDPostDayBook'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDPostDayBook]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCheckUnpostableEntries'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCheckUnpostableEntries]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDUpdateTimeEntry'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDUpdateTimeEntry]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDUpdateTimeEntry2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDUpdateTimeEntry2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDUpdateTimeEntryFromDayBook'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDUpdateTimeEntryFromDayBook]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDAlterTimeDayBook'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDAlterTimeDayBook]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTimeDayBook'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTimeDayBook]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTimeDayBookWithAxleErrors'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTimeDayBookWithAxleErrors]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDActionCheckDependentActions'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDActionCheckDependentActions]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDActionAuthorisedToComplete'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDActionAuthorisedToComplete]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDelegateAction_DiaryDel'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDDelegateAction_DiaryDel]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDActionComplete2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDActionComplete2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDActionComplete'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDActionComplete]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDNextActionMissingCasePartner'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDNextActionMissingCasePartner]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDAssignAction_DiaryDel'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDAssignAction_DiaryDel]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDReleaseAction_DiaryDel'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDReleaseAction_DiaryDel]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDUpdateAction_DiaryDel'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDUpdateAction_DiaryDel]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSetTimeDayBookRateCharge'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDSetTimeDayBookRateCharge]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMatLedger'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDMatLedger]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDHandlerTimeBudgetDashboard'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDHandlerTimeBudgetDashboard]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDHFBudgets'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDHFBudgets]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDHFCountDraftInvoices'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDHFCountDraftInvoices]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDHFUndertakings'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDHFUndertakings]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMTUndertakings'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDMTUndertakings]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchCaseAssociates3'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchCaseAssociates3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchContacts3'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchContacts3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchClientContacts3'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchClientContacts3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchMatterContacts3'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchMatterContacts3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchAllContacts3'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDSearchAllContacts3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchAllContacts'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDSearchAllContacts]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchAllContacts2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDSearchAllContacts2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchMatterContacts2'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchMatterContacts2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchMatterContacts'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchMatterContacts]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchClientContacts2'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchClientContacts2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchClientContacts'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchClientContacts]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchContacts2'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchContacts2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchContacts'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchContacts]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchCaseAssociates2'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchCaseAssociates2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDSearchCaseAssociates'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDSearchCaseAssociates]
  END
GO

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMatterListCount'
             AND [XTYPE] = 'P')
    Drop procedure [dbo].[ky_WDMatterListCount]
Go

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMatterList'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDMatterList]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDMatterList2'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDMatterList2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocuments'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCaseDocuments]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocuments2'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCaseDocuments2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocuments3'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCaseDocuments3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocuments4'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDCaseDocuments4]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocList'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDCaseDocList]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocList2'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDCaseDocList2]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocList3'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDCaseDocList3]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDocList4'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDCaseDocList4]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDiaryDocuments'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDDiaryDocuments]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDiaryDocList'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDDiaryDocList]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListPage'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListPage]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListByActionTypePage'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListByActionTypePage]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListByHighlightPage'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListByHighlightPage]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListSet'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTaskListSet]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListByActionTypeSet'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTaskListByActionTypeSet]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListByHighlightSet'
             AND [XTYPE] = 'TF')
  BEGIN
    DROP FUNCTION [dbo].[ky_WDTaskListByHighlightSet]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListCount'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListCount]
  END
GO

/*No longer required. Superseded by ky_WDTaskListCountByActionType*/
IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListCriticalCount'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListCriticalCount]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListCountByActionType'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListCountByActionType]
  END
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskListCountByHighlight'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_WDTaskListCountByHighlight]
  END
GO

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDGetTimePassed'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_WDGetTimePassed]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_ConvertTimeToClarion'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_ConvertTimeToClarion]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_ConvertDateAndClarionTimeToDateTime'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_ConvertDateAndClarionTimeToDateTime]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDTaskList'
             AND [XTYPE] = 'P')
    Drop procedure [dbo].[ky_WDTasklist]
Go

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDelTeamView'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDDelTeamView]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDDelView'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDDelView]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDiary3'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDCaseDiary3]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDiaryPage3'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDCaseDiaryPage3]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDiary2'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDCaseDiary2]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDiaryPage'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDCaseDiaryPage]
GO

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDCaseDiary'
             AND [XTYPE] = 'TF')
    Drop function [dbo].[ky_WDCaseDiary]
GO

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_WDGetDate'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_WDGetDate]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_RemoveSpuriousWhitespace'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_RemoveSpuriousWhitespace]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_GetFirstLineOfAddress'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_GetFirstLineOfAddress]
Go

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_UpdateRecentMatterList'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_UpdateRecentMatterList]
  END
GO

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_HeuristicPhoneNumber'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_HeuristicPhoneNumber]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_GetAddressFromEmailAddress'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_GetAddressFromEmailAddress]
Go

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_GetNameFromEmailAddress'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_GetNameFromEmailAddress]
Go

IF EXISTS(SELECT *
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_AddAlarmDelegate'
             AND [XTYPE] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[ky_AddAlarmDelegate]
  END
GO

IF EXISTS(SELECT * 
            FROM SYSOBJECTS
           WHERE [NAME] = 'ky_TimeFromMinutes'
             AND [XTYPE] = 'FN')
    Drop function [dbo].[ky_TimeFromMinutes]
Go

/**************************************************************************************
 *
 * (RE)-Create Functions and Procedures that will be re-generated in this script.
 *
 **************************************************************************************/
GO

create function
       [dbo].[ky_TimeFromMinutes]
      (@time       int)
RETURNS varchar(6)
AS
BEGIN

DECLARE @sign varchar(1)

IF (@time < 0)
  BEGIN
    SET @time = -@time
    SET @sign = '-'
  END
ELSE
  BEGIN
    SET @sign = ''
  END
  
  
RETURN @sign +
       RIGHT('00' + Convert(VARCHAR(4), CONVERT(int, @time / 60)), 2)
             + ':'
             + RIGHT('00' + convert(VARCHAR(2), @time - (60 * CONVERT(int, @time / 60))), 2) 

END
GO

CREATE procedure
       [dbo].[ky_AddAlarmDelegate]
      (@LinkID VARCHAR(50),
       @Handler VARCHAR(5))
AS
BEGIN
   INSERT
     INTO [dbo].[Alarms]
         ([ID],
          [HandlerCode],
          [MatterRef],
          [LinkID],
          [OriginalDate],
          [DeferredDate],
          [Title],
          [Message],
          [Type],
          [Status])
   SELECT convert(VARCHAR(38), newid()),
          @Handler,
          ALM1.[MatterRef],
          @LinkID,
          ALM1.[OriginalDate],
          ALM1.[OriginalDate],
          ALM1.[Title],
          ALM1.[Message],
          ALM1.[Type],
          ALMS.[StatusID]
     FROM [dbo].[Alarms] ALM1
          INNER JOIN [dbo].[AlarmTypes] ALMT
                  ON ALMT.[TypeID] = ALM1.[Type]
                 AND ALMT.[Description] = 'Action'
          INNER JOIN [dbo].[AlarmStatus] ALMS
                  ON ALMS.[Description] = 'Attention'
          LEFT OUTER JOIN [dbo].[Alarms] ALM2
                       ON ALM2.[Type] = ALMT.[TypeID]
                      AND ALM2.[LinkID] = ALM1.[LinkID]
                      AND ALM2.[HandlerCode] = @Handler
          INNER JOIN [dbo].[Diary] DIA
                  ON DIA.[ActionID] = convert(DECIMAL(15,0), @LinkID)
                 AND DIA.[FnCode] = ALM1.[HandlerCode]
    WHERE ALM1.[LinkID] = @LinkID
      AND ALM2.HandlerCode IS NULL
END
GO

/**************************************************************************************
 *
 * ky_GetNameFromEmailAddress
 *
 * Extracts the name from an e-mail address. The e-mail address should be formatted in the
 *    standard format: 
 *                      "Person's Name" <email@address.com>
 *
 * This function can, however, cope with variations such as
 *                      Person's Name <email@address.com>
 *                      <email@address.com>
 *                      email@address.com
 *
 * in the first two examples it will return: Person's Name
 * in the second two examples it will return: email
 *
 **************************************************************************************/
Create Function [dbo].[ky_GetNameFromEmailAddress]
               (@address         varchar(500))
RETURNS varchar(200)
AS
BEGIN
	DECLARE @ltpos int
	DECLARE @before varchar(500)
	
	SET @ltpos = CHARINDEX('<', @address, 1)
	
	IF (@ltpos > 0)
	  BEGIN
	    SET @before = RTRIM(Left(@address, @ltpos - 1))
	  END
	ELSE
	  BEGIN
	    SET @before = @address
	  END
	  
	SET @before = RTRIM(LTrim(Replace(@before, '"', '')))
	
	IF (@before = '')
	  BEGIN
	    SET @before = RTRIM(LTRIM(Replace(Replace(@address, '>', ''), '<', '')))
	  END

	SET @ltpos = CHARINDEX('@', @before, 1)

	IF (@ltpos > 0)
	  BEGIN
	    SET @before = RTRIM(Left(@before, @ltpos - 1))
		SET @before = REPLACE(@before, '.', ' ')
	  END
	  
	RETURN @before
END
GO

/**************************************************************************************
 *
 * ky_GetAddressFromEmailAddress
 *
 * Extracts the name from an e-mail address. The e-mail address should be formatted in the
 *    standard format: 
 *                      "Person's Name" <email@address.com>
 *
 * This function can, however, cope with variations such as
 *                      Person's Name <email@address.com>
 *                      <email@address.com>
 *                      email@address.com
 *
 * in the first two examples it will return: Person's Name
 * in the second two examples it will return: email
 *
 **************************************************************************************/
Create Function [dbo].[ky_GetAddressFromEmailAddress]
               (@address         varchar(500))
RETURNS varchar(200)
AS
BEGIN
	DECLARE @ltpos int
	DECLARE @before varchar(500)
	
	SET @before = RTRIM(@address)
	
	SET @ltpos = CHARINDEX('<', @before, 1)
	
	IF (@ltpos > 0)
	  BEGIN
	    SET @before = RTRIM(RIGHT(@before, LEN(@before) - @ltpos + 1))
	  END
	ELSE
	  BEGIN
	    SET @before = @address
	  END
	  
    SET @before = RTRIM(LTRIM(Replace(Replace(@before, '>', ''), '<', '')))
	  
	RETURN @before
END
GO

/**************************************************************************************
 *
 * ky_WDNextWhile
 *
 * Get the dates between now and a specified number of days/weeks/months/years ahead
 *
 **************************************************************************************/
 CREATE FUNCTION 
        [dbo].[ky_WDNextWhile]
       (@interval varchar(2),
        @number int,
        @FromDate datetime)
RETURNS @Dates Table
       ([date]   datetime,
        [desc]   varchar(20),
        [wkday]  varchar(3))
AS
BEGIN
  DECLARE @ToDate    datetime
  DECLARE @CurDate   Datetime
  DECLARE @DatesIn   int
  DECLARE @WeekCount int
  DECLARE @Desc      varchar(20)
  DECLARE @CurMonth  int
  DECLARE @NewMonth  int
  
  SET @ToDate = CASE @interval
                     WHEN 'DD' 
                          THEN DATEADD(DD, @number, @FromDate)
                     WHEN 'WW' 
                          THEN DATEADD(WW, @number, @FromDate)
                     WHEN 'MM' 
                          THEN DATEADD(MM, @number, @FromDate)
                     WHEN 'YY' 
                          THEN DATEADD(YY, @number, @FromDate)
                     ELSE DATEADD(DD, @number, @FromDate) END
  
  SET @CurDate = convert(datetime, convert(varchar(8), @FromDate, 112))
  SET @WeekCount = 0
  SET @DatesIn   = 0
  SET @CurMonth  = 0
  
  WHILE @CurDate <= @ToDate
    BEGIN
      
      SET @NewMonth = DATEDIFF(MM, @FromDate, @CurDate)

      IF DAY(@CurDate) < DAY(@FromDate)
         SET @NewMonth = @NewMonth - 1
      
      SET @Desc = CASE WHEN @DatesIn = 0
                            THEN ''
                       WHEN @DatesIn = 1
                            THEN '(1 day)'
                       WHEN @DatesIn = 7
                            THEN '(1 week)'
                       WHEN (@CurMonth <> @NewMonth) AND (@NewMonth = 1)
                            THEN '(1 month)'
                       WHEN (@CurMonth <> @NewMonth) AND (@NewMonth > 1)
                            THEN '(' + RTrim(Convert(varchar(2), @NewMonth)) + ' months)'
                       WHEN @WeekCount = 0
                            THEN '(' + RTrim(Convert(varchar(4), (@DatesIn / 7))) + ' weeks)'
                       WHEN @DatesIn < 21
                            THEN '(' + RTrim(Convert(varchar(2), @DatesIn)) + ' days)'
                       ELSE '' END

      IF (@CurMonth <> @NewMonth)
        SET @CurMonth = @NewMonth
                             
      INSERT
        INTO @Dates
            ([date],
             [desc],
             [wkday])
      VALUES(@CurDate,
             @Desc,
             Convert(varchar(3), DATENAME(WEEKDAY, @CurDate)))
      
      SET @DatesIn = @DatesIn + 1
      SET @WeekCount = @WeekCount + 1
      IF (@WeekCount = 7)
        SET @WeekCount = 0
        
      SET @CurDate = DATEADD(DD, 1, @CurDate)
    END
  
  RETURN
  
END
GO

/**************************************************************************************
 *
 * ky_GetFirstLineOfAddress
 *
 * Returns the first line of an address
 *
 **************************************************************************************/
create function
       [dbo].[ky_HeuristicPhoneNumber]
      (@Address varchar(500),
       @FromPhone varchar(30))
RETURNS varchar(30)
AS
BEGIN

DECLARE @StartPos int
DECLARE @FromLen int
DECLARE @Pre int
DECLARE @PreFrom varchar(30)
DECLARE @OrgPhone varchar(30)
DECLARE @Prefix varchar(4)

SET @OrgPhone = RTrim(LTrim(IsNull(@FromPhone, '')))

IF (@OrgPhone = '')
  BEGIN
    RETURN ''
  END

SET @StartPos = 1
SET @FromLen = Len(@FromPhone)
SET @PreFrom = ''
SET @Pre = 0
WHILE (@StartPos <= @FromLen)
  BEGIN
    IF (@Pre = 0)
      BEGIN
        SET @Pre = CASE SUBSTRING(@FromPhone, @StartPos, 1)
                        WHEN '+'
                             THEN 1
                        WHEN '0'
                             THEN 1
                        WHEN '1'
                             THEN 1
                        WHEN '2'
                             THEN 1
                        WHEN '3'
                             THEN 1
                        WHEN '4'
                             THEN 1
                        WHEN '5'
                             THEN 1
                        WHEN '6'
                             THEN 1
                        WHEN '7'
                             THEN 1
                        WHEN '8'
                             THEN 1
                        WHEN '9'
                             THEN 1
                        WHEN '('
                             THEN 1
                        WHEN ')'
                             THEN 1
                        ELSE 0 END

        IF (@Pre = 1)
          BEGIN
            SET @PreFrom = SUBSTRING(@FromPhone, 1, @StartPos - 1)
            SET @OrgPhone = SUBSTRING(@FromPhone, @StartPos, @FromLen - @StartPos + 1)
            SET @OrgPhone = RTrim(LTrim(IsNull(@OrgPhone, '')))
        
            IF (@OrgPhone = '')
            BEGIN
              RETURN ''
            END
          END
      END

    SET @StartPos = @StartPos + 1
  END 

SET @OrgPhone = Replace(@OrgPhone, ' ', '')
SET @OrgPhone = Replace(@OrgPhone, '-', '')
SET @OrgPhone = Replace(@OrgPhone, ',', '')
SET @OrgPhone = Replace(@OrgPhone, '.', '')
SET @OrgPhone = Replace(@OrgPhone, '(', '')
SET @OrgPhone = Replace(@OrgPhone, ')', '')

IF (isnumeric(@OrgPhone) = 0)
  BEGIN
    RETURN @FromPhone
  END

SET @OrgPhone = '=' + @OrgPhone

IF (patindex('%=00%', @OrgPhone) > 0)
  BEGIN
    SET @OrgPhone = Replace(@OrgPhone, '=00', '+')
  END

IF (patindex('%=+%', @OrgPhone) > 0)
  BEGIN
    SET @OrgPhone = Replace(@OrgPhone, '=+', '+')
  END

IF (patindex('%=0%', @OrgPhone) > 0)
  BEGIN
    SET @OrgPhone = Replace(@OrgPhone, '=0', '+353')
  END

IF (patindex('%=%', @OrgPhone) > 0)
  BEGIN
    SET @Address = replace(@Address, 'Dublin Road', '')
    SET @Address = replace(@Address, 'Dublin Street', '')
    SET @Address = replace(@Address, 'Dublin Way', '')
    SET @Address = replace(@Address, 'Dublin Avenue', '')
    SET @Address = replace(@Address, 'Cork Road', '')
    SET @Address = replace(@Address, 'Cork Street', '')
    SET @Address = replace(@Address, 'Cork Way', '')
    SET @Address = replace(@Address, 'Cork Avenue', '')
    SET @Address = replace(@Address, 'Limerick Road', '')
    SET @Address = replace(@Address, 'Limerick Street', '')
    SET @Address = replace(@Address, 'Limerick Way', '')
    SET @Address = replace(@Address, 'Limerick Avenue', '')
    SET @Address = replace(@Address, 'Galway Road', '')
    SET @Address = replace(@Address, 'Galway Street', '')
    SET @Address = replace(@Address, 'Galway Way', '')
    SET @Address = replace(@Address, 'Galway Avenue', '')
    SET @Address = replace(@Address, 'Waterford Road', '')
    SET @Address = replace(@Address, 'Waterford Street', '')
    SET @Address = replace(@Address, 'Waterford Way', '')
    SET @Address = replace(@Address, 'Waterford Avenue', '')
    SET @Address = replace(@Address, 'Wicklow Road', '')
    SET @Address = replace(@Address, 'Wicklow Street', '')
    SET @Address = replace(@Address, 'Wicklow Way', '')
    SET @Address = replace(@Address, 'Wicklow Avenue', '')
    SET @Address = replace(@Address, 'Arklow Road', '')
    SET @Address = replace(@Address, 'Arklow Street', '')
    SET @Address = replace(@Address, 'Arklow Way', '')
    SET @Address = replace(@Address, 'Arklow Avenue', '')
    SET @Address = replace(@Address, 'Sligo Road', '')
    SET @Address = replace(@Address, 'Sligo Street', '')
    SET @Address = replace(@Address, 'Sligo Way', '')
    SET @Address = replace(@Address, 'Sligo Avenue', '')

    SET @Prefix = CASE WHEN patindex('%Dublin%', @Address) > 0
                            THEN '1'
                       WHEN patindex('%Cork%', @Address) > 0
                            THEN '21'
                       WHEN patindex('%Limerick%', @Address) > 0
                            THEN '61'
                       WHEN patindex('%Sligo%', @Address) > 0
                            THEN '71'
                       WHEN patindex('%Galway%', @Address) > 0
                            THEN '91'
                       WHEN patindex('%Waterford%', @Address) > 0
                            THEN '51'
                       WHEN patindex('%Wicklow%', @Address) > 0
                            THEN '404'
                       WHEN patindex('%Arklow%', @Address) > 0
                            THEN '402'
                       ELSE '1' END

    SET @OrgPhone = Replace(@OrgPhone, '=', '+353' + @Prefix)
  END 

RETURN RTrim(LTrim(@PreFrom + @OrgPhone))

END
GO

/**************************************************************************************
 *
 * ky_UpdateRecentMatterList
 *
 * This included in Build 78
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_UpdateRecentMatterList]
      (@FEE varchar(5),
       @Matter varchar(17))
AS
BEGIN
   DECLARE @LastDate datetime
   DECLARE @Now datetime
   DECLARE @RMLCount int
   DECLARE @RMLMax int

   SET @Now = getDate()

     select @RMLMax = HAN.[NORECENTMATTERS]
       from [dbo].[Handlers] HAN
      WHERE HAN.[code] = @FEE
      
        SET @RMLMax = IsNull(@RMLMax, 30)
        
         IF (@RMLMax = 0)
           SET @RMLMax = 30
      
     select TOP 1
            @LastDate = [DateField]
       from [dbo].[RecentMatterList] RML
      where RML.[FEE] = @FEE
        and RML.[DateField] IS NOT NULL
   ORDER BY [DateField] ASC

   UPDATE RML
      SET @LastDate = DateAdd(s, -1, @LastDate),
          RML.[DateField] = @LastDate
     FROM [dbo].[RecentMatterList] RML
    WHERE RML.[FEE] = @FEE
      AND RML.[DateField] IS NULL

   DELETE RML
     FROM [dbo].[RecentMatterList] RML
    WHERE RML.[FEE] = @FEE
      AND RML.[MATTER] = @MATTER

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

   SELECT @RMLCount = count(1)
     FROM [dbo].[RecentMatterList] RML
    WHERE RML.[FEE] = @FEE

   WHILE @RMLCount > @RMLMax
      BEGIN
           select TOP 1
                  @LastDate = [DateField]
             from [dbo].[RecentMatterList] RML
            where RML.[FEE] = @FEE
              and RML.[DateField] IS NOT NULL
         ORDER BY [DateField] ASC

           DELETE RML
             FROM [dbo].[RecentMatterList] RML
            WHERE RML.[FEE] = @FEE
              AND RML.[DateField] = @LastDate

           SELECT @RMLCount = count(1)
             FROM [dbo].[RecentMatterList] RML
            WHERE RML.[FEE] = @FEE
      END
END
GO

/**************************************************************************************
 *
 * ky_GetFirstLineOfAddress
 *
 * Returns the first line of an address
 *
 **************************************************************************************/
create function
       [dbo].[ky_GetFirstLineOfAddress]
      (@original varchar(200))
returns varchar(200)
AS
BEGIN
  DECLARE @pos int

  SET @pos = CharIndex(char(10), @original)

  IF (@pos > 0)
    BEGIN
      SET @original = substring(@original, 1, @pos - 1)
    END

  SET @pos = CharIndex(char(13), @original)

  IF (@pos > 0)
    BEGIN
      SET @original = substring(@original, 1, @pos - 1)
    END

  SET @pos = CharIndex(char(11), @original)

  IF (@pos > 0)
    BEGIN
      SET @original = substring(@original, 1, @pos - 1)
    END

  SET @pos = CharIndex(',', @original)

  IF (@pos > 0)
    BEGIN
      SET @original = substring(@original, 1, @pos - 1)
    END

  RETURN @original
END
GO

/**************************************************************************************
 *
 * ky_WDGetTimePassed
 *
 * gets the time passed between two dates, to the largest level of granularity, e.g.
 * anything over a year is expressed in years, anything over a month as months, anything
 * over a week as weeks. Anything less than that is expressed as days.    
 *     
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDGetTimePassed]
      (@datefrom datetime,
       @dateto datetime)
RETURNS varchar(20)
AS
BEGIN

DECLARE @YYYY int
DECLARE @MM int
DECLARE @WW int
DECLARE @DD int

SET @DD = DATEDIFF(DD, @datefrom, @dateto)
SET @WW = DATEDIFF(WW, @datefrom, @dateto)
SET @MM = DATEDIFF(MM, @datefrom, @dateto)
SET @YYYY = DATEDIFF(YYYY, @datefrom, @dateto)

IF (DATEADD(WW, @WW, @datefrom) > @dateto)
  SET @WW = @WW - 1

IF (DATEADD(MM, @MM, @datefrom) > @dateto)
  SET @MM = @MM - 1

IF (DATEADD(YYYY, @YYYY, @datefrom) > @dateto)
  SET @YYYY = @YYYY - 1
  
RETURN CASE WHEN @YYYY = null
                 THEN 'N/A'
            WHEN @YYYY = 1
                 THEN '(1 year)'
            WHEN @YYYY > 1
                 THEN '(' + convert(varchar(4), @YYYY) + ' years)'
            WHEN @MM = 1
                 THEN '(1 month)'
            WHEN @MM > 1
                 THEN '(' + convert(varchar(6), @MM) + ' months)'
            WHEN @WW = 1
                 THEN '(1 week)'
            WHEN @WW > 1
                 THEN '(' + convert(varchar(6), @WW) + ' weeks)'
            WHEN @DD = 1
                 THEN '(1 day)'
            ELSE '(' + convert(varchar(6), @DD) + ' days)' END
END
GO

/**************************************************************************************
 *
 * ky_ConvertTimeToClarion
 *
 * converts a SQL Date (ignoring any DATE part in that date)
 * to the Clarion Time value, i.e. the number of 1/100 of a second since
 * midnight, plus one.    
 *     
 **************************************************************************************/
create function
       [dbo].[ky_ConvertTimeToClarion]
      (@datetime    datetime)
RETURNS int
AS
BEGIN
  DECLARE @hour int
  DECLARE @minute int
  DECLARE @second int
  DECLARE @centi int
  DECLARE @result int
  
  SET @centi = convert(int,
                       convert(decimal(4, 1), 
                               DATEPART(millisecond, @datetime)) 
                     / convert(decimal(4, 1),
                               10))
                               
  SET @second = DATEPART(second, @datetime)
  SET @minute = DATEPART(minute, @datetime)
  SET @hour = DATEPART(hour, @datetime)

  SET @result = @hour
  SET @result = 60 * @result
  SET @result = @result + @minute
  SET @result = 60 * @result   
  SET @result = @result + @second
  SET @result = 100 * @result
  SET @result = @result + @centi + 1
  
  RETURN @result
END
GO


/**************************************************************************************
 *
 * ky_ConvertDateAndClarionTimeToDateTime
 *
 * converts a SQL Date (ignoring any TIME part in that date) plus a CLARION TIME,
 *     which is a time represented as an integer number, denoting the number of
 *     1/100 of a second since midnight, but for some strange reason starting at
 *     midnight = 1 instead of 0, and combines the two into an ordinary SQL DateTime value
 *     
 *     PLEASE NOTE that in some tables this value is stored in a field of type char(10),
 *                 and that in the past, occasionally, data was written to these fields in
 *                 a standard character representation of the time, i.e. something like
 *                 09:33:20 - this function also caters for that eventuality.
 *
 **************************************************************************************/
create function
       [dbo].[ky_ConvertDateAndClarionTimeToDateTime]
      (@date datetime,
       @CT   char(12))
returns datetime
AS
BEGIN

   DECLARE @CTRES varchar(23)
   DECLARE @resultdate datetime
   DECLARE @CTVAL int
   DECLARE @CTHOURS int

   IF (RTRIM(IsNull(@CT, '')) = '')
      BEGIN
         SET @CTRES = CONVERT(varchar, @date, 112)
         SET @CTRES = REPLACE(@CTRES, '-', '')
         RETURN convert(datetime, @CTRES)
      END

   IF (RTRIM(@CT) = '0')
      BEGIN
         SET @CTRES = CONVERT(varchar, @date, 112)
         SET @CTRES = REPLACE(@CTRES, '-', '')
         RETURN convert(datetime, @CTRES)
      END

   IF (@CT LIKE '%:%')
      BEGIN
         SET @CTRES = CONVERT(varchar, @date, 112)
         SET @CTRES = REPLACE(@CTRES, '-', '')
         SET @resultdate = convert(datetime, @CTRES)

         SET @resultdate = DATEADD(MILLISECOND,
                                   10 * floor(datepart(millisecond, convert(datetime, RTRIM(@CT))) / 10), 
                                   @resultdate)
                                   
         SET @resultdate = DATEADD(second,
                                   datepart(second, convert(datetime, RTRIM(@CT))), 
                                   @resultdate)
                                   
         SET @resultdate = DATEADD(minute,
                                   datepart(minute, convert(datetime, RTRIM(@CT))), 
                                   @resultdate)
                                   
         SET @resultdate = DATEADD(hour,
                                   datepart(hour, convert(datetime, RTRIM(@CT))), 
                                   @resultdate)
                                   
         RETURN @resultdate
      END

   SET @CTVAL = convert(int, @CT) - 1
   SET @CTHOURS = floor(@CTVAL / 360000)

   IF (@CTHOURS > 23)
      BEGIN
         SET @CTRES = CONVERT(varchar, @date, 112)
         SET @CTRES = REPLACE(@CTRES, '-', '')
         RETURN convert(datetime, @CTRES)
      END

   SET @CTVAL = @CTVAL * 10
   
   SET @CTRES = CONVERT(varchar, @date, 112)
   SET @CTRES = REPLACE(@CTRES, '-', '')
   SET @resultdate = convert(datetime, @CTRES)

   SET @resultdate = DATEADD(MILLISECOND,
                             @CTVAL, 
                             @resultdate)

   RETURN @resultdate

END
go

/**************************************************************************************
 *
 * ky_RemoveSpuriousWhitespace
 *
 * 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 lists.
 *
 **************************************************************************************/
create function
       [dbo].[ky_RemoveSpuriousWhitespace]
      (@original varchar(300),
       @maxlen   int)
returns varchar(255)
AS
BEGIN
  DECLARE @len int

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

  SET @len = 0
    WHILE (@len <> len(@original))
      BEGIN
        SET @len = len(@original)
        SET @original = replace(@original, '  ', ' ')
      END

  RETURN substring(@original, 1, @maxlen)
  
END
GO

/**************************************************************************************
 *
 * ky_WDGetDate
 *
 * Emulates the old Clarion GetDate function
 *
 **************************************************************************************/
create function
       [dbo].[ky_WDGetDate]
      (@fromdate     datetime,
       @timetype     varchar(10),
       @timevalue    int)
returns datetime
AS
BEGIN

DECLARE @MO int

  IF ((ISNULL(@timetype, '') = '') OR (UPPER(ISNULL(@timetype, '')) = 'NOW'))
    BEGIN
      SET @fromdate = @fromdate
    END

  IF ((UPPER(ISNULL(@timetype, '')) = 'DAYS') OR (UPPER(ISNULL(@timetype, '')) = 'DAY(S)'))
    BEGIN
      SET @fromdate = dateadd(DD, @timevalue, @fromdate)
    END
    
  IF ((UPPER(ISNULL(@timetype, '')) = 'WEEKS') OR (UPPER(ISNULL(@timetype, '')) = 'WEEK(S)'))
    BEGIN
      SET @fromdate = dateadd(WK, @timevalue, @fromdate)
    END

  IF ((UPPER(ISNULL(@timetype, '')) = 'MONTHS') OR (UPPER(ISNULL(@timetype, '')) = 'MONTH(S)'))
    BEGIN
      SET @fromdate = dateadd(MM, @timevalue, @fromdate)
    END

  IF ((UPPER(ISNULL(@timetype, '')) = 'YEARS') OR (UPPER(ISNULL(@timetype, '')) = 'YEAR(S)'))
    BEGIN
      SET @fromdate = dateadd(YY, @timevalue, @fromdate)
    END
    
  SET @MO = DATEPART(dw, dateadd(d, 6, @fromdate)) - DATEPART(dw, '20000103')
  SET @MO =  CASE WHEN @MO > 0
                       THEN @MO
                  ELSE @MO + 7 END
                
  SET @MO = CASE WHEN @MO < 5 THEN 0 ELSE (7 - @MO) END
  
  --Always make sure you return a Monday / Friday
  SET @fromdate = DATEADD(d, @mo, @fromdate)
  
  --We should look into including code to avoid Bank Holidays here ...
  
  RETURN @fromdate  
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDiary
 *
 * Case Diary view
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDCaseDiary]
      (@casecode        varchar(20),
       @actionid        int)
RETURNS @DV TABLE
       ([CaseCode]             varchar(20),
        [WKCode]               varchar(10),
        [Action]               varchar(255),
        [Status]               int,
        [ActionType]           varchar(1),
        [Priority]             varchar(1),
        [DelegateStatus]       int,
        [ImageNo]              int,
        [Handler]              varchar(10),
        [Team]                 varchar(10),
        [FromHandler]          varchar(10),
        [ActionID]             int,
        [DiaryStatus]          int,
        [Highlighted]          varchar(1),
        [Attachments]          varchar(1),
        [DiaryDate]            varchar(11),
        [DiaryTime]            varchar(5),
        [FNCode]               varchar(10),
        [TeamCode]             varchar(10),
        [WorkProcess]          int,
        [DelegationStatus]     int,
        [ActionCode]           varchar(30),
        [Duration]             varchar(30),
        [DelegatedDateTime]    datetime,
        [SELECTEDLINE]         int,
        [AssignNo]         int)
AS
BEGIN

  INSERT
    INTO @DV
        ([CaseCode],
         [WKCode],
         [Action],
         [Status],
         [ActionType],
         [Priority],
         [DelegateStatus],
         [ImageNo],
         [Handler],
         [Team],
         [FromHandler],
         [ActionID],
         [DiaryStatus],
         [Highlighted],
         [Attachments],
         [DiaryDate],
         [DiaryTime],
         [FNCode],
         [TeamCode],
         [WorkProcess],
         [DelegationStatus],
         [ActionCode],
         [Duration],
         [DelegatedDateTime],
         [SELECTEDLINE],
         [AssignNo])
  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
         CM.[CSWKTCODE],
         CASE WHEN DIA.[ActionType] = 'E'
                   THEN SUBSTRING('Email from: ' + Rtrim(IsNull([dbo].[ky_GetNameFromEmailAddress](DIA.[EmailAddress]), '')) + ' - ' + RTrim(IsNull(convert(varchar(2000), DIA.[Subject]), '')), 1, 120)
              ELSE SUBSTRING(DIA.[TEXT1], 1, 120) END As [Action],
         DEL.[Status],
         IsNull(DIA.[ActionType], '') As [ActionType],
         IsNull(DIA.[Priority], '') As [Priority],
         IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
         DIA.[ImageNo],
         IsNull(DEL.[Handler], '') As [Handler],
         IsNull(DEL.[Team], '') As [Team],
         IsNull(DEL.[FromHandler], '') As [FromHandler],
         DIA.[ActionID] As [ActionID],
         IsNull(DIA.[Status], 0) As [DiaryStatus],
         IsNull(DIA.[Highlighted], '') As [Highlighted],
         IsNull(DIA.[Attachments], '') As [Attachments],
         Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
         SUBSTRING(Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[DYSTARTTIME]), 108), 1, 5) AS [DiaryTime],
         RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
         IsNull(DIA.[TeamCode], '') AS [TeamCode],
         IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
         Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
         RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
         CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                   THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
              ELSE '' END AS [DURATION],
         [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime],
         CASE WHEN DIA.[ActionID] = @ActionID
                   THEN 1
              ELSE 0 END As [SELECTEDLINE],
         DEL.[AssignNo] As [AssignNo]
    FROM [dbo].[Diary] DIA
         CROSS APPLY (  SELECT TOP 1 
                               DELX.[STATUS],
                               DELX.[DELEGATESTATUS],
                               DELX.[HANDLER],
                               DELX.[TEAM],
                               DELX.[FROMHANDLER],
                               DELX.[DATE],
                               DELX.[TIME],
                               DELX.[ASSIGNNO]
                          FROM [dbo].[DiaryDelegations] DELX
                         WHERE DELX.[ActionID] = DIA.[ActionID]
                           AND DELX.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                      ORDER BY DELX.[AssignNo] DESC) DEL
         INNER JOIN [dbo].[CaseMaster] CM
                 ON CM.[CSCODE] = DIA.[CASECODE]
   WHERE DIA.[CaseCode] = @casecode

UPDATE DV
   SET DV.[Action] = [dbo].[ky_removespuriouswhitespace](DV.[Action], 80)
  FROM @DV DV
       INNER JOIN [dbo].[Diary] DIA
               ON DIA.[ActionID] = DV.[ActionID]

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDiaryPage
 *
 * Retrieve a page from the Case Diary
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDCaseDiaryPage]
      (@CASECODE     VARCHAR(20),
       @start        int,
       @pagesize     int)
RETURNS @CD TABLE
       ([ID]             int identity(1, 1),
        [ActionID]       int,
        [DiaryDate]      datetime)
AS
BEGIN
    INSERT
      INTO @CD
          ([ActionID],
           [DiaryDate])
    SELECT DIA.[ActionID],
           DIA.[Date]
      FROM [dbo].[Diary] DIA
     WHERE DIA.[CASECODE] = @CASECODE
  ORDER BY DIA.[Status],
           DIA.[DATE] DESC

  DELETE @CD
   WHERE [ID] < @start
   
  DELETE @CD
   WHERE [ID] >= @start + @pagesize
   
  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDiary2
 *
 * Case Diary view with support for paging
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDCaseDiary2]
      (@casecode        varchar(20),
       @start           int,
       @pagesize        int)
RETURNS @DV TABLE
       ([CaseCode]             varchar(20),
        [WKCode]               varchar(10),
        [Action]               varchar(255),
        [Status]               int,
        [ActionType]           varchar(1),
        [Priority]             varchar(1),
        [DelegateStatus]       int,
        [ImageNo]              int,
        [Handler]              varchar(10),
        [Team]                 varchar(10),
        [FromHandler]          varchar(10),
        [ActionID]             int,
        [DiaryStatus]          int,
        [Highlighted]          varchar(1),
        [Attachments]          varchar(1),
        [DiaryDate]            varchar(11),
        [DiaryTime]            varchar(5),
        [FNCode]               varchar(10),
        [TeamCode]             varchar(10),
        [WorkProcess]          int,
        [DelegationStatus]     int,
        [ActionCode]           varchar(30),
        [Duration]             varchar(30),
        [DelegatedDateTime]    datetime,
        [AssignNo]         int)
AS
BEGIN

  INSERT
    INTO @DV
        ([CaseCode],
         [WKCode],
         [Action],
         [Status],
         [ActionType],
         [Priority],
         [DelegateStatus],
         [ImageNo],
         [Handler],
         [Team],
         [FromHandler],
         [ActionID],
         [DiaryStatus],
         [Highlighted],
         [Attachments],
         [DiaryDate],
         [DiaryTime],
         [FNCode],
         [TeamCode],
         [WorkProcess],
         [DelegationStatus],
         [ActionCode],
         [Duration],
         [DelegatedDateTime],
         [AssignNo])
  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
         CM.[CSWKTCODE],
         CASE WHEN DIA.[ActionType] = 'E'
                   THEN SUBSTRING('Email from: ' + Rtrim(IsNull([dbo].[ky_GetNameFromEmailAddress](DIA.[EmailAddress]), '')) + ' - ' + RTrim(IsNull(convert(varchar(2000), DIA.[Subject]), '')), 1, 120)
              ELSE SUBSTRING(DIA.[TEXT1], 1, 120) END As [Action],
         DEL.[Status],
         IsNull(DIA.[ActionType], '') As [ActionType],
         IsNull(DIA.[Priority], '') As [Priority],
         IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
         DIA.[ImageNo],
         IsNull(DEL.[Handler], '') As [Handler],
         IsNull(DEL.[Team], '') As [Team],
         IsNull(DEL.[FromHandler], '') As [FromHandler],
         DIA.[ActionID] As [ActionID],
         IsNull(DIA.[Status], 0) As [DiaryStatus],
         IsNull(DIA.[Highlighted], '') As [Highlighted],
         IsNull(DIA.[Attachments], '') As [Attachments],
         Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
         SUBSTRING(Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[DYSTARTTIME]), 108), 1, 5) AS [DiaryTime],
         RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
         IsNull(DIA.[TeamCode], '') AS [TeamCode],
         IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
         Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
         RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
         CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                   THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
              ELSE '' END AS [DURATION],
         [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime],
         DEL.[AssignNo] As [AssignNo]
    FROM [dbo].[ky_wdcasediarypage](@CASECODE, @start, @pagesize) DIP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ACTIONID] = DIP.[ACTIONID]
         CROSS APPLY (  SELECT TOP 1 
                               DELX.[STATUS],
                               DELX.[DELEGATESTATUS],
                               DELX.[HANDLER],
                               DELX.[TEAM],
                               DELX.[FROMHANDLER],
                               DELX.[DATE],
                               DELX.[TIME],
                               DELX.[ASSIGNNO]
                          FROM [dbo].[DiaryDelegations] DELX
                         WHERE DELX.[ActionID] = DIA.[ActionID]
                           AND DELX.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                      ORDER BY DELX.[AssignNo] DESC) DEL
         INNER JOIN [dbo].[CaseMaster] CM
                 ON CM.[CSCODE] = DIA.[CASECODE]

UPDATE DV
   SET DV.[Action] = [dbo].[ky_removespuriouswhitespace](DV.[Action], 80)
  FROM @DV DV
       INNER JOIN [dbo].[Diary] DIA
               ON DIA.[ActionID] = DV.[ActionID]

RETURN
END

GO

/**************************************************************************************
 *
 * ky_WDCaseDiaryPage3
 *
 * Retrieve a page from the Case Diary, with search criteria
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDCaseDiaryPage3]
      (@CASECODE     VARCHAR(20),
       @start        int,
       @pagesize     int,
       @search       varchar(100),
       @ActionType   varchar(1),
       @highlighted  varchar(1),
       @Priority     varchar(1))
RETURNS @CD TABLE
       ([ID]             int identity(1, 1),
        [ActionID]       int,
        [DiaryDate]      datetime)
AS
BEGIN

    SET @search = REPLACE('%' + RTRIM(ISNULL(@search, '')) + '%', '%%', '%')
    SET @highlighted = CASE WHEN UPPER(ISNULL(@highlighted, 'N')) = 'Y'
                                 THEN 'Y'
                            ELSE '' END
    SET @ActionType = RTRIM(ISNULL(@actiontype, ''))
    SET @Priority = RTRIM(ISNULL(@priority, ''))
    
    INSERT
      INTO @CD
          ([ActionID],
           [DiaryDate])
    SELECT DIA.[ActionID],
           DIA.[Date]
      FROM [dbo].[Diary] DIA
     WHERE DIA.[CASECODE] = @CASECODE
       AND (   @search = '%'
            OR CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
            OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search)
       AND (   @highlighted = ''
            OR DIA.[HIGHLIGHTED] = 'Y')
       AND (   @ActionType = ''
            OR DIA.[ACTIONTYPE] = @ActionType)
       AND (   @Priority = ''
            OR DIA.[PRIORITY] = @Priority)
  ORDER BY DIA.[Status],
           DIA.[DATE] DESC

  DELETE @CD
   WHERE [ID] < @start
   
  DELETE @CD
   WHERE [ID] >= @start + @pagesize
   
  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDiary3
 *
 * Case Diary view with support for paging
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDCaseDiary3]
      (@casecode        varchar(20),
       @start           int,
       @pagesize        int,
       @search          varchar(100),
       @ActionType      varchar(1),
       @highlighted     varchar(1),
       @priority        varchar(1))
RETURNS @DV TABLE
       ([DIPID]                int,
        [CaseCode]             varchar(20),
        [WKCode]               varchar(10),
        [Action]               varchar(255),
        [Status]               int,
        [ActionType]           varchar(1),
        [Priority]             varchar(1),
        [DelegateStatus]       int,
        [ImageNo]              int,
        [Handler]              varchar(10),
        [Team]                 varchar(10),
        [FromHandler]          varchar(10),
        [ActionID]             int,
        [DiaryStatus]          int,
        [Highlighted]          varchar(1),
        [Attachments]          varchar(1),
        [DiaryDate]            varchar(11),
        [DiaryTime]            varchar(5),
        [FNCode]               varchar(10),
        [TeamCode]             varchar(10),
        [WorkProcess]          int,
        [DelegationStatus]     int,
        [ActionCode]           varchar(30),
        [Duration]             varchar(30),
        [DelegatedDateTime]    datetime,
        [AssignNo]         int)
AS
BEGIN

  INSERT
    INTO @DV
        ([DIPID],
         [CaseCode],
         [WKCode],
         [Action],
         [Status],
         [ActionType],
         [Priority],
         [DelegateStatus],
         [ImageNo],
         [Handler],
         [Team],
         [FromHandler],
         [ActionID],
         [DiaryStatus],
         [Highlighted],
         [Attachments],
         [DiaryDate],
         [DiaryTime],
         [FNCode],
         [TeamCode],
         [WorkProcess],
         [DelegationStatus],
         [ActionCode],
         [Duration],
         [DelegatedDateTime],
         [AssignNo])
  SELECT DIP.[ID],
         RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
         CM.[CSWKTCODE],
         CASE WHEN DIA.[ActionType] = 'E'
                   THEN SUBSTRING('Email from: ' + Rtrim(IsNull([dbo].[ky_GetNameFromEmailAddress](DIA.[EmailAddress]), '')) + ' - ' + RTrim(IsNull(convert(varchar(2000), DIA.[Subject]), '')), 1, 120)
              ELSE SUBSTRING(DIA.[TEXT1], 1, 120) END As [Action],
         DEL.[Status],
         IsNull(DIA.[ActionType], '') As [ActionType],
         IsNull(DIA.[Priority], '') As [Priority],
         IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
         DIA.[ImageNo],
         IsNull(DEL.[Handler], '') As [Handler],
         IsNull(DEL.[Team], '') As [Team],
         IsNull(DEL.[FromHandler], '') As [FromHandler],
         DIA.[ActionID] As [ActionID],
         IsNull(DIA.[Status], 0) As [DiaryStatus],
         IsNull(DIA.[Highlighted], '') As [Highlighted],
         IsNull(DIA.[Attachments], '') As [Attachments],
         Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
         SUBSTRING(Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[DYSTARTTIME]), 108), 1, 5) AS [DiaryTime],
         RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
         IsNull(DIA.[TeamCode], '') AS [TeamCode],
         IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
         Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
         RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
         CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                   THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
              ELSE '' END AS [DURATION],
         [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime],
         DEL.[AssignNo] As [AssignNo]
    FROM [dbo].[ky_wdcasediarypage3](@CASECODE,
                                     @start,
                                     @pagesize,
                                     @search,
                                     @ActionType,
                                     @highlighted,
                                     @priority) DIP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ACTIONID] = DIP.[ACTIONID]
         CROSS APPLY (  SELECT TOP 1 
                               DELX.[STATUS],
                               DELX.[DELEGATESTATUS],
                               DELX.[HANDLER],
                               DELX.[TEAM],
                               DELX.[FROMHANDLER],
                               DELX.[DATE],
                               DELX.[TIME],
                               DELX.[ASSIGNNO]
                          FROM [dbo].[DiaryDelegations] DELX
                         WHERE DELX.[ActionID] = DIA.[ActionID]
                           AND DELX.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                      ORDER BY DELX.[AssignNo] DESC) DEL
         INNER JOIN [dbo].[CaseMaster] CM
                 ON CM.[CSCODE] = DIA.[CASECODE]
ORDER BY DIP.[ID]

UPDATE DV
   SET DV.[Action] = [dbo].[ky_removespuriouswhitespace](DV.[Action], 80)
  FROM @DV DV
       INNER JOIN [dbo].[Diary] DIA
               ON DIA.[ActionID] = DV.[ActionID]

RETURN
END


GO

/**************************************************************************************
 *
 * ky_WDDelView
 *
 * Delegations view
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDDelView]
      (@handler         varchar(10),
       @startdate       datetime,
       @enddate         datetime,
       @outstanding     int)
RETURNS @DV TABLE
       ([CaseCode]             varchar(20),
        [Action]               varchar(255),
        [Status]               int,
        [ActionType]           varchar(1),
        [Priority]             varchar(1),
        [DelegateStatus]       int,
        [ImageNo]              int,
        [Handler]              varchar(10),
        [Team]                 varchar(10),
        [FromHandler]          varchar(10),
        [ActionID]             int,
        [DiaryStatus]          int,
        [Highlighted]          varchar(1),
        [Attachments]          varchar(1),
        [DiaryDate]            varchar(11),
        [FNCode]               varchar(10),
        [TeamCode]             varchar(10),
        [WorkProcess]          int,
        [DelegationStatus]     int,
        [ActionCode]           varchar(30),
        [Duration]             varchar(30),
        [DelegatedDateTime]    datetime)
AS
BEGIN

SET @outstanding = isnull(@outstanding, 1)

  INSERT
    INTO @DV
        ([CaseCode],
         [Action],
         [Status],
         [ActionType],
         [Priority],
         [DelegateStatus],
         [ImageNo],
         [Handler],
         [Team],
         [FromHandler],
         [ActionID],
         [DiaryStatus],
         [Highlighted],
         [Attachments],
         [DiaryDate],
         [FNCode],
         [TeamCode],
         [WorkProcess],
         [DelegationStatus],
         [ActionCode],
         [Duration],
         [DelegatedDateTime])
  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
         '' As [Action],
         DEL.[Status],
         IsNull(DIA.[ActionType], '') As [ActionType],
         IsNull(DIA.[Priority], '') As [Priority],
         IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
         DIA.[ImageNo],
         IsNull(DEL.[Handler], '') As [Handler],
         IsNull(DEL.[Team], '') As [Team],
         IsNull(DEL.[FromHandler], '') As [FromHandler],
         DIA.[ActionID] As [ActionID],
         IsNull(DIA.[Status], 0) As [DiaryStatus],
         IsNull(DIA.[Highlighted], '') As [Highlighted],
         IsNull(DIA.[Attachments], '') As [Attachments],
         Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
         RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
         IsNull(DIA.[TeamCode], '') AS [TeamCode],
         IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
         Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
         RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
         CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                   THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
              ELSE '' END AS [DURATION],
         [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime]
    FROM [dbo].[DiaryDelegations] DEL
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = DEL.[ActionID]
--         INNER JOIN [dbo].[WDOpenMatters] WOM
--                 ON WOM.[Code] = DIA.[CASECODE]
   WHERE DEL.[Handler] = @handler
     AND DEL.[DATE] >= @startdate
     AND DEL.[DATE] < @enddate
     AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
     AND (   @outstanding = 0
          OR DEL.[Status] = 0)

UPDATE DV
   SET DV.[Action] = [dbo].[ky_removespuriouswhitespace](substring(DIA.[TEXT1], 1, 120), 80)
  FROM @DV DV
       INNER JOIN [dbo].[Diary] DIA
               ON DIA.[ActionID] = DV.[ActionID]

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDDelTeamView
 *
 * Delegations by Team view
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDDelTeamView]
      (@team            varchar(10),
       @startdate       datetime,
       @enddate         datetime,
       @outstanding     int)
RETURNS @DV TABLE
       ([CaseCode]             varchar(20),
        [Action]               varchar(255),
        [Status]               int,
        [ActionType]           varchar(1),
        [Priority]             varchar(1),
        [DelegateStatus]       int,
        [ImageNo]              int,
        [Handler]              varchar(10),
        [Team]                 varchar(10),
        [FromHandler]          varchar(10),
        [ActionID]             int,
        [DiaryStatus]          int,
        [Highlighted]          varchar(1),
        [Attachments]          varchar(1),
        [DiaryDate]            varchar(11),
        [FNCode]               varchar(10),
        [TeamCode]             varchar(10),
        [WorkProcess]          int,
        [DelegationStatus]     int,
        [ActionCode]           varchar(30),
        [Duration]             varchar(30),
        [DelegatedDateTime]    datetime)
AS
BEGIN

SET @outstanding = isnull(@outstanding, 1)

  INSERT
    INTO @DV
        ([CaseCode],
         [Action],
         [Status],
         [ActionType],
         [Priority],
         [DelegateStatus],
         [ImageNo],
         [Handler],
         [Team],
         [FromHandler],
         [ActionID],
         [DiaryStatus],
         [Highlighted],
         [Attachments],
         [DiaryDate],
         [FNCode],
         [TeamCode],
         [WorkProcess],
         [DelegationStatus],
         [ActionCode],
         [Duration],
         [DelegatedDateTime])
  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
         '' As [Action],
         DEL.[Status],
         IsNull(DIA.[ActionType], '') As [ActionType],
         IsNull(DIA.[Priority], '') As [Priority],
         IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
         DIA.[ImageNo],
         IsNull(DEL.[Handler], '') As [Handler],
         IsNull(DEL.[Team], '') As [Team],
         IsNull(DEL.[FromHandler], '') As [FromHandler],
         DIA.[ActionID] As [ActionID],
         IsNull(DIA.[Status], 0) As [DiaryStatus],
         IsNull(DIA.[Highlighted], '') As [Highlighted],
         IsNull(DIA.[Attachments], '') As [Attachments],
         Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
         RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
         IsNull(DIA.[TeamCode], '') AS [TeamCode],
         IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
         Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
         RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
         CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                   THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
              ELSE '' END AS [DURATION],
         [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime]
    FROM [dbo].[DiaryDelegations] DEL
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = DEL.[ActionID]
--         INNER JOIN [dbo].[WDOpenMatters] WOM
--                 ON WOM.[Code] = DIA.[CASECODE]
   WHERE DEL.[Team] = @team
     AND DEL.[DATE] >= @startdate
     AND DEL.[DATE] < @enddate
     AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
     AND (   @outstanding = 0
          OR DEL.[Status] = 0)

UPDATE DV
   SET DV.[Action] = [dbo].[ky_removespuriouswhitespace](substring(DIA.[TEXT1], 1, 120), 80)
  FROM @DV DV
       INNER JOIN [dbo].[Diary] DIA
               ON DIA.[ActionID] = DV.[ActionID]

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDTaskList
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskList]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int)
AS
BEGIN

  DECLARE @startdate datetime
  DECLARE @enddate   datetime

  IF (IsNull(@startdateT, '') = '')
    BEGIN
      SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
    END
  ELSE
    BEGIN
      IF (isdate(@startdateT) = 1)
        BEGIN
          set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
        END
      ELSE
        BEGIN
          SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
        END
    END

  IF (IsNull(@enddateT, '') = '')
    BEGIN
      SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
    END
  ELSE
    BEGIN
      IF (isdate(@enddateT) = 1)
        BEGIN
          set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
        END
      ELSE
        BEGIN
          SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
        END
    END

  IF (RTrim(IsNull(@Handler, '')) <> '')
    BEGIN
      SET @Team = ''

      IF (IsNull(@outstanding, 1) = 0)
        BEGIN
            SELECT TSK.[CaseCode],
                   TSK.[Action],
                   RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
                   RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
                   Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
                   Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
                   TSK.[Status],
                   TSK.[ActionType],
                   TSK.[Priority],
                   TSK.[DelegateStatus],
                   TSK.[ImageNo],
                   TSK.[Handler],
                   TSK.[Team],
                   TSK.[FromHandler],
                   TSK.[ActionID],
                   TSK.[DiaryStatus],
                   TSK.[Highlighted],
                   TSK.[Attachments],
                   TSK.[DiaryDate],
                   TSK.[FNCode],
                   TSK.[TeamCode],
                   TSK.[WorkProcess],
                   TSK.[DelegationStatus],
                   TSK.[ActionCode],
                   TSK.[DURATION],
                   TSK.[DELEGATEDDATETIME]
              FROM [dbo].[ky_WDDelView](@Handler, @startdate, @enddate, @outstanding) TSK
                   INNER JOIN [dbo].[matters] MAT
                              INNER JOIN [dbo].[contacts] CTC
                                      ON CTC.[CODE] = MAT.[CLIENTCODE]
                           ON MAT.[Code] = TSK.[CASECODE]
          ORDER BY TSK.[DelegatedDateTime],
                   TSK.[ActionID]
        END
      ELSE
        BEGIN
            SELECT TSK.[CaseCode],
                   TSK.[Action],
                   RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
                   RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
                   Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
                   Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
                   TSK.[Status],
                   TSK.[ActionType],
                   TSK.[Priority],
                   TSK.[DelegateStatus],
                   TSK.[ImageNo],
                   TSK.[Handler],
                   TSK.[Team],
                   TSK.[FromHandler],
                   TSK.[ActionID],
                   TSK.[DiaryStatus],
                   TSK.[Highlighted],
                   TSK.[Attachments],
                   TSK.[DiaryDate],
                   TSK.[FNCode],
                   TSK.[TeamCode],
                   TSK.[WorkProcess],
                   TSK.[DelegationStatus],
                   TSK.[ActionCode],
                   TSK.[DURATION],
                   TSK.[DELEGATEDDATETIME]
              FROM [dbo].[ky_WDDelView](@Handler, @startdate, @enddate, @outstanding) TSK
                   INNER JOIN [dbo].[matters] MAT
                              INNER JOIN [dbo].[contacts] CTC
                                      ON CTC.[CODE] = MAT.[CLIENTCODE]
                           ON MAT.[Code] = TSK.[CASECODE]
             WHERE TSK.[Status] = 0
          ORDER BY TSK.[DelegatedDateTime],
                   TSK.[ActionID]
        END
    END


  IF (RTrim(IsNull(@Team, '')) <> '')
    BEGIN
      IF (IsNull(@outstanding, 1) = 0)
        BEGIN
            SELECT TSK.[CaseCode],
                   TSK.[Action],
                   RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
                   RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
                   Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
                   Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
                   TSK.[Status],
                   TSK.[ActionType],
                   TSK.[Priority],
                   TSK.[DelegateStatus],
                   TSK.[ImageNo],
                   TSK.[Handler],
                   TSK.[Team],
                   TSK.[FromHandler],
                   TSK.[ActionID],
                   TSK.[DiaryStatus],
                   TSK.[Highlighted],
                   TSK.[Attachments],
                   TSK.[DiaryDate],
                   TSK.[FNCode],
                   TSK.[TeamCode],
                   TSK.[WorkProcess],
                   TSK.[DelegationStatus],
                   TSK.[ActionCode],
                   TSK.[DURATION],
                   TSK.[DELEGATEDDATETIME]
              FROM [dbo].[ky_WDDelTeamView](@Team, @startdate, @enddate, @outstanding) TSK
                   INNER JOIN [dbo].[matters] MAT
                              INNER JOIN [dbo].[contacts] CTC
                                      ON CTC.[CODE] = MAT.[CLIENTCODE]
                           ON MAT.[Code] = TSK.[CASECODE]
          ORDER BY TSK.[DelegatedDateTime],
                   TSK.[ActionID]
        END
      ELSE
        BEGIN
            SELECT TSK.[CaseCode],
                   TSK.[Action],
                   RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
                   RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
                   Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
                   Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
                   TSK.[Status],
                   TSK.[ActionType],
                   TSK.[Priority],
                   TSK.[DelegateStatus],
                   TSK.[ImageNo],
                   TSK.[Handler],
                   TSK.[Team],
                   TSK.[FromHandler],
                   TSK.[ActionID],
                   TSK.[DiaryStatus],
                   TSK.[Highlighted],
                   TSK.[Attachments],
                   TSK.[DiaryDate],
                   TSK.[FNCode],
                   TSK.[TeamCode],
                   TSK.[WorkProcess],
                   TSK.[DelegationStatus],
                   TSK.[ActionCode],
                   TSK.[DURATION],
                   TSK.[DELEGATEDDATETIME]
              FROM [dbo].[ky_WDDelTeamView](@Team, @startdate, @enddate, @outstanding) TSK
                   INNER JOIN [dbo].[matters] MAT
                              INNER JOIN [dbo].[contacts] CTC
                                      ON CTC.[CODE] = MAT.[CLIENTCODE]
                           ON MAT.[Code] = TSK.[CASECODE]
             WHERE TSK.[Status] = 0
          ORDER BY TSK.[DelegatedDateTime],
                   TSK.[ActionID]
        END
    END
END
GO

/**************************************************************************************
 *
 * ky_WDDiaryDocList
 *
 * Lists Diary documents (Diary Attachments). With support for Paging.
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDDiaryDocList]
       (@actionID int,
        @search   varchar(50),
        @startno  int,
        @count    int)
RETURNS @CDL TABLE
       ([docid]                 int               IDENTITY(1, 1),
        [CASECODE]              varchar(20),
        [DATE]                  datetime,
        [DIARYID]               int,
        [TrackReference]        int)
AS
BEGIN

  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

  IF (@search = '%')
    BEGIN
        INSERT
          INTO @CDL
              ([CASECODE],
               [DATE],
               [DIARYID],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
         WHERE DIA.[ACTIONID] = @actionID
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END
  ELSE
    BEGIN
        INSERT
          INTO @CDL
              ([CASECODE],
               [DATE],
               [DIARYID],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
         WHERE DIA.[ACTIONID] = @actionID
           AND (   DAT.[Document] LIKE @search
                OR DIA.[subject] LIKE @search
                OR DIA.[emailaddress] LIKE @search
                OR Substring(DIA.[AddressTo], 1, 200) LIKE @search)
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END

    DELETE @CDL
     WHERE [docid] < @startno

    DELETE @CDL
     WHERE [docid] > (@startno + @count - 1)

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDocList2
 *
 * Lists case documents. With support for Paging.
 * Supersedes ky_WDCaseDocList. Includes checks for selected classes,
 *                              the option to exclude images from the result,
 *                              or selected document types
 *
 * Note: parameter format for selected classes or selected types (@classes and @types)
 *       is (e.g.) '*Item1*Item2*Item3*Item4*'
 *       to select all classes or all types, pass in '' or NULL
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDCaseDocList2]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int,
        @classes  varchar(max),
        @noimg    int,
        @types    varchar(max))
RETURNS @CDL TABLE
       ([docid]                 int               IDENTITY(1, 1),
        [CASECODE]              varchar(20),
        [DATE]                  datetime,
        [DIARYID]               int,
        [TrackReference]        int)
AS
BEGIN

  DECLARE @noimgtypes varchar(max)
  
  IF (@noimg = 1)
    SET @noimgtypes = '*GIF*JPG*JPEG*BMP*PNG*TIF*TIFF*'
  ELSE
    SET @noimgtypes = '*'
    
  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

  IF (@search = '%')
    BEGIN
        INSERT
          INTO @CDL
              ([CASECODE],
               [DATE],
               [DIARYID],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
                      AND @noimgtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND (   (@types is NULL)
                           OR (@types LIKE '%*' + DAT.[TYPE] + '*%'))
                      AND (   (@classes is NULL)
                           OR (@classes LIKE '%*' + DAT.[DOCCLASS] + '*%'))
         WHERE DIA.[CASECODE] = @casecode
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END
  ELSE
    BEGIN
        INSERT
          INTO @CDL
              ([CASECODE],
               [DATE],
               [DIARYID],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
                      AND @noimgtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND (   (@types is NULL)
                           OR (@types LIKE '%*' + DAT.[TYPE] + '*%'))
                      AND (   (@classes is NULL)
                           OR (@classes LIKE '%*' + DAT.[DOCCLASS] + '*%'))
         WHERE DIA.[CASECODE] = @casecode
           AND (   DAT.[Document] LIKE @search
                OR DIA.[subject] LIKE @search
                OR DIA.[emailaddress] LIKE @search
                OR Substring(DIA.[AddressTo], 1, 200) LIKE @search)
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END

    DELETE @CDL
     WHERE [docid] < @startno

    DELETE @CDL
     WHERE [docid] > (@startno + @count - 1)

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDocuments2
 *
 * Lists case documents (expanded list). With support for Paging.
 *
 **************************************************************************************/
 CREATE PROCEDURE
        [dbo].[ky_WDCaseDocuments2]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int,
        @classes  varchar(max),
        @noimg    int,
        @types    varchar(max))
AS
BEGIN
  IF (RTRIM(ISNULL(@classes, '')) = '')
    BEGIN
      set @classes = NULL
    END

  IF (RTRIM(ISNULL(@types, '')) = '')
    BEGIN
      set @types = NULL
    END
        
  SELECT Convert(VARCHAR, DIA.[DATE], 106) AS [DocumentDate],
         DAT.[DOCCLASS] AS [DocumentClass],
         UPPER(RTRIM(ISNULL(DAT.[TYPE], ''))) AS [TYPE],
         RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], '')) AS [DocumentClassDescription],
         RTRIM(ISNULL(DAT.[Source], '')) AS [DocumentSource],
         RTRIM(ISNULL(DIA.[EMAILADDRESS], '')) AS [EmailAddress],
         KYD.[AddressTo] AS [AddressTo],
         KYD.[SUBJECT] AS [SUBJECT],
         RTRIM(ISNULL(DAT.[ENTEREDBY], '')) AS [ENTEREDBY],
         ISNULL(Convert(VARCHAR, DAT.[DateEntered], 106), '') AS [DATEENTERED],
         RTRIM(ISNULL(DAT.[LASTACCESSBY], '')) AS [LASTACCESSBY],
         ISNULL(Convert(VARCHAR, DAT.[LASTACCESSDATE], 106), '') AS [LASTACCESSDATE],
         CASE WHEN ISNULL(DIA.[EMAIL], '') = 'Y'
                   THEN 'Y'
              WHEN (OMS.[TYPE] = 'MSG')
                   THEN 'Y'
              ELSE 'N' END AS [EMAIL],
         RTRIM(ISNULL(DAT.[Document], '')) AS [OriginalDocumentName],
         CASE WHEN (ISNULL(DIA.[EMAIL], '') = 'Y') OR (OMS.[TYPE] = 'MSG')
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [ShortDocument],
         CASE WHEN (    (   (ISNULL(DIA.[EMAIL], '') = 'Y')
                         OR (OMS.[TYPE] = 'MSG'))
                    AND (DAT.TrackReference = OMS.TrackReference))
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END + 
                        ': ' + 
                        CASE UPPER(KYD.[SUBJECT])
                             WHEN ''
                                  THEN '[no subject]'
                             WHEN 'FW:'
                                  THEN 'FW: [no subject]'
                             WHEN 'RE:'
                                  THEN 'RE: [no subject]'
                             ELSE KYD.[SUBJECT] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [Document],
         CASE WHEN (    ISNULL(DIA.[EMAIL], '') = 'Y'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              WHEN (    ISNULL(DAT.TYPE, '') = 'MSG'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              ELSE 'N' END AS [MainMailFile],
         DAT.[TrackReference],
         RTRIM(ISNULL(DAT.[NAME], '')) AS [NAME],
         RTRIM(ISNULL(DAT.[FILEPATH], '')) AS [FILEPATH],
         RTRIM(ISNULL(DIA.[PROCESSTYPE], '')) AS [PROCESSTYPE],
         RTRIM(ISNULL(DIA.[ACTIONTYPE], '')) AS [ACTIONTYPE],
         DIA.[ActionID]
    FROM [dbo].[ky_WDCaseDocList2](@casecode, @search, @startno, @count, @classes, @noimg, @types) CDLP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = CDLP.[DiaryID]
         INNER JOIN [dbo].[DiaryAttachments] DAT
                    LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
                                 ON DCL.[CLASSCODE] = DAT.[DOCCLASS]
                 ON DAT.[TrackReference] = CDLP.[TrackReference]
         CROSS APPLY (SELECT RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[AddressTo], 1, 255)), '')) As [AddressTo],
                             RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[Subject], 1, 255)), '')) As [Subject]
                        FROM [dbo].[Diary] DIAX
                       WHERE DIAX.[ActionID] = DIA.[ActionID]) KYD
         OUTER APPLY (  SELECT TOP 1
                               MST.[TrackReference] AS [TrackReference],
                               MST.[Type] AS [Type]
                          FROM [dbo].[diaryattachments] MST
                         WHERE MST.[diaryid] = DIA.[ActionID]
                      ORDER BY CASE WHEN MST.TYPE = 'MSG'
                                    THEN 0
                               ELSE 1 END,
                               MST.[TrackReference]) OMS
ORDER BY CDLP.[docid] 



END
GO

/**************************************************************************************
 *
 * ky_WDCaseDocList3
 *
 * Lists case documents. With support for Paging.
 * Supersedes ky_WDCaseDocList2. Added the option to exclude e-mails
 *
 *                               Already added in ky_WDCaseDocList2:
 *                               Includes checks for selected classes,
 *                               the option to exclude images from the result,
 *                               or selected document types
 *
 * Note: parameter format for selected classes or selected types (@classes and @types)
 *       is (e.g.) '*Item1*Item2*Item3*Item4*'
 *       to select all classes or all types, pass in '' or NULL
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDCaseDocList3]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int,
        @classes  varchar(max),
        @noimg    int,
        @noeml    int,
        @types    varchar(max))
RETURNS @CDL TABLE
       ([docid]                 int               IDENTITY(1, 1),
        [CASECODE]              varchar(20),
        [DATE]                  datetime,
        [DIARYID]               int,
        [TrackReference]        int)
AS
BEGIN

  DECLARE @CDL2 TABLE
         ([docid]                 int               IDENTITY(1, 1),
          [CASECODE]              varchar(20),
          [DATE]                  datetime,
          [DIARYID]               int,
          [EMAIL]                 varchar(1),
          [TYPE]                  varchar(10),
          [TrackReference]        int)

  DECLARE @noimgtypes varchar(max)
  
  IF (@noimg = 1)
    SET @noimgtypes = '*GIF*JPG*JPEG*BMP*PNG*TIF*TIFF*'
  ELSE
    SET @noimgtypes = '*'
    
  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

  IF (@search = '%')
    BEGIN
        INSERT
          INTO @CDL2
              ([CASECODE],
               [DATE],
               [DIARYID],
               [EMAIL],
               [TYPE],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DIA.[EMAIL],
               DAT.[TYPE],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
                      AND @noimgtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND (   (@types is NULL)
                           OR (@types LIKE '%*' + DAT.[TYPE] + '*%'))
                      AND (   (@classes is NULL)
                           OR (@classes LIKE '%*' + DAT.[DOCCLASS] + '*%'))
         WHERE DIA.[CASECODE] = @casecode
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END
  ELSE
    BEGIN
        INSERT
          INTO @CDL2
              ([CASECODE],
               [DATE],
               [DIARYID],
               [EMAIL],
               [TYPE],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DIA.[EMAIL],
               DAT.[TYPE],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
                      AND @noimgtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND (   (@types is NULL)
                           OR (@types LIKE '%*' + DAT.[TYPE] + '*%'))
                      AND (   (@classes is NULL)
                           OR (@classes LIKE '%*' + DAT.[DOCCLASS] + '*%'))
         WHERE DIA.[CASECODE] = @casecode
           AND (   DAT.[Document] LIKE @search
                OR DIA.[subject] LIKE @search
                OR DIA.[emailaddress] LIKE @search
                OR Substring(DIA.[AddressTo], 1, 200) LIKE @search)
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END

    IF (@noeml = 1)
      BEGIN
        DELETE CDL2
          FROM @CDL2 CDL2
               OUTER APPLY (  SELECT TOP 1
                                     MST.[TrackReference] AS [TrackReference],
                                     MST.[Type] AS [Type]
                                FROM [dbo].[diaryattachments] MST
                               WHERE MST.[diaryid] = CDL2.[DiaryID]
                            ORDER BY CASE WHEN MST.[TYPE] = 'MSG'
                                               THEN 0
                                          WHEN MST.[TYPE] = 'HTM'
                                               THEN 1
                                          ELSE 2 END,
                                     MST.[TrackReference]) OMS
         WHERE CASE WHEN (    ISNULL(CDL2.[EMAIL], '') = 'Y'
                          AND CDL2.[TrackReference] = OMS.[TrackReference])
                          THEN 'Y'
                    WHEN (    ISNULL(CDL2.[TYPE], '') = 'MSG'
                          AND CDL2.[TrackReference] = OMS.[TrackReference])
                          THEN 'Y'
                    ELSE 'N' END = 'Y'
      END

      INSERT
        INTO @CDL
            ([CASECODE],
             [DATE],
             [DIARYID],
             [TrackReference])
      SELECT CDL2.[CASECODE],
             CDL2.[DATE],
             CDL2.[DIARYID],
             CDL2.[TrackReference]
        FROM @CDL2 CDL2
    ORDER BY CDL2.[docid]
    
    DELETE @CDL
     WHERE [docid] < @startno

    DELETE @CDL
     WHERE [docid] > (@startno + @count - 1)

  RETURN
END

GO

/**************************************************************************************
 *
 * ky_WDCaseDocuments3
 *
 * Lists case documents (expanded list). With support for Paging.
 *
 **************************************************************************************/
 CREATE PROCEDURE
        [dbo].[ky_WDCaseDocuments3]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int,
        @classes  varchar(max),
        @noimg    int,
        @noeml    int,
        @types    varchar(max))
AS
BEGIN
  IF (RTRIM(ISNULL(@classes, '')) = '')
    BEGIN
      set @classes = NULL
    END

  IF (RTRIM(ISNULL(@types, '')) = '')
    BEGIN
      set @types = NULL
    END
        
  SELECT Convert(VARCHAR, DIA.[DATE], 106) AS [DocumentDate],
         DAT.[DOCCLASS] AS [DocumentClass],
         UPPER(RTRIM(ISNULL(DAT.[TYPE], ''))) AS [TYPE],
         RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], '')) AS [DocumentClassDescription],
         RTRIM(ISNULL(DAT.[Source], '')) AS [DocumentSource],
         RTRIM(ISNULL(DIA.[EMAILADDRESS], '')) AS [EmailAddress],
         KYD.[AddressTo] AS [AddressTo],
         KYD.[SUBJECT] AS [SUBJECT],
         RTRIM(ISNULL(DAT.[ENTEREDBY], '')) AS [ENTEREDBY],
         ISNULL(Convert(VARCHAR, DAT.[DateEntered], 106), '') AS [DATEENTERED],
         RTRIM(ISNULL(DAT.[LASTACCESSBY], '')) AS [LASTACCESSBY],
         ISNULL(Convert(VARCHAR, DAT.[LASTACCESSDATE], 106), '') AS [LASTACCESSDATE],
         CASE WHEN ISNULL(DIA.[EMAIL], '') = 'Y'
                   THEN 'Y'
              WHEN (OMS.[TYPE] = 'MSG')
                   THEN 'Y'
              ELSE 'N' END AS [EMAIL],
         RTRIM(ISNULL(DAT.[Document], '')) AS [OriginalDocumentName],
         CASE WHEN (ISNULL(DIA.[EMAIL], '') = 'Y') OR (OMS.[TYPE] = 'MSG')
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [ShortDocument],
         CASE WHEN (    (   (ISNULL(DIA.[EMAIL], '') = 'Y')
                         OR (OMS.[TYPE] = 'MSG'))
                    AND (DAT.TrackReference = OMS.TrackReference))
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END + 
                        ': ' + 
                        CASE UPPER(KYD.[SUBJECT])
                             WHEN ''
                                  THEN '[no subject]'
                             WHEN 'FW:'
                                  THEN 'FW: [no subject]'
                             WHEN 'RE:'
                                  THEN 'RE: [no subject]'
                             ELSE KYD.[SUBJECT] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [Document],
         CASE WHEN (    ISNULL(DIA.[EMAIL], '') = 'Y'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              WHEN (    ISNULL(DAT.TYPE, '') = 'MSG'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              ELSE 'N' END AS [MainMailFile],
         DAT.[TrackReference],
         RTRIM(ISNULL(DAT.[NAME], '')) AS [NAME],
         RTRIM(ISNULL(DAT.[FILEPATH], '')) AS [FILEPATH],
         RTRIM(ISNULL(DIA.[PROCESSTYPE], '')) AS [PROCESSTYPE],
         RTRIM(ISNULL(DIA.[ACTIONTYPE], '')) AS [ACTIONTYPE],
         DIA.[ActionID]
    FROM [dbo].[ky_WDCaseDocList3](@casecode, @search, @startno, @count, @classes, @noimg, @noeml, @types) CDLP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = CDLP.[DiaryID]
         INNER JOIN [dbo].[DiaryAttachments] DAT
                    LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
                                 ON DCL.[CLASSCODE] = DAT.[DOCCLASS]
                 ON DAT.[TrackReference] = CDLP.[TrackReference]
         CROSS APPLY (SELECT RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[AddressTo], 1, 255)), '')) As [AddressTo],
                             RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[Subject], 1, 255)), '')) As [Subject]
                        FROM [dbo].[Diary] DIAX
                       WHERE DIAX.[ActionID] = DIA.[ActionID]) KYD
         OUTER APPLY (  SELECT TOP 1
                               MST.[TrackReference] AS [TrackReference],
                               MST.[Type] AS [Type]
                          FROM [dbo].[diaryattachments] MST
                         WHERE MST.[diaryid] = DIA.[ActionID]
                      ORDER BY CASE WHEN MST.TYPE = 'MSG'
                                         THEN 0
                                    WHEN MST.TYPE = 'HTM'
                                         THEN 1
                                    ELSE 2 END,
                               MST.[TrackReference]) OMS
ORDER BY CDLP.[docid] 



END
GO

/**************************************************************************************
 *
 * ky_WDCaseDocList4
 *
 * Lists case documents. With support for Paging.
 * Supersedes ky_WDCaseDocList3. Added the option to exclude media
 * Supersedes ky_WDCaseDocList2. Added the option to exclude e-mails
 *
 *                               Already added in ky_WDCaseDocList2:
 *                               Includes checks for selected classes,
 *                               the option to exclude images from the result,
 *                               or selected document types
 *
 * Note: parameter format for selected classes or selected types (@classes and @types)
 *       is (e.g.) '*Item1*Item2*Item3*Item4*'
 *       to select all classes or all types, pass in '' or NULL
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDCaseDocList4]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int,
        @classes  varchar(max),
        @noimg    int,
        @noeml    int,
        @nomed    int,
        @types    varchar(max))
RETURNS @CDL TABLE
       ([docid]                 int               IDENTITY(1, 1),
        [CASECODE]              varchar(20),
        [DATE]                  datetime,
        [DIARYID]               int,
        [TrackReference]        int)
AS
BEGIN

  DECLARE @CDL2 TABLE
         ([docid]                 int               IDENTITY(1, 1),
          [CASECODE]              varchar(20),
          [DATE]                  datetime,
          [DIARYID]               int,
          [EMAIL]                 varchar(1),
          [TYPE]                  varchar(10),
          [TrackReference]        int)

  DECLARE @noimgtypes varchar(max)
  DECLARE @nomedtypes varchar(max)
  
  IF (@noimg = 1)
    SET @noimgtypes = '*GIF*JPG*JPEG*BMP*PNG*TIF*TIFF*'
  ELSE
    SET @noimgtypes = '*'

  IF (@nomed = 1)
    SET @nomedtypes = '*WAV*MP3*MP4*WMV*AVI*MOV*3GP*MPG*OGG*'
  ELSE
    SET @nomedtypes = '*'
    
  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

  IF (@search = '%')
    BEGIN
        INSERT
          INTO @CDL2
              ([CASECODE],
               [DATE],
               [DIARYID],
               [EMAIL],
               [TYPE],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DIA.[EMAIL],
               DAT.[TYPE],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
                      AND @noimgtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND @nomedtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND (   (@types is NULL)
                           OR (@types LIKE '%*' + DAT.[TYPE] + '*%'))
                      AND (   (@classes is NULL)
                           OR (@classes LIKE '%*' + DAT.[DOCCLASS] + '*%'))
         WHERE DIA.[CASECODE] = @casecode
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END
  ELSE
    BEGIN
        INSERT
          INTO @CDL2
              ([CASECODE],
               [DATE],
               [DIARYID],
               [EMAIL],
               [TYPE],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DIA.[EMAIL],
               DAT.[TYPE],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
                      AND @noimgtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND @nomedtypes NOT LIKE '%*' + DAT.[TYPE] + '*%'
                      AND (   (@types is NULL)
                           OR (@types LIKE '%*' + DAT.[TYPE] + '*%'))
                      AND (   (@classes is NULL)
                           OR (@classes LIKE '%*' + DAT.[DOCCLASS] + '*%'))
         WHERE DIA.[CASECODE] = @casecode
           AND (   DAT.[Document] LIKE @search
                OR DIA.[subject] LIKE @search
                OR DIA.[emailaddress] LIKE @search
                OR Substring(DIA.[AddressTo], 1, 200) LIKE @search)
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END

    IF (@noeml = 1)
      BEGIN
        DELETE CDL2
          FROM @CDL2 CDL2
               OUTER APPLY (  SELECT TOP 1
                                     MST.[TrackReference] AS [TrackReference],
                                     MST.[Type] AS [Type]
                                FROM [dbo].[diaryattachments] MST
                               WHERE MST.[diaryid] = CDL2.[DiaryID]
                            ORDER BY CASE WHEN MST.[TYPE] = 'MSG'
                                               THEN 0
                                          WHEN MST.[TYPE] = 'HTM'
                                               THEN 1
                                          ELSE 2 END,
                                     MST.[TrackReference]) OMS
         WHERE CASE WHEN (    ISNULL(CDL2.[EMAIL], '') = 'Y'
                          AND CDL2.[TrackReference] = OMS.[TrackReference])
                          THEN 'Y'
                    WHEN (    ISNULL(CDL2.[TYPE], '') = 'MSG'
                          AND CDL2.[TrackReference] = OMS.[TrackReference])
                          THEN 'Y'
                    ELSE 'N' END = 'Y'
      END

      INSERT
        INTO @CDL
            ([CASECODE],
             [DATE],
             [DIARYID],
             [TrackReference])
      SELECT CDL2.[CASECODE],
             CDL2.[DATE],
             CDL2.[DIARYID],
             CDL2.[TrackReference]
        FROM @CDL2 CDL2
    ORDER BY CDL2.[docid]
    
    DELETE @CDL
     WHERE [docid] < @startno

    DELETE @CDL
     WHERE [docid] > (@startno + @count - 1)

  RETURN
END

GO

/**************************************************************************************
 *
 * ky_WDCaseDocuments4
 *
 * Lists case documents (expanded list). With support for Paging.
 *
 **************************************************************************************/
 CREATE PROCEDURE
        [dbo].[ky_WDCaseDocuments4]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int,
        @classes  varchar(max),
        @noimg    int,
        @noeml    int,
        @nomed    int,
        @types    varchar(max))
AS
BEGIN
  IF (RTRIM(ISNULL(@classes, '')) = '')
    BEGIN
      set @classes = NULL
    END

  IF (RTRIM(ISNULL(@types, '')) = '')
    BEGIN
      set @types = NULL
    END
        
  SELECT Convert(VARCHAR, DIA.[DATE], 106) AS [DocumentDate],
         DAT.[DOCCLASS] AS [DocumentClass],
         UPPER(RTRIM(ISNULL(DAT.[TYPE], ''))) AS [TYPE],
         RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], '')) AS [DocumentClassDescription],
         RTRIM(ISNULL(DAT.[Source], '')) AS [DocumentSource],
         RTRIM(ISNULL(DIA.[EMAILADDRESS], '')) AS [EmailAddress],
         KYD.[AddressTo] AS [AddressTo],
         KYD.[SUBJECT] AS [SUBJECT],
         RTRIM(ISNULL(DAT.[ENTEREDBY], '')) AS [ENTEREDBY],
         ISNULL(Convert(VARCHAR, DAT.[DateEntered], 106), '') AS [DATEENTERED],
         RTRIM(ISNULL(DAT.[LASTACCESSBY], '')) AS [LASTACCESSBY],
         ISNULL(Convert(VARCHAR, DAT.[LASTACCESSDATE], 106), '') AS [LASTACCESSDATE],
         CASE WHEN ISNULL(DIA.[EMAIL], '') = 'Y'
                   THEN 'Y'
              WHEN (OMS.[TYPE] = 'MSG')
                   THEN 'Y'
              ELSE 'N' END AS [EMAIL],
         RTRIM(ISNULL(DAT.[Document], '')) AS [OriginalDocumentName],
         CASE WHEN (ISNULL(DIA.[EMAIL], '') = 'Y') OR (OMS.[TYPE] = 'MSG')
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [ShortDocument],
         CASE WHEN (    (   (ISNULL(DIA.[EMAIL], '') = 'Y')
                         OR (OMS.[TYPE] = 'MSG'))
                    AND (DAT.TrackReference = OMS.TrackReference))
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END + 
                        ': ' + 
                        CASE UPPER(KYD.[SUBJECT])
                             WHEN ''
                                  THEN '[no subject]'
                             WHEN 'FW:'
                                  THEN 'FW: [no subject]'
                             WHEN 'RE:'
                                  THEN 'RE: [no subject]'
                             ELSE KYD.[SUBJECT] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [Document],
         CASE WHEN (    ISNULL(DIA.[EMAIL], '') = 'Y'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              WHEN (    ISNULL(DAT.TYPE, '') = 'MSG'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              ELSE 'N' END AS [MainMailFile],
         DAT.[TrackReference],
         RTRIM(ISNULL(DAT.[NAME], '')) AS [NAME],
         RTRIM(ISNULL(DAT.[FILEPATH], '')) AS [FILEPATH],
         RTRIM(ISNULL(DIA.[PROCESSTYPE], '')) AS [PROCESSTYPE],
         RTRIM(ISNULL(DIA.[ACTIONTYPE], '')) AS [ACTIONTYPE],
         DIA.[ActionID]
    FROM [dbo].[ky_WDCaseDocList4](@casecode, @search, @startno, @count, @classes, @noimg, @noeml, @nomed, @types) CDLP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = CDLP.[DiaryID]
         INNER JOIN [dbo].[DiaryAttachments] DAT
                    LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
                                 ON DCL.[CLASSCODE] = DAT.[DOCCLASS]
                 ON DAT.[TrackReference] = CDLP.[TrackReference]
         CROSS APPLY (SELECT RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[AddressTo], 1, 255)), '')) As [AddressTo],
                             RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[Subject], 1, 255)), '')) As [Subject]
                        FROM [dbo].[Diary] DIAX
                       WHERE DIAX.[ActionID] = DIA.[ActionID]) KYD
         OUTER APPLY (  SELECT TOP 1
                               MST.[TrackReference] AS [TrackReference],
                               MST.[Type] AS [Type]
                          FROM [dbo].[diaryattachments] MST
                         WHERE MST.[diaryid] = DIA.[ActionID]
                      ORDER BY CASE WHEN MST.TYPE = 'MSG'
                                         THEN 0
                                    WHEN MST.TYPE = 'HTM'
                                         THEN 1
                                    ELSE 2 END,
                               MST.[TrackReference]) OMS
ORDER BY CDLP.[docid] 



END
GO



/**************************************************************************************
 *
 * ky_WDDiaryDocuments
 *
 * Lists Diary documents (Diary Attachments) (expanded list). With support for Paging.
 *
 **************************************************************************************/
 CREATE PROCEDURE
        [dbo].[ky_WDDiaryDocuments]
       (@actionID varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int)
AS
BEGIN
  SELECT Convert(VARCHAR, DIA.[DATE], 106) AS [DocumentDate],
         DAT.[DOCCLASS] AS [DocumentClass],
         UPPER(RTRIM(ISNULL(DAT.[TYPE], ''))) AS [TYPE],
         RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], '')) AS [DocumentClassDescription],
         RTRIM(ISNULL(DAT.[Source], '')) AS [DocumentSource],
         RTRIM(ISNULL(DIA.[EMAILADDRESS], '')) AS [EmailAddress],
         KYD.[AddressTo] AS [AddressTo],
         KYD.[SUBJECT] AS [SUBJECT],
         RTRIM(ISNULL(DAT.[ENTEREDBY], '')) AS [ENTEREDBY],
         ISNULL(Convert(VARCHAR, DAT.[DateEntered], 106), '') AS [DATEENTERED],
         RTRIM(ISNULL(DAT.[LASTACCESSBY], '')) AS [LASTACCESSBY],
         ISNULL(Convert(VARCHAR, DAT.[LASTACCESSDATE], 106), '') AS [LASTACCESSDATE],
         CASE WHEN ISNULL(DIA.[EMAIL], '') = 'Y'
                   THEN 'Y'
              WHEN (OMS.[TYPE] = 'MSG')
                   THEN 'Y'
              ELSE 'N' END AS [EMAIL],
         RTRIM(ISNULL(DAT.[Document], '')) AS [OriginalDocumentName],
         CASE WHEN (ISNULL(DIA.[EMAIL], '') = 'Y') OR (OMS.[TYPE] = 'MSG')
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [ShortDocument],
         CASE WHEN (    (   (ISNULL(DIA.[EMAIL], '') = 'Y')
                         OR (OMS.[TYPE] = 'MSG'))
                    AND (DAT.TrackReference = OMS.TrackReference))
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END + 
                        ': ' + 
                        CASE UPPER(KYD.[SUBJECT])
                             WHEN ''
                                  THEN '[no subject]'
                             WHEN 'FW:'
                                  THEN 'FW: [no subject]'
                             WHEN 'RE:'
                                  THEN 'RE: [no subject]'
                             ELSE KYD.[SUBJECT] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [Document],
         CASE WHEN (    ISNULL(DIA.[EMAIL], '') = 'Y'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              WHEN (    ISNULL(DAT.TYPE, '') = 'MSG'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              ELSE 'N' END AS [MainMailFile],
         DAT.[TrackReference],
         RTRIM(ISNULL(DAT.[NAME], '')) AS [NAME],
         RTRIM(ISNULL(DAT.[FILEPATH], '')) AS [FILEPATH],
         RTRIM(ISNULL(DIA.[PROCESSTYPE], '')) AS [PROCESSTYPE],
         RTRIM(ISNULL(DIA.[ACTIONTYPE], '')) AS [ACTIONTYPE],
         DIA.[ActionID]
    FROM [dbo].[ky_WDDiaryDocList](@actionID, @search, @startno, @count) CDLP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = CDLP.[DiaryID]
         INNER JOIN [dbo].[DiaryAttachments] DAT
                    LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
                                 ON DCL.[CLASSCODE] = DAT.[DOCCLASS]
                 ON DAT.[TrackReference] = CDLP.[TrackReference]
         CROSS APPLY (SELECT RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[AddressTo], 1, 255)), '')) As [AddressTo],
                             RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[Subject], 1, 255)), '')) As [Subject]
                        FROM [dbo].[Diary] DIAX
                       WHERE DIAX.[ActionID] = DIA.[ActionID]) KYD
         OUTER APPLY (  SELECT TOP 1
                               MST.[TrackReference] AS [TrackReference],
                               MST.[Type] AS [Type]
                          FROM [dbo].[diaryattachments] MST
                         WHERE MST.[diaryid] = DIA.[ActionID]
                      ORDER BY CASE WHEN MST.TYPE = 'MSG'
                                    THEN 0
                               ELSE 1 END,
                               MST.[TrackReference]) OMS
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDocList
 *
 * Lists case documents. With support for Paging.
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDCaseDocList]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int)
RETURNS @CDL TABLE
       ([docid]                 int               IDENTITY(1, 1),
        [CASECODE]              varchar(20),
        [DATE]                  datetime,
        [DIARYID]               int,
        [TrackReference]        int)
AS
BEGIN

  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

  IF (@search = '%')
    BEGIN
        INSERT
          INTO @CDL
              ([CASECODE],
               [DATE],
               [DIARYID],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
         WHERE DIA.[CASECODE] = @casecode
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END
  ELSE
    BEGIN
        INSERT
          INTO @CDL
              ([CASECODE],
               [DATE],
               [DIARYID],
               [TRACKREFERENCE])
        SELECT DIA.[CASECODE],
               IsNull(DIA.[DATE], convert(datetime, '18991230')) AS [DATE],
               DIA.[ActionID],
               DAT.[TrackReference]
          FROM [dbo].[Diary] DIA
               INNER JOIN [dbo].[DiaryAttachments] DAT
                       ON DAT.[DiaryID] = DIA.[ActionID]
         WHERE DIA.[CASECODE] = @casecode
           AND (   DAT.[Document] LIKE @search
                OR DIA.[subject] LIKE @search
                OR DIA.[emailaddress] LIKE @search
                OR Substring(DIA.[AddressTo], 1, 200) LIKE @search)
      ORDER BY DIA.[DATE] DESC,
               DAT.[TrackReference] DESC
    END

    DELETE @CDL
     WHERE [docid] < @startno

    DELETE @CDL
     WHERE [docid] > (@startno + @count - 1)

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDCaseDocuments
 *
 * Lists case documents (expanded list). With support for Paging.
 *
 **************************************************************************************/
 CREATE PROCEDURE
        [dbo].[ky_WDCaseDocuments]
       (@casecode varchar(20),
        @search   varchar(50),
        @startno  int,
        @count    int)
AS
BEGIN
  SELECT Convert(VARCHAR, DIA.[DATE], 106) AS [DocumentDate],
         DAT.[DOCCLASS] AS [DocumentClass],
         UPPER(RTRIM(ISNULL(DAT.[TYPE], ''))) AS [TYPE],
         RTRIM(ISNULL(DCL.[CLASSDESCRIPTION], '')) AS [DocumentClassDescription],
         RTRIM(ISNULL(DAT.[Source], '')) AS [DocumentSource],
         RTRIM(ISNULL(DIA.[EMAILADDRESS], '')) AS [EmailAddress],
         KYD.[AddressTo] AS [AddressTo],
         KYD.[SUBJECT] AS [SUBJECT],
         RTRIM(ISNULL(DAT.[ENTEREDBY], '')) AS [ENTEREDBY],
         ISNULL(Convert(VARCHAR, DAT.[DateEntered], 106), '') AS [DATEENTERED],
         RTRIM(ISNULL(DAT.[LASTACCESSBY], '')) AS [LASTACCESSBY],
         ISNULL(Convert(VARCHAR, DAT.[LASTACCESSDATE], 106), '') AS [LASTACCESSDATE],
         CASE WHEN ISNULL(DIA.[EMAIL], '') = 'Y'
                   THEN 'Y'
              WHEN (OMS.[TYPE] = 'MSG')
                   THEN 'Y'
              ELSE 'N' END AS [EMAIL],
         RTRIM(ISNULL(DAT.[Document], '')) AS [OriginalDocumentName],
         CASE WHEN (ISNULL(DIA.[EMAIL], '') = 'Y') OR (OMS.[TYPE] = 'MSG')
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [ShortDocument],
         CASE WHEN (    (   (ISNULL(DIA.[EMAIL], '') = 'Y')
                         OR (OMS.[TYPE] = 'MSG'))
                    AND (DAT.TrackReference = OMS.TrackReference))
                   THEN 'E-mail from ' + 
                        CASE WHEN RTRIM(ISNULL([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS]), '')) = ''
                                  THEN '[undisclosed]'
                             ELSE RTRIM([dbo].[ky_GetNameFromEmailAddress](DIA.[EMAILADDRESS])) END + 
                        ' to ' + 
                        CASE WHEN KYD.[AddressTo] = ''
                                  THEN '[undisclosed]'
                             ELSE KYD.[AddressTo] END + 
                        ': ' + 
                        CASE UPPER(KYD.[SUBJECT])
                             WHEN ''
                                  THEN '[no subject]'
                             WHEN 'FW:'
                                  THEN 'FW: [no subject]'
                             WHEN 'RE:'
                                  THEN 'RE: [no subject]'
                             ELSE KYD.[SUBJECT] END
              ELSE RTRIM(ISNULL(DAT.[Document],'')) END AS [Document],
         CASE WHEN (    ISNULL(DIA.[EMAIL], '') = 'Y'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              WHEN (    ISNULL(DAT.TYPE, '') = 'MSG'
                    AND DAT.[TrackReference] = OMS.[TrackReference])
                   THEN 'Y'
              ELSE 'N' END AS [MainMailFile],
         DAT.[TrackReference],
         RTRIM(ISNULL(DAT.[NAME], '')) AS [NAME],
         RTRIM(ISNULL(DAT.[FILEPATH], '')) AS [FILEPATH],
         RTRIM(ISNULL(DIA.[PROCESSTYPE], '')) AS [PROCESSTYPE],
         RTRIM(ISNULL(DIA.[ACTIONTYPE], '')) AS [ACTIONTYPE],
         DIA.[ActionID]
    FROM [dbo].[ky_WDCaseDocList](@casecode, @search, @startno, @count) CDLP
         INNER JOIN [dbo].[Diary] DIA
                 ON DIA.[ActionID] = CDLP.[DiaryID]
         INNER JOIN [dbo].[DiaryAttachments] DAT
                    LEFT OUTER JOIN [dbo].[DocumentClasses] DCL
                                 ON DCL.[CLASSCODE] = DAT.[DOCCLASS]
                 ON DAT.[TrackReference] = CDLP.[TrackReference]
         CROSS APPLY (SELECT RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[AddressTo], 1, 255)), '')) As [AddressTo],
                             RTRIM(ISNULL(CONVERT(VARCHAR(255), SUBSTRING(DIAX.[Subject], 1, 255)), '')) As [Subject]
                        FROM [dbo].[Diary] DIAX
                       WHERE DIAX.[ActionID] = DIA.[ActionID]) KYD
         OUTER APPLY (  SELECT TOP 1
                               MST.[TrackReference] AS [TrackReference],
                               MST.[Type] AS [Type]
                          FROM [dbo].[diaryattachments] MST
                         WHERE MST.[diaryid] = DIA.[ActionID]
                      ORDER BY CASE WHEN MST.TYPE = 'MSG'
                                    THEN 0
                               ELSE 1 END,
                               MST.[TrackReference]) OMS
ORDER BY CDLP.[docid] 

END
GO

/**************************************************************************************
 *
 * ky_WDMatterList
 *
 * Lists cases. With support for Paging.
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDMatterList]
       (@fecode   varchar(10),
        @startno  int,
        @count    int,
        @search   varchar(50),
        @order    int)
RETURNS @ML TABLE
       ([matid]                 int               IDENTITY(1, 1),
        [CaseCode]              varchar(20),
        [FECode]                varchar(10),
        [HandlerName]           varchar(100),
        [ContactName]           varchar(100),
        [Description]           varchar(200),
        [Colour]                varchar(10),
        [ColourDescription]     varchar(50),
        [User1]                 varchar(50),
        [User2]                 varchar(50),
        [User3]                 varchar(50),
        [LastAccessed]          varchar(21),
        [TDBTime]               varchar(5),
        [TDBStopwatchRunning]   int,
        [TDBRecordID]           int)
AS
BEGIN

  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

/*
   @order = display order
            1 = by Code
            2 = by Most Recent First
*/

  /* This avoids unnecessary nesting as we can subsequently
     break out of each IF statement.  
     SQL Server doesn't have a "switch" construct. */
  WHILE (1 = 1)
    BEGIN
      IF (@order = 3)
        BEGIN
          INSERT
            INTO @ML
                (CASECODE)
          SELECT RTRIM(IsNull(MAT.[CODE], '')) AS [CASECODE]
            FROM [dbo].[MATTERS] MAT
                 INNER JOIN [dbo].[contacts] CON
                         ON CON.[Code] = MAT.[ClientCode]
                 LEFT OUTER JOIN (  SELECT RL.[DateField],
                                           RL.[MATTER]
                                      FROM [dbo].[RecentMatterList] RL
                                     WHERE RL.[FEE] = @fecode) RML
                              ON RML.[MATTER] = MAT.[CODE]
           WHERE (   MAT.[Description] LIKE @search
                  OR CON.[NAME] LIKE @search)
          ORDER BY IsNull(RML.[DateField], convert(datetime, 0)) desc,
                   MAT.[CODE] ASC

          BREAK
        END

      INSERT
        INTO @ML
            (CASECODE)
      SELECT RTRIM(IsNull(MAT.[CODE], '')) AS [CASECODE]
        FROM [dbo].[MATTERS] MAT
             INNER JOIN [dbo].[contacts] CON
                     ON CON.[Code] = MAT.[ClientCode]
       WHERE (   MAT.[Description] LIKE @search
              OR CON.[NAME] LIKE @search)

      BREAK
    END

    DELETE @ML
     WHERE [matid] < @startno

    DELETE @ML
     WHERE [matid] > (@startno + @count - 1)

    UPDATE ML
       SET ML.[DESCRIPTION] = RTrim(IsNull(MAT.[DESCRIPTION], '')),
           ML.[ContactName] = RTrim(IsNull(CON.[Name], '')),
           ML.[FECode] = RTrim(IsNull(MAT.[FECode], '')),
           ML.[HandlerName] = RTrim(IsNull(HAN.[Name], '')),
           ML.[Colour] = RTrim(IsNull(MAT.[FileColour], '')),
           ML.[ColourDescription] = RTrim(IsNull(COL.[COLOURDESC], '')),
           ML.[User1] = RTRIM(ISNULL(MAT.[User1], '')),
           ML.[User2] = RTRIM(ISNULL(MAT.[User2], '')),
           ML.[User3] = RTRIM(ISNULL(MAT.[User3], '')),
           ML.[LastAccessed] = CASE WHEN IsNull(RML.[DateField], convert(datetime, 0)) = convert(datetime, 0)
                                         THEN ''
                                    ELSE convert(varchar, RML.[DateField], 106) + '     ' + convert(varchar(5), RML.[DateField], 108) END 
      FROM @ML ML
           INNER JOIN [dbo].[matters] MAT
                      LEFT OUTER JOIN [dbo].[FileColours] COL
                                   ON COL.[COLOURCODE] = MAT.[FileColour]
                      LEFT OUTER JOIN [dbo].[RecentMatterList] RML
                                   ON RML.[FEE] = @FECode
                                  AND RML.[MATTER] = MAT.[CODE]
                      INNER JOIN [dbo].[contacts] CON
                              ON CON.[Code] = MAT.[ClientCode]
                      LEFT OUTER JOIN [dbo].[handlers] HAN
                                   ON HAN.[Code] = MAT.[FECode]
                   ON MAT.[CODE] = ML.[CASECODE]

    UPDATE ML
       SET ML.[TDBTime] = CASE WHEN ABS(TDB.[TIME]) >= 6000
                                    THEN '++++++'
                               ELSE CASE WHEN ISNULL(TDB.[TIME], 0) < 0
                                              THEN '-'
                                         ELSE   right('00' + convert(varchar(2), floor(ABS(IsNull(TDB.[TIME], 0)) / 60)), 2) 
                                              + ':' 
                                              + right('00' + convert(varchar(2), ABS(IsNull(TDB.[TIME], 0)) - (60 * floor(ABS(IsNull(TDB.[TIME], 0)) / 60))), 2) END END,
           ML.[TDBStopwatchRunning] = CASE WHEN TDB.[StopwatchStartTime] IS null
                                                THEN 0
                                           ELSE 1 END,
           ML.[TDBRecordID] = CASE WHEN TDB.[RECORDID] IS null
                                        THEN 0
                                   ELSE TDB.[RECORDID] END
      FROM @ML ML
           LEFT OUTER JOIN [dbo].[TimeDayBook] TDB
                        ON TDB.[MATTER] = ML.[CaseCode]
                       AND TDB.[FEEEARN] = @fecode   

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDMatterList2
 *
 * Lists cases. Exclude cases that the Handler is not authorised to see.
 * With support for Paging.
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDMatterList2]
       (@fecode   varchar(10),
        @startno  int,
        @count    int,
        @search   varchar(50),
        @order    int)
RETURNS @ML TABLE
       ([matid]                 int               IDENTITY(1, 1),
        [CaseCode]              varchar(20),
        [FECode]                varchar(10),
        [HandlerName]           varchar(100),
        [ContactName]           varchar(100),
        [Description]           varchar(200),
        [Colour]                varchar(10),
        [ColourDescription]     varchar(50),
        [User1]                 varchar(50),
        [User2]                 varchar(50),
        [User3]                 varchar(50),
        [LastAccessed]          varchar(21),
        [TDBTime]               varchar(5),
        [TDBStopwatchRunning]   int,
        [TDBRecordID]           int)
AS
BEGIN

  DECLARE @JPER int

  SELECT @JPER = CASE WHEN IsNull(JP.[JPER_Permissions], 0) = 0
                           THEN 0
                      ELSE JP.[JPER_Permissions] END
    FROM [dbo].[HandlerOPE] OPE
         LEFT OUTER JOIN [dbo].[JPermissions] JP
                      ON JP.[JPER_UserNumber] = OPE.[OPE_NUMBER] 
   WHERE OPE.[Handler] = @fecode
  
  SET @JPER = ISNULL(@JPER, 0)
  
  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

/*
   @order = display order
            1 = by Code
            2 = by Most Recent First
*/

  /* This avoids unnecessary nesting as we can subsequently
     break out of each IF statement.  
     SQL Server doesn't have a "switch" construct. */
  WHILE (1 = 1)
    BEGIN
      IF (@order = 3)
        BEGIN
            INSERT
              INTO @ML
                  (CASECODE)
            SELECT RTRIM(IsNull(MAT.[CODE], '')) AS [CASECODE]
              FROM [dbo].[MATTERS] MAT
                   INNER JOIN [dbo].[contacts] CON
                           ON CON.[Code] = MAT.[ClientCode]
                   INNER JOIN (  SELECT RL.[DateField],
                                        RL.[MATTER]
                                   FROM [dbo].[RecentMatterList] RL
                                  WHERE RL.[FEE] = @fecode) RML
                           ON RML.[MATTER] = MAT.[CODE]
             WHERE (   MAT.[Description] LIKE @search
                    OR CON.[NAME] LIKE @search)
               AND (   (IsNull(MAT.[Permissions], 0) = 0)
                    OR ((IsNull(MAT.[Permissions], 0) & @JPER) <> 0))
          ORDER BY IsNull(RML.[DateField], convert(datetime, 0)) desc,
                   MAT.[CODE] ASC

            INSERT
              INTO @ML
                  (CASECODE)
            SELECT TOP (@startno + @count)
                   RTRIM(IsNull(MAT.[CODE], '')) AS [CASECODE]
              FROM [dbo].[MATTERS] MAT
                   INNER JOIN [dbo].[contacts] CON
                           ON CON.[Code] = MAT.[ClientCode]
                   LEFT OUTER JOIN (  SELECT RL.[DateField],
                                             RL.[MATTER]
                                        FROM [dbo].[RecentMatterList] RL
                                       WHERE RL.[FEE] = @fecode) RML
                                ON RML.[MATTER] = MAT.[CODE]
             WHERE (   MAT.[Description] LIKE @search
                    OR CON.[NAME] LIKE @search)
               AND (   (IsNull(MAT.[Permissions], 0) = 0)
                    OR ((IsNull(MAT.[Permissions], 0) & @JPER) <> 0))
               AND RML.[MATTER] IS NULL
          ORDER BY MAT.[CODE] ASC

          BREAK
        END

      IF (@order = 1)
        BEGIN
            INSERT
              INTO @ML
                  (CASECODE)
            SELECT TOP (@startno + @count)
                   RTRIM(IsNull(MAT.[CODE], '')) AS [CASECODE]
              FROM [dbo].[MATTERS] MAT
                   INNER JOIN [dbo].[contacts] CON
                           ON CON.[Code] = MAT.[ClientCode]
             WHERE (   MAT.[Description] LIKE @search
                    OR CON.[NAME] LIKE @search)
               AND (   (IsNull(MAT.[Permissions], 0) = 0)
                    OR ((IsNull(MAT.[Permissions], 0) & @JPER) <> 0))
          ORDER BY MAT.[CODE] ASC

          BREAK

        END


      IF (@order = 2)
        BEGIN
            INSERT
              INTO @ML
                  (CASECODE)
            SELECT TOP (@startno + @count)
                   RTRIM(IsNull(MAT.[CODE], '')) AS [CASECODE]
              FROM [dbo].[MATTERS] MAT
                   INNER JOIN [dbo].[contacts] CON
                           ON CON.[Code] = MAT.[ClientCode]
             WHERE (   MAT.[Description] LIKE @search
                    OR CON.[NAME] LIKE @search)
               AND (   (IsNull(MAT.[Permissions], 0) = 0)
                    OR ((IsNull(MAT.[Permissions], 0) & @JPER) <> 0))
          ORDER BY MAT.[Started] DESC

          BREAK

        END
    END

    DELETE @ML
     WHERE [matid] < @startno

    DELETE @ML
     WHERE [matid] > (@startno + @count - 1)

    UPDATE ML
       SET ML.[DESCRIPTION] = RTrim(IsNull(MAT.[DESCRIPTION], '')),
           ML.[ContactName] = RTrim(IsNull(CON.[Name], '')),
           ML.[FECode] = RTrim(IsNull(MAT.[FECode], '')),
           ML.[HandlerName] = RTrim(IsNull(HAN.[Name], '')),
           ML.[Colour] = RTrim(IsNull(MAT.[FileColour], '')),
           ML.[ColourDescription] = RTrim(IsNull(COL.[COLOURDESC], '')),
           ML.[User1] = RTRIM(ISNULL(MAT.[User1], '')),
           ML.[User2] = RTRIM(ISNULL(MAT.[User2], '')),
           ML.[User3] = RTRIM(ISNULL(MAT.[User3], '')),
           ML.[LastAccessed] = CASE WHEN IsNull(RML.[DateField], convert(datetime, 0)) = convert(datetime, 0)
                                         THEN ''
                                    ELSE convert(varchar, RML.[DateField], 106) + '     ' + convert(varchar(5), RML.[DateField], 108) END 
      FROM @ML ML
           INNER JOIN [dbo].[matters] MAT
                      LEFT OUTER JOIN [dbo].[FileColours] COL
                                   ON COL.[COLOURCODE] = MAT.[FileColour]
                      LEFT OUTER JOIN [dbo].[RecentMatterList] RML
                                   ON RML.[FEE] = @FECode
                                  AND RML.[MATTER] = MAT.[CODE]
                      INNER JOIN [dbo].[contacts] CON
                              ON CON.[Code] = MAT.[ClientCode]
                      LEFT OUTER JOIN [dbo].[handlers] HAN
                                   ON HAN.[Code] = MAT.[FECode]
                   ON MAT.[CODE] = ML.[CASECODE]

    UPDATE ML
       SET ML.[TDBTime] = right('00' + convert(varchar(2), floor(TDB.[TIME] / 60)), 2) 
                        + ':' 
                        + right('00' + convert(varchar(2), TDB.[TIME] - (60 * floor(TDB.[TIME] / 60))), 2),
           ML.[TDBStopwatchRunning] = CASE WHEN TDB.[StopwatchStartTime] IS null
                                                THEN 0
                                           ELSE 1 END,
           ML.[TDBRecordID] = CASE WHEN TDB.[RECORDID] IS null
                                        THEN 0
                                   ELSE TDB.[RECORDID] END
      FROM @ML ML
           LEFT OUTER JOIN [dbo].[TimeDayBook] TDB
                        ON TDB.[MATTER] = ML.[CaseCode]
                       AND TDB.[FEEEARN] = @fecode      

  RETURN
END

GO

/**************************************************************************************
 *
 * ky_WDMatterListCount
 *
 * Counts the total number of matters satisfying the selection criteria
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDMatterListCount]
      (@search   varchar(50))
AS
BEGIN
  SET @search = '%' + RTrim(IsNull(@Search, '')) + '%'
  SET @search = Replace(@search, '%%', '%')

  SELECT COUNT(1) AS [TOTAL]
    FROM [dbo].[MATTERS] MAT
         INNER JOIN [dbo].[contacts] CON
                 ON CON.[Code] = MAT.[ClientCode]
   WHERE (   MAT.[Description] LIKE @search
          OR CON.[NAME] LIKE @search)

END
GO

/**************************************************************************************
 *
 * ky_WDTaskListCountByHighlight
 *
 * Returns the number of highlighted items in the Task List to be displayed in 
 * WinDev/WebDev versions of the software filtered by an Action Type
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskListCountByHighlight]
      (@Handler           varchar(10),
       @ActionType        varchar(1),
       @Highlighted       varchar(1),
       @Priority          varchar(1),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @Search            varchar(100))
AS
BEGIN
DECLARE @startdate datetime
DECLARE @enddate   datetime

SET @handler = RTrim(IsNull(@handler, ''))
SET @Team = RTRIM(IsNull(@team, ''))
SET @ActionType = RTrim(IsNull(@ActionType, ''))
SET @Highlighted = RTrim(IsNull(@Highlighted, ''))
SET @Priority = RTrim(IsNull(@Priority, ''))
SET @startdateT = IsNull(@startdateT, '')
SET @enddateT = IsNull(@enddateT, '')
SET @outstanding = isnull(@outstanding, 1)

IF (IsNull(@startdateT, '') = '')
  BEGIN
    SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
  END
ELSE
  BEGIN
    IF (isdate(@startdateT) = 1)
      BEGIN
        set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
      END
    ELSE
      BEGIN
        SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
      END
  END

IF (IsNull(@enddateT, '') = '')
  BEGIN
    SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
  END
ELSE
  BEGIN
    IF (isdate(@enddateT) = 1)
      BEGIN
        set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
      END
    ELSE
      BEGIN
        SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
      END
  END

IF (@outstanding = 0)
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
      END
    ELSE IF (@handler = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
      END
    ELSE IF (@team = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[HANDLER] = @handler
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
      END
    ELSE
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Handler] = @handler
           AND DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
        END
  END
ELSE
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
      END
    ELSE IF (@handler = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
      END
    ELSE IF (@team = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[handler] = @handler
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
      END
    ELSE
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                    THEN 'Y'
                                                               ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                      AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                     THEN DIA.[PRIORITY] 
                                                ELSE @Priority  end
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Handler] = @handler
           AND DEL.[TEAM] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = CASE WHEN RTRIM(IsNull(@ActionType, '')) = '' 
                                            THEN DEL.[ActionType]
                                       ELSE @ActionType END
        END
  END
END
GO

/**************************************************************************************
 *
 * ky_WDTaskListCountByActionType
 *
 * Returns the number of items in the Task List to be displayed in 
 * WinDev/WebDev versions of the software filtered by an Action Type
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskListCountByActionType]
      (@Handler           varchar(10),
       @ActionType        varchar(1),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @Search            varchar(100))
AS
BEGIN
DECLARE @startdate datetime
DECLARE @enddate   datetime

SET @handler = RTrim(IsNull(@handler, ''))
SET @Team = RTRIM(IsNull(@team, ''))
SET @ActionType = RTrim(IsNull(@ActionType, ''))
SET @startdateT = IsNull(@startdateT, '')
SET @enddateT = IsNull(@enddateT, '')
SET @outstanding = isnull(@outstanding, 1)

IF (IsNull(@startdateT, '') = '')
  BEGIN
    SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
  END
ELSE
  BEGIN
    IF (isdate(@startdateT) = 1)
      BEGIN
        set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
      END
    ELSE
      BEGIN
        SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
      END
  END

IF (IsNull(@enddateT, '') = '')
  BEGIN
    SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
  END
ELSE
  BEGIN
    IF (isdate(@enddateT) = 1)
      BEGIN
        set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
      END
    ELSE
      BEGIN
        SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
      END
  END

IF (@outstanding = 0)
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = @ActionType
      END
    ELSE IF (@handler = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = @ActionType
      END
    ELSE IF (@team = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[handler] = @handler
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = @ActionType
      END
    ELSE
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Handler] = @handler
           AND DEL.[team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[ActionType] = @ActionType
        END
  END
ELSE
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = @ActionType
      END
    ELSE IF (@handler = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = @ActionType
      END
    ELSE IF (@team = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[handler] = @handler
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = @ActionType
      END
    ELSE
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[subject]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Handler] = @handler
           AND DEL.[team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
           AND DEL.[ActionType] = @ActionType
        END
  END
END
GO

/**************************************************************************************
 *
 * ky_WDTaskListCount
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskListCount]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @Search            varchar(100))
AS
BEGIN
DECLARE @startdate datetime
DECLARE @enddate   datetime

SET @handler = RTrim(IsNull(@handler, ''))
SET @Team = RTRIM(IsNull(@team, ''))
SET @startdateT = IsNull(@startdateT, '')
SET @enddateT = IsNull(@enddateT, '')
SET @outstanding = isnull(@outstanding, 1)

IF (IsNull(@startdateT, '') = '')
  BEGIN
    SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
  END
ELSE
  BEGIN
    IF (isdate(@startdateT) = 1)
      BEGIN
        set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
      END
    ELSE
      BEGIN
        SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
      END
  END

IF (IsNull(@enddateT, '') = '')
  BEGIN
    SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
  END
ELSE
  BEGIN
    IF (isdate(@enddateT) = 1)
      BEGIN
        set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
      END
    ELSE
      BEGIN
        SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
      END
  END

IF (@outstanding = 0)
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
      END
    ELSE IF (@handler = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
      END
    ELSE IF (@team = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[handler] = @handler
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
      END
    ELSE
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Handler] = @handler
           AND DEL.[team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
        END
  END
ELSE
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
      END
    ELSE IF (@handler = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
      END
    ELSE IF (@team = '')
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[handler] = @handler
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
      END
    ELSE
      BEGIN
        SELECT COUNT(1) AS TOTAL
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                          INNER JOIN [dbo].[matters] MS
                                     INNER JOIN [dbo].[contacts] CTS
                                             ON CTS.[CODE] = MS.[ClientCode]
                                  ON MS.[Code] = DIA.[CaseCode]
                       ON DIA.[ActionID] = DEL.[ActionID]
                      AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                           OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                           OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                           OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                           OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
         WHERE DEL.[Handler] = @handler
           AND DEL.[team] = @team
           AND DEL.[DATE] >= @startdate
           AND DEL.[DATE] < @enddate
           AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
           AND DEL.[Status] = 0
        END
  END
END
GO

/**************************************************************************************
 *
 * ky_WDTaskListSet
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDTaskListSet]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @startno           int,
       @count             int,
       @Search            varchar(100))
RETURNS @TL TABLE
       ([taskid]              int               IDENTITY(1, 1),
        [ActionID]            int,
        [AssignNo]            int)
AS
BEGIN
DECLARE @startdate datetime
DECLARE @enddate   datetime

SET @handler = RTrim(IsNull(@handler, ''))
SET @Team = RTRIM(IsNull(@team, ''))
SET @startdateT = IsNull(@startdateT, '')
SET @enddateT = IsNull(@enddateT, '')
SET @outstanding = isnull(@outstanding, 1)

IF (IsNull(@startdateT, '') = '')
  BEGIN
    SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
  END
ELSE
  BEGIN
    IF (isdate(@startdateT) = 1)
      BEGIN
        set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
      END
    ELSE
      BEGIN
        SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
      END
  END

IF (IsNull(@enddateT, '') = '')
  BEGIN
    SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
  END
ELSE
  BEGIN
    IF (isdate(@enddateT) = 1)
      BEGIN
        set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
      END
    ELSE
      BEGIN
        SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
      END
  END

IF (@outstanding = 0)
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@handler = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@team = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[handler] = @handler
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
        END
  END
ELSE
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@handler = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@team = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
        END
  END

  DELETE @TL
   WHERE [taskid] < @startno

  DELETE @TL
   WHERE [taskid] > (@startno + @count - 1)

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDTaskListByHighlightSet
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDTaskListByHighlightSet]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @startno           int,
       @count             int,
       @ActionType        varchar(1),
       @Highlighted       varchar(1),
       @Priority          varchar(1),
       @Search            varchar(100))
RETURNS @TL TABLE
       ([taskid]              int               IDENTITY(1, 1),
        [ActionID]            int,
        [AssignNo]            int)
AS
BEGIN
DECLARE @startdate datetime
DECLARE @enddate   datetime

SET @Highlighted = RTrim(IsNull(@Highlighted, ''))
SET @Priority = RTrim(IsNull(@Priority, ''))

SET @handler = RTrim(IsNull(@handler, ''))
SET @Team = RTRIM(IsNull(@team, ''))
SET @startdateT = IsNull(@startdateT, '')
SET @enddateT = IsNull(@enddateT, '')
SET @outstanding = isnull(@outstanding, 1)

IF (IsNull(@startdateT, '') = '')
  BEGIN
    SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
  END
ELSE
  BEGIN
    IF (isdate(@startdateT) = 1)
      BEGIN
        set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
      END
    ELSE
      BEGIN
        SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
      END
  END

IF (IsNull(@enddateT, '') = '')
  BEGIN
    SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
  END
ELSE
  BEGIN
    IF (isdate(@enddateT) = 1)
      BEGIN
        set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
      END
    ELSE
      BEGIN
        SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
      END
  END

IF (@outstanding = 0)
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD 
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@handler = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@team = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[handler] = @handler
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[TEAM] = @Team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
        END
  END
ELSE
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@handler = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@team = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @Handler
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND IsNull(DIA.[HIGHLIGHTED], '') = CASE WHEN @Highlighted = 'Y'
                                                                                THEN 'Y'
                                                                           ELSE IsNull(DIA.[HIGHLIGHTED], '') end 
                                  AND DIA.[PRIORITY] = CASE WHEN @Priority = ''
                                                                 THEN DIA.[PRIORITY] 
                                                            ELSE @Priority  end
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[TEAM] = @Team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = CASE WHEN RTRIM(ISNULL(@ActionType, '')) = ''
                                                        THEN DEL.[ActionType]
                                                   ELSE @ActionType END) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
        END
  END

  DELETE @TL
   WHERE [taskid] < @startno

  DELETE @TL
   WHERE [taskid] > (@startno + @count - 1)

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDTaskListByActionTypeSet
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDTaskListByActionTypeSet]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @startno           int,
       @count             int,
       @ActionType        varchar(1),
       @Search            varchar(100))
RETURNS @TL TABLE
       ([taskid]              int               IDENTITY(1, 1),
        [ActionID]            int,
        [AssignNo]            int)
AS
BEGIN
DECLARE @startdate datetime
DECLARE @enddate   datetime

SET @handler = RTrim(IsNull(@handler, ''))
SET @Team = RTRIM(IsNull(@team, ''))
SET @startdateT = IsNull(@startdateT, '')
SET @enddateT = IsNull(@enddateT, '')
SET @outstanding = isnull(@outstanding, 1)

IF (IsNull(@startdateT, '') = '')
  BEGIN
    SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
  END
ELSE
  BEGIN
    IF (isdate(@startdateT) = 1)
      BEGIN
        set @startdate = convert(datetime, replace(convert(varchar(10), convert(datetime, @startdateT), 121), '-', ''))
      END
    ELSE
      BEGIN
        SET @startdate = convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', ''))
      END
  END

IF (IsNull(@enddateT, '') = '')
  BEGIN
    SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
  END
ELSE
  BEGIN
    IF (isdate(@enddateT) = 1)
      BEGIN
        set @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), convert(datetime, @enddateT), 121), '-', '')))
      END
    ELSE
      BEGIN
        SET @enddate = dateadd(d, 1, convert(datetime, replace(convert(varchar(10), getDate(), 121), '-', '')))
      END
  END

IF (@outstanding = 0)
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@handler = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@team = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[handler] = @handler
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[TEAM] = @Team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
        END
  END
ELSE
  BEGIN
    IF (@handler = '') AND (@team = '') 
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@handler = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[TEAM] = @team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE IF (@team = '')
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @Handler
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
      END
    ELSE
      BEGIN
        INSERT
          INTO @TL
              ([ActionID],
               [AssignNo])
            SELECT TOP (@startno + @count - 1)
                   OD.[ActionID],
                   OD.[AssignNo]
              FROM (SELECT DEL.[ActionID],
                           DEL.[AssignNo],
                           DEL.[DATE],
                           DEL.[TIME]
                      FROM [dbo].[DiaryDelegations] DEL
                           INNER JOIN [dbo].[Diary] DIA
                                      INNER JOIN [dbo].[matters] MS
                                                 INNER JOIN [dbo].[contacts] CTS
                                                         ON CTS.[CODE] = MS.[ClientCode]
                                              ON MS.[Code] = DIA.[CaseCode]
                                   ON DIA.[ActionID] = DEL.[ActionID]
                                  AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                                       OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                                       OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                                       OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                                       OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                     WHERE DEL.[HANDLER] = @handler
                       AND DEL.[TEAM] = @Team
                       AND DEL.[DATE] >= @startdate
                       AND DEL.[DATE] < @enddate
                       AND DEL.[STATUS] = 0
                       AND DEL.[DelType] NOT IN ('Completed', 'Processed', 'Returned')
                       AND DEL.[ActionType] = @ActionType) OD
          ORDER BY OD.[DATE],
                   OD.[TIME],
                   OD.[AssignNo],
                   OD.[ActionID]
        END
  END

  DELETE @TL
   WHERE [taskid] < @startno

  DELETE @TL
   WHERE [taskid] > (@startno + @count - 1)

  RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDTaskListPage
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskListPage]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @startno           int,
       @count             int,
       @Search            varchar(100))
AS
BEGIN
  SELECT TSK.[CaseCode],
         TSK.[Action],
         TSK.[Subject],
         RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
         RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
         Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
         Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
         TSK.[Status],
         TSK.[ActionType],
         TSK.[Priority],
         TSK.[DelegateStatus],
         TSK.[ImageNo],
         TSK.[Handler],
         TSK.[Team],
         TSK.[FromHandler],
         TSK.[ActionID],
         TSK.[DiaryStatus],
         TSK.[Highlighted],
         TSK.[Attachments],
         TSK.[DiaryDate],
         TSK.[FNCode],
         TSK.[TeamCode],
         TSK.[WorkProcess],
         TSK.[DelegationStatus],
         TSK.[ActionCode],
         TSK.[DURATION],
         TSK.[DELEGATEDDATETIME],
         TSK.[AssignNo]
    FROM (  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
                   [dbo].[ky_removespuriouswhitespace](substring(DIA.[TEXT1], 1, 120), 80) As [Action],
                   [dbo].[ky_removespuriouswhitespace](substring(DIA.[SUBJECT], 1, 150), 80) As [Subject],
                   DEL.[Status],
                   IsNull(DIA.[ActionType], '') As [ActionType],
                   IsNull(DIA.[Priority], '') As [Priority],
                   IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
                   DIA.[ImageNo],
                   IsNull(DEL.[Handler], '') As [Handler],
                   IsNull(DEL.[Team], '') As [Team],
                   IsNull(DEL.[FromHandler], '') As [FromHandler],
                   DIA.[ActionID] As [ActionID],
                   IsNull(DIA.[Status], 0) As [DiaryStatus],
                   IsNull(DIA.[Highlighted], '') As [Highlighted],
                   IsNull(DIA.[Attachments], '') As [Attachments],
                   Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
                   RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
                   IsNull(DIA.[TeamCode], '') AS [TeamCode],
                   IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
                   Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
                   RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
                   CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                             THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
                        ELSE '' END AS [DURATION],
                   [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime],
                   DEL.[AssignNo]
              FROM [dbo].[ky_WDTaskListSet]
                  (@Handler,
                   @Team,
                   @startdateT,
                   @enddateT,
                   @outstanding,
                   @startno,
                   @count,
                   @Search) TLS
                   INNER JOIN [dbo].[Diary] DIA
                              INNER JOIN [dbo].[matters] MS
                                         INNER JOIN [dbo].[contacts] CTS
                                                 ON CTS.[CODE] = MS.[ClientCode]
                                      ON MS.[Code] = DIA.[CaseCode]
                           ON DIA.[ActionID] = TLS.[ActionID]
                          AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                               OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                               OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                               OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                               OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                   INNER JOIN [dbo].[DiaryDelegations] DEL
                           ON DEL.[AssignNo] = TLS.[AssignNo]) TSK
         INNER JOIN [dbo].[matters] MAT
                    INNER JOIN [dbo].[contacts] CTC
                            ON CTC.[CODE] = MAT.[CLIENTCODE]
                 ON MAT.[Code] = TSK.[CASECODE]
ORDER BY TSK.[DelegatedDateTime]

END
GO

/**************************************************************************************
 *
 * ky_WDTaskListByHighlightPage
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskListByHighlightPage]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @startno           int,
       @count             int,
       @ActionType        varchar(1),
       @Highlighted       varchar(1),
       @Priority          varchar(1),
       @Search            varchar(100))
AS
BEGIN
  SELECT TSK.[CaseCode],
         TSK.[Action],
         TSK.[Subject],
         RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
         RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
         Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
         Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
         TSK.[Status],
         TSK.[ActionType],
         TSK.[Priority],
         TSK.[DelegateStatus],
         TSK.[ImageNo],
         TSK.[Handler],
         TSK.[Team],
         TSK.[FromHandler],
         TSK.[ActionID],
         TSK.[DiaryStatus],
         TSK.[Highlighted],
         TSK.[Attachments],
         TSK.[DiaryDate],
         TSK.[FNCode],
         TSK.[TeamCode],
         TSK.[WorkProcess],
         TSK.[DelegationStatus],
         TSK.[ActionCode],
         TSK.[DURATION],
         TSK.[DELEGATEDDATETIME],
         TSK.[AssignNo]
    FROM (  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
                   [dbo].[ky_removespuriouswhitespace](substring(DIA.[TEXT1], 1, 120), 80) As [Action],
                   [dbo].[ky_removespuriouswhitespace](substring(DIA.[SUBJECT], 1, 150), 80) As [Subject],
                   DEL.[Status],
                   IsNull(DIA.[ActionType], '') As [ActionType],
                   IsNull(DIA.[Priority], '') As [Priority],
                   IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
                   DIA.[ImageNo],
                   IsNull(DEL.[Handler], '') As [Handler],
                   IsNull(DEL.[Team], '') As [Team],
                   IsNull(DEL.[FromHandler], '') As [FromHandler],
                   DIA.[ActionID] As [ActionID],
                   IsNull(DIA.[Status], 0) As [DiaryStatus],
                   IsNull(DIA.[Highlighted], '') As [Highlighted],
                   IsNull(DIA.[Attachments], '') As [Attachments],
                   Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
                   RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
                   IsNull(DIA.[TeamCode], '') AS [TeamCode],
                   IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
                   Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
                   RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
                   CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                             THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
                        ELSE '' END AS [DURATION],
                   [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime],
                   DEL.[AssignNo]
              FROM [dbo].[ky_WDTaskListByHighlightSet]
                  (@Handler,
                   @Team,
                   @startdateT,
                   @enddateT,
                   @outstanding,
                   @startno,
                   @count,
                   @ActionType,
                   @Highlighted,
                   @Priority,
                   @Search) TLS
                   INNER JOIN [dbo].[Diary] DIA
                              INNER JOIN [dbo].[matters] MS
                                         INNER JOIN [dbo].[contacts] CTS
                                                 ON CTS.[CODE] = MS.[ClientCode]
                                      ON MS.[Code] = DIA.[CaseCode]
                           ON DIA.[ActionID] = TLS.[ActionID]
                          AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                               OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                               OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                               OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                               OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                   INNER JOIN [dbo].[DiaryDelegations] DEL
                           ON DEL.[AssignNo] = TLS.[AssignNo]) TSK
         INNER JOIN [dbo].[matters] MAT
                    INNER JOIN [dbo].[contacts] CTC
                            ON CTC.[CODE] = MAT.[CLIENTCODE]
                 ON MAT.[Code] = TSK.[CASECODE]
ORDER BY TSK.[DelegatedDateTime]

END
GO

/**************************************************************************************
 *
 * ky_WDTaskListByActionTypePage
 *
 * Returns the Task List to be displayed in WinDev/WebDev versions of the software
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDTaskListByActionTypePage]
      (@Handler           varchar(10),
       @Team              varchar(10),
       @startdateT        varchar(8),
       @enddateT          varchar(8),
       @outstanding       int,
       @startno           int,
       @count             int,
       @ActionType        varchar(1),
       @Search            varchar(100))
AS
BEGIN
  SELECT TSK.[CaseCode],
         TSK.[Action],
         TSK.[Subject],
         RTrim(IsNull(CTC.[Name], '')) AS [ClientName],
         RTrim(IsNull(MAT.[Description], '')) AS [MatterDescription],
         Convert(varchar, TSK.[DelegatedDateTime], 106) As [DATE],
         Convert(varchar, TSK.[DelegatedDateTime], 108) As [TIME],
         TSK.[Status],
         TSK.[ActionType],
         TSK.[Priority],
         TSK.[DelegateStatus],
         TSK.[ImageNo],
         TSK.[Handler],
         TSK.[Team],
         TSK.[FromHandler],
         TSK.[ActionID],
         TSK.[DiaryStatus],
         TSK.[Highlighted],
         TSK.[Attachments],
         TSK.[DiaryDate],
         TSK.[FNCode],
         TSK.[TeamCode],
         TSK.[WorkProcess],
         TSK.[DelegationStatus],
         TSK.[ActionCode],
         TSK.[DURATION],
         TSK.[DELEGATEDDATETIME],
         TSK.[AssignNo]
    FROM (  SELECT RTrim(IsNull(DIA.[CaseCode], '')) As [CaseCode],
                   [dbo].[ky_removespuriouswhitespace](substring(DIA.[TEXT1], 1, 120), 80) As [Action],
                   [dbo].[ky_removespuriouswhitespace](substring(DIA.[SUBJECT], 1, 150), 80) As [Subject],
                   DEL.[Status],
                   IsNull(DIA.[ActionType], '') As [ActionType],
                   IsNull(DIA.[Priority], '') As [Priority],
                   IsNull(DEL.[DELEGATESTATUS], 0) As [DelegateStatus],
                   DIA.[ImageNo],
                   IsNull(DEL.[Handler], '') As [Handler],
                   IsNull(DEL.[Team], '') As [Team],
                   IsNull(DEL.[FromHandler], '') As [FromHandler],
                   DIA.[ActionID] As [ActionID],
                   IsNull(DIA.[Status], 0) As [DiaryStatus],
                   IsNull(DIA.[Highlighted], '') As [Highlighted],
                   IsNull(DIA.[Attachments], '') As [Attachments],
                   Convert(varchar, DIA.[DATE], 106) As [DiaryDate],
                   RTrim(IsNull(DIA.[FNCode], '')) AS [FNCode],
                   IsNull(DIA.[TeamCode], '') AS [TeamCode],
                   IsNull(DIA.[WorkProcess], 0) AS [WorkProcess],
                   Convert(int, IsNull(DIA.[DelegationStatus], 0)) AS [DelegationStatus],
                   RTrim(IsNull(DIA.[ACTIONCODE], '')) AS [ActionCode],
                   CASE WHEN DIA.[ACTIONTYPE] = 'D' AND DIA.[IMAGENO] > 0
                             THEN 'Length: ' + Convert(varchar, [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DIA.[DATE], DIA.[IMAGENO]), 108)
                        ELSE '' END AS [DURATION],
                   [dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL.[DATE], DEL.[TIME]) AS [DelegatedDateTime],
                   DEL.[AssignNo]
              FROM [dbo].[ky_WDTaskListByActionTypeSet]
                  (@Handler,
                   @Team,
                   @startdateT,
                   @enddateT,
                   @outstanding,
                   @startno,
                   @count,
                   @ActionType,
                   @Search) TLS
                   INNER JOIN [dbo].[Diary] DIA
                              INNER JOIN [dbo].[matters] MS
                                         INNER JOIN [dbo].[contacts] CTS
                                                 ON CTS.[CODE] = MS.[ClientCode]
                                      ON MS.[Code] = DIA.[CaseCode]
                           ON DIA.[ActionID] = TLS.[ActionID]
                          AND DIA.[ActionType] = @ActionType
                          AND (   CONVERT(varchar(5000), DIA.[SUBJECT]) LIKE @Search
                               OR CONVERT(varchar(5000), DIA.[Text1]) LIKE @Search
                               OR CONVERT(varchar(20), MS.[Code]) LIKE @Search
                               OR CONVERT(varchar(5000), MS.[Description]) LIKE @Search
                               OR CONVERT(varchar(5000), CTS.[Name]) LIKE @Search)
                   INNER JOIN [dbo].[DiaryDelegations] DEL
                           ON DEL.[AssignNo] = TLS.[AssignNo]) TSK
         INNER JOIN [dbo].[matters] MAT
                    INNER JOIN [dbo].[contacts] CTC
                            ON CTC.[CODE] = MAT.[CLIENTCODE]
                 ON MAT.[Code] = TSK.[CASECODE]
ORDER BY TSK.[DelegatedDateTime]

END
GO

/**************************************************************************************
 *
 * ky_WDSearchCaseAssociates2
 *
 * Returns a list of Case Associates matching a search criterion
 * by name, addres, or phone number
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchCaseAssociates2]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe
 
SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[LegalAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CASE WHEN CAS.[TOTALCLIENTS] = 0
                     THEN ''
                WHEN CAS.[TOTALCLIENTS] = 1
                     THEN SIC.[ClientCode]
                ELSE convert(varchar(5), CAS.[TOTALCLIENTS]) + ' Clients' END AS [ClientCode],
           CAN.[Code] As [NameCode]
      FROM [dbo].[CaseAssociatesNames] CAN
           CROSS APPLY (SELECT COUNT(DISTINCT MA1.[Code]) AS TOTAL,
                               COUNT(DISTINCT MA1.[ClientCode]) AS TOTALCLIENTS
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) CAS
           CROSS APPLY (SELECT TOP 1 CCO.[CASECODE],
                                     MA1.[ClientCode] 
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) SIC
     WHERE (   CAN.[name] like @search
            OR CAN.[address] like @search
            OR (    @IncludePhone = 1
                AND CAN.[phoneno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[faxno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[mobileno] like @search)
            OR CAN.[legalname] like @search
            OR CAN.[legaladdress] like @search)
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CASE WHEN CAS.[TOTALCLIENTS] = 0
                     THEN ''
                WHEN CAS.[TOTALCLIENTS] = 1
                     THEN SIC.[ClientCode]
                ELSE convert(varchar(5), CAS.[TOTALCLIENTS]) + ' Clients' END AS [ClientCode],
           CAN.[NameCode] As [NameCode]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]
             WHERE (   CAC.[name] like @search
                    OR CAC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CAC.[phone] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[fax] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT COUNT(DISTINCT MA1.[Code]) AS TOTAL,
                               COUNT(DISTINCT MA1.[ClientCode]) AS TOTALCLIENTS
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) CAS
           CROSS APPLY (SELECT TOP 1 CCO.[CASECODE],
                                     MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) SIC
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[LegalAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[CASECODE] AS [Cases],
           SIC.[ClientCode] AS [ClientCode],
           CAN.[Code] As [NameCode]
      FROM [dbo].[CaseAssociatesNames] CAN
           CROSS APPLY (SELECT CCO.[CASECODE],
                               MA1.[ClientCode] 
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) SIC
     WHERE (   CAN.[name] like @search
            OR CAN.[address] like @search
            OR (    @IncludePhone = 1
                AND CAN.[phoneno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[faxno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[mobileno] like @search)
            OR CAN.[legalname] like @search
            OR CAN.[legaladdress] like @search)
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[CASECODE] AS [Cases],
           SIC.[ClientCode] AS [ClientCode],
           CAN.[NameCode] As [NameCode]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]
             WHERE (   CAC.[name] like @search
                    OR CAC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CAC.[phone] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[fax] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT CCO.[CASECODE],
                               MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) SIC
  END

DELETE @SR
 WHERE [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN

END

GO

/**************************************************************************************
 *
 * ky_WDSearchCaseAssociates
 *
 * Returns a list of Case Associates matching a search criterion
 * by name, addres, or phone number
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchCaseAssociates]
      (@search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[LegalAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CASE WHEN CAS.[TOTALCLIENTS] = 0
                     THEN ''
                WHEN CAS.[TOTALCLIENTS] = 1
                     THEN SIC.[ClientCode]
                ELSE convert(varchar(5), CAS.[TOTALCLIENTS]) + ' Clients' END AS [ClientCode],
           CAN.[Code] As [NameCode]
      FROM [dbo].[CaseAssociatesNames] CAN
           CROSS APPLY (SELECT COUNT(DISTINCT MA1.[Code]) AS TOTAL,
                               COUNT(DISTINCT MA1.[ClientCode]) AS TOTALCLIENTS
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) CAS
           CROSS APPLY (SELECT TOP 1 CCO.[CASECODE],
                                     MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) SIC
     WHERE (   CAN.[name] like @search
            OR CAN.[address] like @search
            OR (    @IncludePhone = 1
                AND CAN.[phoneno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[faxno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[mobileno] like @search)
            OR CAN.[legalname] like @search
            OR CAN.[legaladdress] like @search)
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CASE WHEN CAS.[TOTALCLIENTS] = 0
                     THEN ''
                WHEN CAS.[TOTALCLIENTS] = 1
                     THEN SIC.[ClientCode]
                ELSE convert(varchar(5), CAS.[TOTALCLIENTS]) + ' Clients' END AS [ClientCode],
           CAN.[NameCode] As [NameCode]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]
             WHERE (   CAC.[name] like @search
                    OR CAC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CAC.[phone] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[fax] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT COUNT(DISTINCT MA1.[Code]) AS TOTAL,
                               COUNT(DISTINCT MA1.[ClientCode]) AS TOTALCLIENTS
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) CAS
           CROSS APPLY (SELECT TOP 1 CCO.[CASECODE],
                                     MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) SIC
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[LegalAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[CASECODE] AS [Cases],
           SIC.[ClientCode] AS [ClientCode],
           CAN.[Code] As [NameCode]
      FROM [dbo].[CaseAssociatesNames] CAN
           CROSS APPLY (SELECT CCO.[CASECODE],
                               MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) SIC
     WHERE (   CAN.[name] like @search
            OR CAN.[address] like @search
            OR (    @IncludePhone = 1
                AND CAN.[phoneno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[faxno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[mobileno] like @search)
            OR CAN.[legalname] like @search
            OR CAN.[legaladdress] like @search)
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[CASECODE] AS [Cases],
           SIC.[ClientCode] AS [ClientCode],
           CAN.[NameCode] As [NameCode]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]
             WHERE (   CAC.[name] like @search
                    OR CAC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CAC.[phone] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[fax] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT CCO.[CASECODE],
                               MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) SIC
  END

DELETE @SR
 WHERE [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN

END
GO

/**************************************************************************************
 *
 * ky_WDSearchContacts2
 *
 * Returns a list of Contacts matching a search criterion
 * by name, addres, or phone number
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchContacts2]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[OtherAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CON.[Code] AS [ClientCode],
           '' AS [NameCode]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]
           CROSS APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) CAS
           CROSS APPLY (SELECT TOP 1 MAT.[CODE] AS [CASECODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
     WHERE (   CON.[name] like @search
            OR CON.[address] like @search
            OR (    @IncludePhone = 1
                AND CON.[tel] like @search)
            OR (    @IncludePhone = 1
                AND CON.[fax] like @search)
            OR (    @IncludePhone = 1
                AND CLI.[CLMOBNO] like @search)
            OR CON.[otheraddress] like @search)
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[OtherAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[FAX], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL],
           SIC.[CaseCode] AS [Cases],
           CON.[Code] AS [ClientCode],
           '' AS [NameCode]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]
           CROSS APPLY (SELECT MAT.[CODE] AS [CASECODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
     WHERE (   CON.[name] like @search
            OR CON.[address] like @search
            OR (    @IncludePhone = 1
                AND CON.[tel] like @search)
            OR (    @IncludePhone = 1
                AND CON.[fax] like @search)
            OR CON.[otheraddress] like @search)
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchContacts
 *
 * Returns a list of Contacts matching a search criterion
 * by name, addres, or phone number
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchContacts]
      (@search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[OtherAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CON.[Code] AS [ClientCode],
           '' AS [NameCode]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]
           CROSS APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)) CAS
           CROSS APPLY (SELECT TOP 1 MAT.[CODE] AS [CASECODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)) SIC
     WHERE (   CON.[name] like @search
            OR CON.[address] like @search
            OR (    @IncludePhone = 1
                AND CON.[tel] like @search)
            OR (    @IncludePhone = 1
                AND CON.[fax] like @search)
            OR (    @IncludePhone = 1
                AND CLI.[CLMOBNO] like @search)
            OR CON.[otheraddress] like @search)
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[OtherAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[FAX], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL],
           SIC.[CaseCode] AS [Cases],
           CON.[Code] AS [ClientCode],
           '' AS [NameCode]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]
           CROSS APPLY (SELECT MAT.[CODE] AS [CASECODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)) SIC
     WHERE (   CON.[name] like @search
            OR CON.[address] like @search
            OR (    @IncludePhone = 1
                AND CON.[tel] like @search)
            OR (    @IncludePhone = 1
                AND CON.[fax] like @search)
            OR CON.[otheraddress] like @search)
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchClientContacts
 *
 * Returns a list of Client Contacts matching a search criterion
 * by name, addres, or phone number
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchClientContacts]
      (@search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CAN.[CLCODE],
           ''
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]
             WHERE (   CLC.[clnamecon] like @search
                    OR CLC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CLC.[homephone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[workphone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)) CAS
           CROSS APPLY (SELECT TOP 1 MAT.[CODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)) SIC
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[Code] AS [Cases],
           CAN.[CLCODE],
           ''
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]
             WHERE (   CLC.[clnamecon] like @search
                    OR CLC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CLC.[homephone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[workphone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT MAT.[CODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)) SIC
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchClientContacts2
 *
 * Returns a list of Client Contacts matching a search criterion
 * by name, addres, or phone number
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchClientContacts2]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CAN.[CLCODE],
           ''
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]
             WHERE (   CLC.[clnamecon] like @search
                    OR CLC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CLC.[homephone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[workphone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) CAS
           CROSS APPLY (SELECT TOP 1 MAT.[CODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[Code] AS [Cases],
           CAN.[CLCODE],
           ''
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]
             WHERE (   CLC.[clnamecon] like @search
                    OR CLC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CLC.[homephone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[workphone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[mobile] like @search))) CAN
           CROSS APPLY (SELECT MAT.[CODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchMatterContacts
 *
 * Returns a list of Matter Contacts matching a search criterion
 * on matter description or user defined fields
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchMatterContacts]
      (@search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT RES.[NAME],
           RES.[Address],
           RES.[Phone],
           RES.[Mobile],
           RES.[Fax],
           RES.[Email],
           CASE WHEN COUNT(1) > 1
                     THEN convert(varchar(5), COUNT(1)) + ' Cases'
                ELSE MAX(RES.[Cases]) END AS [Cases],
           RES.[ClientCode],
           ''
      FROM (SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
                   [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                             THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                        WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                             THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                        ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
                   convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
                   convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
                   convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
                   CAN.[Code] AS [Cases],
                   CAN.[ClientCode] AS [ClientCode]
              FROM (SELECT MAT.[CODE],
                           CNN.[CODE] AS [CLIENTCODE],
                           RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                           RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                           RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                           RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                           RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                           RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
                      FROM [dbo].[matters] MAT
                           LEFT OUTER JOIN [dbo].[Contacts] CNN
                                        ON CNN.[CODE] = MAT.[ClientCode]
                           LEFT OUTER JOIN [dbo].[client] CLN
                                        ON CLN.[CLCODE] = MAT.[ClientCode]
                     WHERE (   MAT.[description] like @mattersearch
                            OR MAT.[user1] like @mattersearch
                            OR MAT.[user2] like @mattersearch
                            OR MAT.[user3] like @mattersearch)
                       AND (   CLN.[CLNAME] like @search
                            OR CLN.[CLADDR] like @search
                            OR CLN.[CLTEL] like @search
                            OR CLN.[CLMOBNO] like @search
                            OR CLN.[CLFAX] like @search
                            OR CLN.[CLEMAIL] like @search)
                       AND (   CNN.[Name] like @search
                            OR CNN.[Address] like @search
                            OR CNN.[Tel] like @search
                            OR CNN.[Fax] like @search
                            OR CNN.[email] like @search)) CAN) RES
    GROUP BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             RES.[ClientCode]
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CAN.[Code] AS [Cases],
           CAN.[ClientCode] AS [ClientCode],
           ''
      FROM (SELECT MAT.[CODE],
                   CNN.[CODE] AS [CLIENTCODE],
                   RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                   RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                   RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                   RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                   RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                   RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
              FROM [dbo].[matters] MAT
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = MAT.[ClientCode]
                   LEFT OUTER JOIN [dbo].[client] CLN
                                ON CLN.[CLCODE] = MAT.[ClientCode]
             WHERE (   MAT.[description] like @mattersearch
                    OR MAT.[user1] like @mattersearch
                    OR MAT.[user2] like @mattersearch
                    OR MAT.[user3] like @mattersearch)
               AND (   CLN.[CLNAME] like @search
                    OR CLN.[CLADDR] like @search
                    OR CLN.[CLTEL] like @search
                    OR CLN.[CLMOBNO] like @search
                    OR CLN.[CLFAX] like @search
                    OR CLN.[CLEMAIL] like @search)
               AND (   CNN.[Name] like @search
                    OR CNN.[Address] like @search
                    OR CNN.[Tel] like @search
                    OR CNN.[Fax] like @search
                    OR CNN.[email] like @search)) CAN
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchMatterContacts2
 *
 * Returns a list of Matter Contacts matching a search criterion
 * on matter description or user defined fields
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchMatterContacts2]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT RES.[NAME],
           RES.[Address],
           RES.[Phone],
           RES.[Mobile],
           RES.[Fax],
           RES.[Email],
           CASE WHEN COUNT(1) > 1
                     THEN convert(varchar(5), COUNT(1)) + ' Cases'
                ELSE MAX(RES.[Cases]) END AS [Cases],
           RES.[ClientCode],
           ''
      FROM (SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
                   [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                             THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                        WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                             THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                        ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
                   convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
                   convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
                   convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
                   CAN.[Code] AS [Cases],
                   CAN.[ClientCode] AS [ClientCode]
              FROM (SELECT MAT.[CODE],
                           CNN.[CODE] AS [CLIENTCODE],
                           RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                           RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                           RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                           RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                           RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                           RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
                      FROM [dbo].[matters] MAT
                           LEFT OUTER JOIN [dbo].[Contacts] CNN
                                        ON CNN.[CODE] = MAT.[ClientCode]
                           LEFT OUTER JOIN [dbo].[client] CLN
                                        ON CLN.[CLCODE] = MAT.[ClientCode]
                     WHERE (   MAT.[description] like @mattersearch
                            OR MAT.[user1] like @mattersearch
                            OR MAT.[user2] like @mattersearch
                            OR MAT.[user3] like @mattersearch)
                       AND (   (IsNull(MAT.[Permissions], 0) = 0)
                            OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))
                       AND (   CLN.[CLNAME] like @search
                            OR CLN.[CLADDR] like @search
                            OR CLN.[CLTEL] like @search
                            OR CLN.[CLMOBNO] like @search
                            OR CLN.[CLFAX] like @search
                            OR CLN.[CLEMAIL] like @search)
                       AND (   CNN.[Name] like @search
                            OR CNN.[Address] like @search
                            OR CNN.[Tel] like @search
                            OR CNN.[Fax] like @search
                            OR CNN.[email] like @search)) CAN) RES
    GROUP BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             RES.[ClientCode]
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CAN.[Code] AS [Cases],
           CAN.[ClientCode] AS [ClientCode],
           ''
      FROM (SELECT MAT.[CODE],
                   CNN.[CODE] AS [CLIENTCODE],
                   RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                   RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                   RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                   RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                   RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                   RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
              FROM [dbo].[matters] MAT
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = MAT.[ClientCode]
                   LEFT OUTER JOIN [dbo].[client] CLN
                                ON CLN.[CLCODE] = MAT.[ClientCode]
             WHERE (   MAT.[description] like @mattersearch
                    OR MAT.[user1] like @mattersearch
                    OR MAT.[user2] like @mattersearch
                    OR MAT.[user3] like @mattersearch)
               AND (   (IsNull(MAT.[Permissions], 0) = 0)
                    OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))
               AND (   CLN.[CLNAME] like @search
                    OR CLN.[CLADDR] like @search
                    OR CLN.[CLTEL] like @search
                    OR CLN.[CLMOBNO] like @search
                    OR CLN.[CLFAX] like @search
                    OR CLN.[CLEMAIL] like @search)
               AND (   CNN.[Name] like @search
                    OR CNN.[Address] like @search
                    OR CNN.[Tel] like @search
                    OR CNN.[Fax] like @search
                    OR CNN.[email] like @search)) CAN
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchAllContacts2
 *
 * Returns a list of Matter Contacts matching a search criterion
 * on matter description or user defined fields
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDSearchAllContacts2]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @includeCA        int,
       @includeCC        int,
       @includeCO        int,
       @includeMC        int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @bycase           int,
       @IncludePhone     int)
AS
BEGIN

SET @IncludePhone = Case When ISNULL(@IncludePhone, 0) = 1 
                              THEN 1
                         ELSE 0 END

IF (@expand = 0)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             COUNT(1) AS [Cases],
             '' As [CaseCode],
             '' As [ClientName],
             '' As [CaseDescription]
        FROM (  SELECT RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case],
                       Max(RES.[ClientCode]) AS [ClientCode],
                       Max(RES.[NameCode]) As [NameCode]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCA,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchContacts2](@fe,
                                                             @search,
                                                             @mattersearch,
                                                             @includeCO,
                                                             1,
                                                             @clientcode,
                                                             @namecode,
                                                             @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeMC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)) RES
              GROUP BY RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case]) NR
    GROUP BY NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode]
  END

if (@expand = 1) AND (@bycase = 1)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             1 As [Cases],
             NR.[Case] As [CaseCode],
             RTrim(IsNull(CON.[Name], '')) As [ClientName],
             RTrim(IsNull(MAT.[Description], '')) As [CaseDescription]
        FROM (  SELECT '' As [Name],
                       '' As [Address],
                       '' As [Phone],
                       '' As [Mobile],
                       '' As [Fax],
                       '' As [Email],
                       @clientcode AS [ClientCode],
                       @namecode AS [NameCode],
                       RES.[Case]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCA,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchContacts2](@fe,
                                                             @search,
                                                             @mattersearch,
                                                             @includeCO,
                                                             1,
                                                             @clientcode,
                                                             @namecode,
                                                             @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeMC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)) RES
              GROUP BY RES.[Case]) NR
             INNER JOIN [dbo].[Matters] MAT
                        INNER JOIN [dbo].[contacts] CON
                                ON CON.[Code] = MAT.[ClientCode]
                     ON MAT.[CODE] = NR.[Case]
  END

if (@expand = 1) AND (@bycase = 0)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             1 As [Cases],
             NR.[Case] As [CaseCode],
             RTrim(IsNull(CON.[Name], '')) As [ClientName],
             RTrim(IsNull(MAT.[Description], '')) As [CaseDescription]
        FROM (  SELECT RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       @clientcode AS [ClientCode],
                       @namecode AS [NameCode],
                       RES.[Case]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCA,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchContacts2](@fe,
                                                             @search,
                                                             @mattersearch,
                                                             @includeCO,
                                                             1,
                                                             @clientcode,
                                                             @namecode,
                                                             @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts2](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeMC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone)) RES
              GROUP BY RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case]) NR
             INNER JOIN [dbo].[Matters] MAT
                        INNER JOIN [dbo].[contacts] CON
                                ON CON.[Code] = MAT.[ClientCode]
                     ON MAT.[CODE] = NR.[Case]
  END

END
GO

/**************************************************************************************
 *
 * ky_WDSearchAllContacts
 *
 * Returns a list of Matter Contacts matching a search criterion
 * on matter description or user defined fields
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDSearchAllContacts]
      (@search           varchar(50),
       @mattersearch     varchar(50),
       @includeCA        int,
       @includeCC        int,
       @includeCO        int,
       @includeMC        int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @bycase           int,
       @IncludePhone     int)
AS
BEGIN

SET @IncludePhone = Case When ISNULL(@IncludePhone, 0) = 1 
                              THEN 1
                         ELSE 0 END

IF (@expand = 0)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             COUNT(1) AS [Cases],
             '' As [CaseCode],
             '' As [ClientName],
             '' As [CaseDescription]
        FROM (  SELECT RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case],
                       Max(RES.[ClientCode]) AS [ClientCode],
                       Max(RES.[NameCode]) As [NameCode]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates](@search,
                                                                  @mattersearch,
                                                                  @includeCA,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts](@search,
                                                                  @mattersearch,
                                                                  @includeCC,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchContacts](@search,
                                                            @mattersearch,
                                                            @includeCO,
                                                            1,
                                                            @clientcode,
                                                            @namecode,
                                                            @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts](@search,
                                                                  @mattersearch,
                                                                  @includeMC,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)) RES
              GROUP BY RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case]) NR
    GROUP BY NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode]
  END

if (@expand = 1) AND (@bycase = 1)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             1 As [Cases],
             NR.[Case] As [CaseCode],
             RTrim(IsNull(CON.[Name], '')) As [ClientName],
             RTrim(IsNull(MAT.[Description], '')) As [CaseDescription]
        FROM (  SELECT '' As [Name],
                       '' As [Address],
                       '' As [Phone],
                       '' As [Mobile],
                       '' As [Fax],
                       '' As [Email],
                       @clientcode AS [ClientCode],
                       @namecode AS [NameCode],
                       RES.[Case]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates](@search,
                                                                  @mattersearch,
                                                                  @includeCA,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts](@search,
                                                                  @mattersearch,
                                                                  @includeCC,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchContacts](@search,
                                                            @mattersearch,
                                                            @includeCO,
                                                            1,
                                                            @clientcode,
                                                            @namecode,
                                                            @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts](@search,
                                                                  @mattersearch,
                                                                  @includeMC,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)) RES
              GROUP BY RES.[Case]) NR
             INNER JOIN [dbo].[Matters] MAT
                        INNER JOIN [dbo].[contacts] CON
                                ON CON.[Code] = MAT.[ClientCode]
                     ON MAT.[CODE] = NR.[Case]
  END

if (@expand = 1) AND (@bycase = 0)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             1 As [Cases],
             NR.[Case] As [CaseCode],
             RTrim(IsNull(CON.[Name], '')) As [ClientName],
             RTrim(IsNull(MAT.[Description], '')) As [CaseDescription]
        FROM (  SELECT RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       @clientcode AS [ClientCode],
                       @namecode AS [NameCode],
                       RES.[Case]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates](@search,
                                                                  @mattersearch,
                                                                  @includeCA,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts](@search,
                                                                  @mattersearch,
                                                                  @includeCC,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchContacts](@search,
                                                            @mattersearch,
                                                            @includeCO,
                                                            1,
                                                            @clientcode,
                                                            @namecode,
                                                            @IncludePhone)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts](@search,
                                                                  @mattersearch,
                                                                  @includeMC,
                                                                  1,
                                                                  @clientcode,
                                                                  @namecode,
                                                                  @IncludePhone)) RES
              GROUP BY RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case]) NR
             INNER JOIN [dbo].[Matters] MAT
                        INNER JOIN [dbo].[contacts] CON
                                ON CON.[Code] = MAT.[ClientCode]
                     ON MAT.[CODE] = NR.[Case]
  END

END
GO

/**************************************************************************************
 *
 * ky_WDSearchCaseAssociates3
 *
 * Returns a list of Case Associates matching a search criterion
 * by name, addres, or phone number
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchCaseAssociates3]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int,
       @IncludeEmails    int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe
 
SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[LegalAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CASE WHEN CAS.[TOTALCLIENTS] = 0
                     THEN ''
                WHEN CAS.[TOTALCLIENTS] = 1
                     THEN SIC.[ClientCode]
                ELSE convert(varchar(5), CAS.[TOTALCLIENTS]) + ' Clients' END AS [ClientCode],
           CAN.[Code] As [NameCode]
      FROM [dbo].[CaseAssociatesNames] CAN
           CROSS APPLY (SELECT COUNT(DISTINCT MA1.[Code]) AS TOTAL,
                               COUNT(DISTINCT MA1.[ClientCode]) AS TOTALCLIENTS
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[Code] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) CAS
           CROSS APPLY (SELECT TOP 1 CCO.[CASECODE],
                                     MA1.[ClientCode] 
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[Code] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) SIC
     WHERE (   CAN.[name] like @search
            OR CAN.[address] like @search
            OR (    @IncludePhone = 1
                AND CAN.[phoneno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[faxno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[mobileno] like @search)
            OR (    @IncludeEmails = 1
                AND CAN.[EMAIL] like @search)
            OR CAN.[legalname] like @search
            OR CAN.[legaladdress] like @search)
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CASE WHEN CAS.[TOTALCLIENTS] = 0
                     THEN ''
                WHEN CAS.[TOTALCLIENTS] = 1
                     THEN SIC.[ClientCode]
                ELSE convert(varchar(5), CAS.[TOTALCLIENTS]) + ' Clients' END AS [ClientCode],
           CAN.[NameCode] As [NameCode]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]
             WHERE (   CAC.[name] like @search
                    OR CAC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CAC.[phone] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[fax] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[mobile] like @search)
                    OR (    @IncludeEmails = 1
                        AND CAC.[EMAIL] like @search))) CAN
           CROSS APPLY (SELECT COUNT(DISTINCT MA1.[Code]) AS TOTAL,
                               COUNT(DISTINCT MA1.[ClientCode]) AS TOTALCLIENTS
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[Code] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) CAS
           CROSS APPLY (SELECT TOP 1 CCO.[CASECODE],
                                     MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[Code] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) SIC
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[LegalAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[CASECODE] AS [Cases],
           SIC.[ClientCode] AS [ClientCode],
           CAN.[Code] As [NameCode]
      FROM [dbo].[CaseAssociatesNames] CAN
           CROSS APPLY (SELECT CCO.[CASECODE],
                               MA1.[ClientCode] 
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[Code] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[CODE]) SIC
     WHERE (   CAN.[name] like @search
            OR CAN.[address] like @search
            OR (    @IncludePhone = 1
                AND CAN.[phoneno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[faxno] like @search)
            OR (    @IncludePhone = 1
                AND CAN.[mobileno] like @search)
            OR (    @IncludeEmails = 1
                AND CAN.[EMAIL] like @search)
            OR CAN.[legalname] like @search
            OR CAN.[legaladdress] like @search)
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[CASECODE] AS [Cases],
           SIC.[ClientCode] AS [ClientCode],
           CAN.[NameCode] As [NameCode]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]
             WHERE (   CAC.[name] like @search
                    OR CAC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CAC.[phone] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[fax] like @search)
                    OR (    @IncludePhone = 1
                        AND CAC.[mobile] like @search)
                    OR (    @IncludeEmails = 1
                        AND CAC.[EMAIL] like @search))) CAN
           CROSS APPLY (SELECT CCO.[CASECODE],
                               MA1.[ClientCode]
                          FROM [dbo].[casecontacts] CCO
                               INNER JOIN [dbo].[matters] MA1
                                       ON MA1.[Code] = CCO.[CASECODE]
                                      AND (   MA1.[description] like @mattersearch
                                           OR MA1.[Code] like @mattersearch
                                           OR MA1.[user1] like @mattersearch
                                           OR MA1.[user2] like @mattersearch
                                           OR MA1.[user3] like @mattersearch)
                                      AND (   (IsNull(MA1.[Permissions], 0) = 0)
                                           OR ((IsNull(MA1.[Permissions], 0) & @fePerm) <> 0))
                                      AND MA1.ClientCode LIKE @clientcode
                         WHERE CCO.[NAMECODE] = CAN.[NAMECODE]
                            OR CCO.[AssignedContact] = CAN.[KEYID]) SIC
  END

DELETE @SR
 WHERE [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN

END

GO

/**************************************************************************************
 *
 * ky_WDSearchContacts3
 *
 * Returns a list of Contacts matching a search criterion
 * by name, addres, or phone number
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchContacts3]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int,
       @IncludeEmails    int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[OtherAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CASECODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CON.[Code] AS [ClientCode],
           '' AS [NameCode]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]
           CROSS APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[Code] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) CAS
           CROSS APPLY (SELECT TOP 1 MAT.[CODE] AS [CASECODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[Code] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
     WHERE (   CON.[name] like @search
            OR CON.[address] like @search
            OR (    @IncludePhone = 1
                AND CON.[tel] like @search)
            OR (    @IncludePhone = 1
                AND CON.[fax] like @search)
            OR (    @IncludePhone = 1
                AND CLI.[CLMOBNO] like @search)
            OR (    @IncludeEmails = 1
                AND CLI.[CLEMAIL] like @search)
            OR CON.[otheraddress] like @search)
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[OtherAddress], 1, 200))
                ELSE [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CON.[Address], 1, 200)) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[FAX], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL],
           SIC.[CaseCode] AS [Cases],
           CON.[Code] AS [ClientCode],
           '' AS [NameCode]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]
           CROSS APPLY (SELECT MAT.[CODE] AS [CASECODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CON.[CODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[Code] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
     WHERE (   CON.[name] like @search
            OR CON.[address] like @search
            OR (    @IncludePhone = 1
                AND CON.[tel] like @search)
            OR (    @IncludePhone = 1
                AND CON.[fax] like @search)
            OR (    @IncludeEmails = 1
                AND CON.[email] like @search)
            OR CON.[otheraddress] like @search)
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchClientContacts3
 *
 * Returns a list of Client Contacts matching a search criterion
 * by name, addres, or phone number
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchClientContacts3]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int,
       @IncludeEmails    int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CASE WHEN CAS.[TOTAL] = 0
                     THEN ''
                WHEN CAS.[TOTAL] = 1
                     THEN SIC.[CODE]
                ELSE convert(varchar(5), CAS.[TOTAL]) + ' Cases' END AS [Cases],
           CAN.[CLCODE],
           ''
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]
             WHERE (   CLC.[clnamecon] like @search
                    OR CLC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CLC.[homephone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[workphone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[mobile] like @search)
                    OR (    @IncludeEmails = 1
                        AND CLC.[EmailAddress] like @search))) CAN
           CROSS APPLY (SELECT COUNT(1) AS TOTAL
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[Code] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) CAS
           CROSS APPLY (SELECT TOP 1 MAT.[CODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[Code] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           SIC.[Code] AS [Cases],
           CAN.[CLCODE],
           ''
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]
             WHERE (   CLC.[clnamecon] like @search
                    OR CLC.[address] like @search
                    OR (    @IncludePhone = 1
                        AND CLC.[homephone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[workphone] like @search)
                    OR (    @IncludePhone = 1
                        AND CLC.[mobile] like @search)
                    OR (    @IncludeEmails = 1
                        AND CLC.[EmailAddress] like @search))) CAN
           CROSS APPLY (SELECT MAT.[CODE]
                          FROM [dbo].[matters] MAT
                         WHERE MAT.[ClientCode] = CAN.[CLCODE]
                           AND (   MAT.[description] like @mattersearch
                                OR MAT.[Code] like @mattersearch
                                OR MAT.[user1] like @mattersearch
                                OR MAT.[user2] like @mattersearch
                                OR MAT.[user3] like @mattersearch)
                           AND (   (IsNull(MAT.[Permissions], 0) = 0)
                                OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))) SIC
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchMatterContacts3
 *
 * Returns a list of Matter Contacts matching a search criterion
 * on matter description or user defined fields
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDSearchMatterContacts3]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @include          int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int,
       @IncludeEmails    int)
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
AS
BEGIN

IF (@include = 0)
  RETURN

DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[Handler] = @fe

SET @search = '%' + RTrim(IsNull(@search, '')) + '%'
SET @search = replace(@search, '%%', '%')

SET @mattersearch = '%' + RTrim(IsNull(@mattersearch, '')) + '%'
SET @mattersearch = replace(@mattersearch, '%%', '%')

SET @clientcode = RTrim(IsNull(@clientcode, ''))
IF (@clientcode = '')
  SET @clientcode = '%'

SET @namecode = RTrim(IsNull(@namecode, ''))
IF (@namecode = '')
  SET @namecode = '%'

IF (@expand = 0)
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT RES.[NAME],
           RES.[Address],
           RES.[Phone],
           RES.[Mobile],
           RES.[Fax],
           RES.[Email],
           CASE WHEN COUNT(1) > 1
                     THEN convert(varchar(5), COUNT(1)) + ' Cases'
                ELSE MAX(RES.[Cases]) END AS [Cases],
           RES.[ClientCode],
           ''
      FROM (SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
                   [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                             THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                        WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                             THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                        ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
                   convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
                   convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
                   convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
                   CAN.[Code] AS [Cases],
                   CAN.[ClientCode] AS [ClientCode]
              FROM (SELECT MAT.[CODE],
                           CNN.[CODE] AS [CLIENTCODE],
                           RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                           RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                           RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                           RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                           RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                           RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
                      FROM [dbo].[matters] MAT
                           LEFT OUTER JOIN [dbo].[Contacts] CNN
                                        ON CNN.[CODE] = MAT.[ClientCode]
                           LEFT OUTER JOIN [dbo].[client] CLN
                                        ON CLN.[CLCODE] = MAT.[ClientCode]
                     WHERE (   MAT.[description] like @mattersearch
                            OR MAT.[Code] like @mattersearch
                            OR MAT.[user1] like @mattersearch
                            OR MAT.[user2] like @mattersearch
                            OR MAT.[user3] like @mattersearch)
                       AND (   (IsNull(MAT.[Permissions], 0) = 0)
                            OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))
                       AND (   CLN.[CLNAME] like @search
                            OR CLN.[CLADDR] like @search
                            OR (    @IncludePhone = 1
                                and CLN.[CLTEL] like @search)
                            OR (    @IncludePhone = 1
                                and CLN.[CLMOBNO] like @search)
                            OR (    @IncludePhone = 1
                                and CLN.[CLFAX] like @search)
                            OR (    @IncludeEmails = 1
                                and CLN.[CLEMAIL] like @search))
                       AND (   CNN.[Name] like @search
                            OR CNN.[Address] like @search
                            OR (    @IncludePhone = 1
                                and CNN.[Tel] like @search)
                            OR (    @IncludePhone = 1
                                and CNN.[Fax] like @search)
                            OR (    @IncludeEmails = 1
                                and CNN.[email] like @search))) CAN) RES
    GROUP BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             RES.[ClientCode]
  END
ELSE
  BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [NameCode])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           [dbo].[ky_GetFirstLineOfAddress](SUBSTRING(CAN.[Address], 1, 200)) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL],
           CAN.[Code] AS [Cases],
           CAN.[ClientCode] AS [ClientCode],
           ''
      FROM (SELECT MAT.[CODE],
                   CNN.[CODE] AS [CLIENTCODE],
                   RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                   RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                   RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                   RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                   RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                   RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
              FROM [dbo].[matters] MAT
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = MAT.[ClientCode]
                   LEFT OUTER JOIN [dbo].[client] CLN
                                ON CLN.[CLCODE] = MAT.[ClientCode]
             WHERE (   MAT.[description] like @mattersearch
                    OR MAT.[Code] like @mattersearch
                    OR MAT.[user1] like @mattersearch
                    OR MAT.[user2] like @mattersearch
                    OR MAT.[user3] like @mattersearch)
               AND (   (IsNull(MAT.[Permissions], 0) = 0)
                    OR ((IsNull(MAT.[Permissions], 0) & @fePerm) <> 0))
               AND (   CLN.[CLNAME] like @search
                    OR CLN.[CLADDR] like @search
                    OR (    @IncludePhone = 1
                        and CLN.[CLTEL] like @search)
                    OR (    @IncludePhone = 1
                        and CLN.[CLMOBNO] like @search)
                    OR (    @IncludePhone = 1
                        and CLN.[CLFAX] like @search)
                    OR (    @IncludeEmails = 1
                        and CLN.[CLEMAIL] like @search))
               AND (   CNN.[Name] like @search
                    OR CNN.[Address] like @search
                    OR (    @IncludePhone = 1
                        and CNN.[Tel] like @search)
                    OR (    @IncludePhone = 1
                        and CNN.[Fax] like @search)
                    OR (    @IncludeEmails = 1
                        and  CNN.[email] like @search))) CAN
  END

DELETE @SR
 WHERE [ClientCode] NOT LIKE @clientcode
    OR [NameCode] NOT LIKE @namecode

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

/**************************************************************************************
 *
 * ky_WDSearchAllContacts3
 *
 * Returns a list of Matter Contacts matching a search criterion
 * on matter description or user defined fields
 *
 * Includes functionality to exclude matters to which the fee earner has not been authorised
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDSearchAllContacts3]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @includeCA        int,
       @includeCC        int,
       @includeCO        int,
       @includeMC        int,
       @expand           int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @bycase           int,
       @IncludePhone     int,
       @IncludeEmails    int)
AS
BEGIN

SET @IncludePhone = Case When ISNULL(@IncludePhone, 0) = 1 
                              THEN 1
                         ELSE 0 END

IF (@expand = 0)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             COUNT(1) AS [Cases],
             '' As [CaseCode],
             '' As [ClientName],
             '' As [CaseDescription]
        FROM (  SELECT RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case],
                       Max(RES.[ClientCode]) AS [ClientCode],
                       Max(RES.[NameCode]) As [NameCode]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCA,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchContacts3](@fe,
                                                             @search,
                                                             @mattersearch,
                                                             @includeCO,
                                                             1,
                                                             @clientcode,
                                                             @namecode,
                                                             @IncludePhone,
                                                             @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeMC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)) RES
              GROUP BY RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case]) NR
    GROUP BY NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode]
  END

if (@expand = 1) AND (@bycase = 1)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             1 As [Cases],
             NR.[Case] As [CaseCode],
             RTrim(IsNull(CON.[Name], '')) As [ClientName],
             RTrim(IsNull(MAT.[Description], '')) As [CaseDescription]
        FROM (  SELECT '' As [Name],
                       '' As [Address],
                       '' As [Phone],
                       '' As [Mobile],
                       '' As [Fax],
                       '' As [Email],
                       @clientcode AS [ClientCode],
                       @namecode AS [NameCode],
                       RES.[Case]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCA,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchContacts3](@fe,
                                                             @search,
                                                             @mattersearch,
                                                             @includeCO,
                                                             1,
                                                             @clientcode,
                                                             @namecode,
                                                             @IncludePhone,
                                                             @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeMC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)) RES
              GROUP BY RES.[Case]) NR
             INNER JOIN [dbo].[Matters] MAT
                        INNER JOIN [dbo].[contacts] CON
                                ON CON.[Code] = MAT.[ClientCode]
                     ON MAT.[CODE] = NR.[Case]
  END

if (@expand = 1) AND (@bycase = 0)
  BEGIN
      SELECT NR.[Name],
             NR.[Address],
             NR.[Phone],
             NR.[Mobile],
             NR.[Fax],
             NR.[Email],
             NR.[ClientCode],
             NR.[NameCode],
             1 As [Cases],
             NR.[Case] As [CaseCode],
             RTrim(IsNull(CON.[Name], '')) As [ClientName],
             RTrim(IsNull(MAT.[Description], '')) As [CaseDescription]
        FROM (  SELECT RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       @clientcode AS [ClientCode],
                       @namecode AS [NameCode],
                       RES.[Case]
                  FROM (SELECT * from [ky_WDSearchCaseAssociates3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCA,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchClientContacts3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeCC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchContacts3](@fe,
                                                             @search,
                                                             @mattersearch,
                                                             @includeCO,
                                                             1,
                                                             @clientcode,
                                                             @namecode,
                                                             @IncludePhone,
                                                             @IncludeEmails)
                        UNION
                        SELECT * from [ky_WDSearchMatterContacts3](@fe,
                                                                   @search,
                                                                   @mattersearch,
                                                                   @includeMC,
                                                                   1,
                                                                   @clientcode,
                                                                   @namecode,
                                                                   @IncludePhone,
                                                                   @IncludeEmails)) RES
              GROUP BY RES.[Name],
                       RES.[Address],
                       RES.[Phone],
                       RES.[Mobile],
                       RES.[Fax],
                       RES.[Email],
                       RES.[Case]) NR
             INNER JOIN [dbo].[Matters] MAT
                        INNER JOIN [dbo].[contacts] CON
                                ON CON.[Code] = MAT.[ClientCode]
                     ON MAT.[CODE] = NR.[Case]
  END

END
GO

DECLARE @COMMAND VARCHAR(8000)

IF EXISTS(SELECT * 
            FROM sysobjects SO
                 INNER JOIN syscolumns SC
                         ON SC.[id] = SO.[id]
                        AND SC.[name] = 'Handler'
           WHERE SO.[name] = 'Undertakings'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDHFUndertakings
 *
 * Get Handler Undertakings in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDHFUndertakings]
       (@handler  varchar(10))
RETURNS @ML TABLE
       ([MATTER]                    varchar(20),
        [SEQ]                       int,
        [DATE]                      datetime,
        [DISCHARGEDATENO]           int,
        [DISCHARGEDATEDATE]         datetime,
        [TYPE]                      varchar(1),
        [DESCRIPTION]               varchar(400),
        [WHO]                       varchar(200),
        [VALUE]                     decimal(13,2),
        [RECORDID]                  int,
        [ActionID]                  int,
        [GivenOrReceived]           varchar(1),
        [Handler]                   varchar(10),
        [UndertakingTo]             varchar(10),
        [Status]                    varchar(30),
        [DealingNumber]             varchar(40),
        [DischargedBy]              varchar(10),
        [Notified]                  varchar(1),
        [EntryDate]                 datetime)
AS
BEGIN
  INSERT
    INTO @ML
        ([MATTER],
         [SEQ],
         [DATE],
         [DISCHARGEDATENO],
         [DISCHARGEDATEDATE],
         [TYPE],
         [DESCRIPTION],
         [WHO],
         [VALUE],
         [RECORDID],
         [ActionID],
         [GivenOrReceived],
         [Handler],
         [UndertakingTo],
         [Status],
         [DealingNumber],
         [DischargedBy],
         [Notified],
         [EntryDate])
  SELECT UND.[MATTER],
         UND.[SEQ],
         UND.[UNDDATE],
         NULL,
         UND.[DISCHARGEDATE],
         UND.[TYPE],
         UND.[DESCRIPTION],
         UND.[WHO],
         UND.[UNDVALUE],
         UND.[RECORDID],
         UND.[ActionID],
         UND.[GivenOrReceived],
         UND.[Handler],
         UND.[CaseContact],
         UND.[Status],
         UND.[DealingNumber],
         UND.[DischargedBy],
         UND.[Notified],
         UND.[EntryDate]
    FROM [dbo].[Undertakings] UND
         INNER JOIN [dbo].[matters] MAT
                 ON MAT.[CODE] = UND.[MATTER]
                AND IsNull(MAT.[Closed], '''') <> ''Y''
   WHERE UND.[Handler] = @Handler
   
   RETURN
END'

EXEC (@COMMAND)

END

IF EXISTS(SELECT * 
            FROM sysobjects SO
                 INNER JOIN syscolumns SC
                         ON SC.[id] = SO.[id]
                        AND SC.[name] = 'AuthorisedByFE'
           WHERE SO.[name] = 'Undertakings'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDHFUndertakings
 *
 * Get Handler Undertakings in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDHFUndertakings]
       (@handler  varchar(10))
RETURNS @ML TABLE
       ([MATTER]                    varchar(20),
        [SEQ]                       int,
        [DATE]                      datetime,
        [DISCHARGEDATENO]           int,
        [DISCHARGEDATEDATE]         datetime,
        [TYPE]                      varchar(1),
        [DESCRIPTION]               varchar(400),
        [WHO]                       varchar(200),
        [VALUE]                     decimal(13,2),
        [RECORDID]                  int,
        [ActionID]                  int,
        [GivenOrReceived]           varchar(1),
        [Handler]                   varchar(10),
        [UndertakingTo]             varchar(10),
        [Status]                    varchar(30),
        [DealingNumber]             varchar(40),
        [DischargedBy]              varchar(10),
        [Notified]                  varchar(1),
        [EntryDate]                 datetime)
AS
BEGIN
  INSERT
    INTO @ML
        ([MATTER],
         [SEQ],
         [DATE],
         [DISCHARGEDATENO],
         [DISCHARGEDATEDATE],
         [TYPE],
         [DESCRIPTION],
         [WHO],
         [VALUE],
         [RECORDID],
         [ActionID],
         [GivenOrReceived],
         [Handler],
         [UndertakingTo],
         [Status],
         [DealingNumber],
         [DischargedBy],
         [Notified],
         [EntryDate])
  SELECT UND.[MATTER],
         UND.[SEQ],
         UND.[DATE],
         UND.[DISCHARGEDATE],
         NULL,
         UND.[TYPE],
         UND.[DESCRIPTION],
         UND.[WHO],
         UND.[VALUE],
         UND.[RECORDID],
         UND.[ActionID],
         UND.[GivenOrReceived],
         UND.[AuthorisedByFE],
         UND.[UndertakingTo],
         UND.[Status],
         UND.[DealingNumber],
         UND.[DischargedBy],
         UND.[Notified],
         NULL
    FROM [dbo].[Undertakings] UND
   WHERE UND.[AuthorisedByFE] = @Handler
   
   RETURN
END'

EXEC (@COMMAND)

END

GO

DECLARE @COMMAND VARCHAR(8000)

IF EXISTS(SELECT * 
            FROM sysobjects SO
                 INNER JOIN syscolumns SC
                         ON SC.[id] = SO.[id]
                        AND SC.[name] = 'Handler'
           WHERE SO.[name] = 'Undertakings'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDMTUndertakings
 *
 * Get Matter Undertakings in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDMTUndertakings]
       (@matter  varchar(20))
RETURNS @ML TABLE
       ([MATTER]                    varchar(20),
        [SEQ]                       int,
        [DATE]                      datetime,
        [DISCHARGEDATENO]           int,
        [DISCHARGEDATEDATE]         datetime,
        [TYPE]                      varchar(1),
        [DESCRIPTION]               varchar(400),
        [WHO]                       varchar(200),
        [VALUE]                     decimal(13,2),
        [RECORDID]                  int,
        [ActionID]                  int,
        [GivenOrReceived]           varchar(1),
        [Handler]                   varchar(10),
        [UndertakingTo]             varchar(10),
        [Status]                    varchar(30),
        [DealingNumber]             varchar(40),
        [DischargedBy]              varchar(10),
        [Notified]                  varchar(1),
        [EntryDate]                 datetime)
AS
BEGIN
  INSERT
    INTO @ML
        ([MATTER],
         [SEQ],
         [DATE],
         [DISCHARGEDATENO],
         [DISCHARGEDATEDATE],
         [TYPE],
         [DESCRIPTION],
         [WHO],
         [VALUE],
         [RECORDID],
         [ActionID],
         [GivenOrReceived],
         [Handler],
         [UndertakingTo],
         [Status],
         [DealingNumber],
         [DischargedBy],
         [Notified],
         [EntryDate])
  SELECT UND.[MATTER],
         UND.[SEQ],
         UND.[UNDDATE],
         NULL,
         UND.[DISCHARGEDATE],
         UND.[TYPE],
         UND.[DESCRIPTION],
         UND.[WHO],
         UND.[UNDVALUE],
         UND.[RECORDID],
         UND.[ActionID],
         UND.[GivenOrReceived],
         UND.[Handler],
         UND.[CaseContact],
         UND.[Status],
         UND.[DealingNumber],
         UND.[DischargedBy],
         UND.[Notified],
         UND.[EntryDate]
    FROM [dbo].[Undertakings] UND
   WHERE UND.[MATTER] = @matter
   
   RETURN
END'

EXEC (@COMMAND)

END

IF EXISTS(SELECT * 
            FROM sysobjects SO
                 INNER JOIN syscolumns SC
                         ON SC.[id] = SO.[id]
                        AND SC.[name] = 'AuthorisedByFE'
           WHERE SO.[name] = 'Undertakings'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDMTUndertakings
 *
 * Get Matter Undertakings in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDMTUndertakings]
       (@matter  varchar(20))
RETURNS @ML TABLE
       ([MATTER]                    varchar(20),
        [SEQ]                       int,
        [DATE]                      datetime,
        [DISCHARGEDATENO]           int,
        [DISCHARGEDATEDATE]         datetime,
        [TYPE]                      varchar(1),
        [DESCRIPTION]               varchar(400),
        [WHO]                       varchar(200),
        [VALUE]                     decimal(13,2),
        [RECORDID]                  int,
        [ActionID]                  int,
        [GivenOrReceived]           varchar(1),
        [Handler]                   varchar(10),
        [UndertakingTo]             varchar(10),
        [Status]                    varchar(30),
        [DealingNumber]             varchar(40),
        [DischargedBy]              varchar(10),
        [Notified]                  varchar(1),
        [EntryDate]                 datetime)
AS
BEGIN
  INSERT
    INTO @ML
        ([MATTER],
         [SEQ],
         [DATE],
         [DISCHARGEDATENO],
         [DISCHARGEDATEDATE],
         [TYPE],
         [DESCRIPTION],
         [WHO],
         [VALUE],
         [RECORDID],
         [ActionID],
         [GivenOrReceived],
         [Handler],
         [UndertakingTo],
         [Status],
         [DealingNumber],
         [DischargedBy],
         [Notified],
         [EntryDate])
  SELECT UND.[MATTER],
         UND.[SEQ],
         UND.[DATE],
         UND.[DISCHARGEDATE],
         NULL,
         UND.[TYPE],
         UND.[DESCRIPTION],
         UND.[WHO],
         UND.[VALUE],
         UND.[RECORDID],
         UND.[ActionID],
         UND.[GivenOrReceived],
         UND.[AuthorisedByFE],
         UND.[UndertakingTo],
         UND.[Status],
         UND.[DealingNumber],
         UND.[DischargedBy],
         UND.[Notified],
         NULL
    FROM [dbo].[Undertakings] UND
   WHERE UND.[MATTER] = @matter
   
   RETURN
END'

EXEC (@COMMAND)

END

GO

DECLARE @COMMAND VARCHAR(8000)

IF EXISTS(SELECT * 
            FROM sysobjects SO
           WHERE SO.[name] = 'BillHeader'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDHFCountDraftInvoices
 *
 * Get Handler Draft Invoices in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDHFCountDraftInvoices]
       (@handler  varchar(10))
RETURNS @ML TABLE
       ([TOTAL]                     int)
AS
BEGIN

  INSERT
    INTO @ML
        ([TOTAL])
  SELECT COUNT(1) AS [TOTAL]
    FROM [dbo].[matters] MAT
         INNER JOIN [dbo].[BillHeader] BIH
                 ON BIH.[MATTER] = MAT.[CODE]
                AND ISNULL(BIH.[BILLNO], 0) = 0
   WHERE MAT.[FECode] = @HANDLER
   
  RETURN
END'

EXEC (@COMMAND)

END

IF EXISTS(SELECT * 
            FROM sysobjects SO
           WHERE SO.[name] = 'Billhead'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDHFCountDraftInvoices
 *
 * Get Handler Draft Invoices in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDHFCountDraftInvoices]
       (@handler  varchar(10))
RETURNS @ML TABLE
       ([TOTAL]                     int)
AS
BEGIN

  INSERT
    INTO @ML
        ([TOTAL])
  SELECT COUNT(1) AS [TOTAL]
    FROM [dbo].[matters] MAT
         INNER JOIN [dbo].[BillHead] BIH
                 ON BIH.[MATTERCODE] = MAT.[CODE]
                AND ISNULL(BIH.[INVOICENO], 0) = 0
   WHERE MAT.[FECode] = @HANDLER
   
  RETURN
END'

EXEC (@COMMAND)

END

GO

DECLARE @COMMAND VARCHAR(8000)

IF EXISTS(SELECT * 
            FROM sysobjects SO
           WHERE SO.[name] = 'FeBudgets'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDHFBudgets
 *
 * Get Handler Budgets in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDHFBudgets]
       (@handler  varchar(10),
        @year     int,
        @month    int)
RETURNS @ML TABLE
       ([Handler]                   varchar(10),
        [Year]                      int,
        [Month]                     int,
        [FeesBudget]                decimal(18, 2),
        [ChargableTimeBudget]       decimal(18, 2),
        [NonChargableTimeBudget]    decimal(18, 2))
AS
BEGIN

INSERT
  INTO @ML
      ([Handler],
       [Year],
       [Month],
       [FeesBudget],
       [ChargableTimeBudget],
       [NonChargableTimeBudget])
select FEB.[FeCode],
       FEB.[Year],
       FEB.[Period],
       FEB.[BudgetFees],
       FEB.[BudgetHours],
       FEB.[NonBillable]
  from [dbo].[FeBudgets] FEB
 where FEB.[FeCode] = @handler
   and FEB.[Year] = @year
   and FEB.[Period] = @month

RETURN

END'

EXEC (@COMMAND)

END

IF EXISTS(SELECT * 
            FROM sysobjects SO
           WHERE SO.[name] = 'HandlerBudgets'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDHFBudgets
 *
 * Get Handler Budgets in a standardised format so this works both in SAM4 and in SAM3.5
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDHFBudgets]
       (@handler  varchar(10),
        @year     int,
        @month    int)
RETURNS @ML TABLE
       ([Handler]                   varchar(10),
        [Year]                      int,
        [Month]                     int,
        [FeesBudget]                decimal(18, 2),
        [ChargableTimeBudget]       decimal(18, 2),
        [NonChargableTimeBudget]    decimal(18, 2))
AS
BEGIN

INSERT
  INTO @ML
      ([Handler],
       [Year],
       [Month],
       [FeesBudget],
       [ChargableTimeBudget],
       [NonChargableTimeBudget])
select HAB.[Handler],
       HAB.[Year],
       HAB.[Month],
       HAB.[FeesBudget],
       HAB.[ChargableTimeBudget],
       HAB.[NonChargableTimeBudget]
  from [dbo].[HandlerBudgets] HAB
 where HAB.[Handler] = @handler
   and HAB.[Year] = @year
   and HAB.[Month] = @month

RETURN

END'

EXEC (@COMMAND)

END


GO

/**************************************************************************************
 *
 * ky_WDHandlerTimeBudgetDashboard
 *
 * Returns Time Entry data for a handler and a particular date.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDHandlerTimeBudgetDashboard]
      (@dateS varchar(8),
       @handler varchar(10),
       @width int)
AS
BEGIN

DECLARE @date datetime
DECLARE @startofmonth datetime
DECLARE @endofmonth datetime

SET @date = convert(datetime, @dateS)

set @startofmonth = DateAdd(DD, -day(@date) + 1, @date)
set @endofmonth = Dateadd(MM, 1, @startofmonth)
set @date = dateadd(DD, 1, @date)

SELECT TRX.[ChargeableWidth],
       TRX.[NonChargeableWidth],
       @width - TRX.[ChargeableWidth] - TRX.[NonChargeableWidth] AS [RemainingWidth],
       TRX.[Handler],
       TRX.[ChargeableTimeBudget],
       convert(varchar(3), convert(int, TRX.[ChargeableTimeBudget] / 60)) +
         ':' +
         Right(convert(varchar(3), 100 + TRX.[ChargeableTimeBudget] - (60 * convert(int, TRX.[ChargeableTimeBudget] / 60))), 2) As [DisplayBudget],
       TRX.[TotalTime],
       convert(varchar(3), convert(int, TRX.[TotalTime] / 60)) +
         ':' +
         Right(convert(varchar(3), 100 + TRX.[TotalTime] - (60 * convert(int, TRX.[TotalTime] / 60))), 2) As [DisplayTotalTime],
       TRX.[TotalChargeable],
       convert(varchar(3), convert(int, TRX.[TotalChargeable] / 60)) +
         ':' +
         Right(convert(varchar(3), 100 + TRX.[TotalChargeable] - (60 * convert(int, TRX.[TotalChargeable] / 60))), 2) As [DisplayTotalChargeable],
       TRX.[TotalNonChargeable],
       convert(varchar(3), convert(int, TRX.[TotalNonChargeable] / 60)) +
         ':' +
         Right(convert(varchar(3), 100 + TRX.[TotalNonChargeable] - (60 * convert(int, TRX.[TotalNonChargeable] / 60))), 2) As [DisplayTotalNonChargeable]
  FROM (SELECT CASE WHEN DB.[ChargeableTimeBudget] = 0
                         THEN @width
                    ELSE convert(int, (DB.[TotalChargeable] / DB.[ChargeableTimeBudget]) * @width) END AS [ChargeableWidth],
               CASE WHEN DB.[ChargeableTimeBudget] = 0
                         THEN 0
                    ELSE convert(int, (DB.[TotalNonChargeable] / DB.[ChargeableTimeBudget]) * @width) END AS [NonChargeableWidth],
               DB.*
          FROM (SELECT @handler AS [Handler],
                       CASE WHEN MB.[ChargeableTimeBudget] < TM.[TotalChargeable]
                                 THEN TM.[TotalChargeable]
                            ELSE MB.[ChargeableTimeBudget] END AS [ChargeableTimeBudget],
                       TM.[TotalTime],
                       TM.[TotalChargeable],
                       CASE WHEN MB.[ChargeableTimeBudget] < TM.[TotalChargeable]
                                 THEN 0
                            WHEN MB.[ChargeableTimeBudget] < TM.[TotalChargeable] + TM.[TotalNonChargeable]
                                 THEN MB.[ChargeableTimeBudget] - TM.[TotalChargeable]
                            ELSE TM.[TotalNonChargeable] END AS [TotalNonChargeable]
                  FROM (select 60 * IsNull(SUM(HB.[ChargableTimeBudget]), 0) As [ChargeableTimeBudget] 
                          from [dbo].[ky_WDHFBudgets](@handler, YEAR(@dateS), MONTH(@DateS)) HB) MB
                       CROSS APPLY (SELECT IsNull(SUM(TR.[TIME]), 0) AS [TotalTime],
                                           IsNull(SUM(CASE WHEN TR.[REC_IRR] = 'N'
                                                                THEN 0
                                                           ELSE TR.[TIME] END), 0) AS [TotalChargeable],
                                           IsNull(SUM(CASE WHEN TR.[REC_IRR] = 'N'
                                                                THEN TR.[TIME]
                                                           ELSE 0 END), 0) AS [TotalNonChargeable]
                                      FROM [dbo].[TimeEntry] TR
                                     WHERE TR.[FEEEARN] = @handler
                                       AND TR.[TIMEORCHARGE] = 'T'
                                       AND TR.[DATE] >= @startofmonth
                                       AND TR.[DATE] < @date) TM) DB) TRX
END
GO

DECLARE @COMMAND VARCHAR(8000)

IF EXISTS(SELECT * 
            FROM sysobjects SO
           WHERE SO.[name] = 'MatterLedger'
             AND SO.[xtype] = 'U')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDMatLedger
 *
 * Lists Matter Ledger. With support for Paging.
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDMatLedger]
       (@casecode varchar(20),
        @startno  int,
        @count    int)
RETURNS @ML TABLE
       ([mlid]                  int               IDENTITY(1, 1),
        [DATE]                  varchar(11),
        [REF]                   varchar(20),
        [NARR]                  varchar(300),
        [VALUED]                decimal(17,2),
        [VALUEO]                decimal(17,2),
        [VALUECC]               decimal(17,2),
        [VALUECD]               decimal(17,2),
        [BATCHNO]               int,
        [PREF]                  int,
        [UNDERTAKING]           varchar(1),
        [FEE]                   varchar(10))
AS
BEGIN

INSERT
  INTO @ML
      ([DATE],
       [REF],
       [NARR],
       [VALUED],
       [VALUEO],
       [VALUECC],
       [VALUECD],
       [BATCHNO],
       [PREF],
       [UNDERTAKING],
       [FEE])
  select CONVERT(varchar, ML.[DATE], 106),
         RTrim(IsNull(ML.[REF], '''')) AS [REF],
         RTrim(IsNull(ML.[NARR], '''')) AS [NARR],
         IsNull(ML.[VALUED], 0) AS [VALUED],
         IsNull(ML.[VALUEO], 0) AS [VALUEO],
         IsNull(ML.[VALUECC], 0) AS [VALUECC],
         IsNull(ML.[VALUECD], 0) AS [VALUECD],
         IsNull(ML.[BATCHNO], 0) AS [BATCHNO],
         IsNull(ML.[PREF], 0) AS [PREF],
         IsNull(MAT.[UNDERTAKING], ''N'') AS [UNDERTAKING],
         RTrim(IsNull(ML.[FEE], '''')) AS [FEE]
    from [dbo].[MatterLedger] ML 
         LEFT OUTER JOIN [dbo].[matters] MAT
                      ON MAT.[code] = ML.[MATTER]
   where ML.[MATTER] = @CASECODE
ORDER BY ML.[DATE] ASC,
         ML.[BATCHNO] ASC,
         ML.[LREF] ASC

    DELETE @ML
     WHERE [mlid] < @startno

    DELETE @ML
     WHERE [mlid] > (@startno + @count - 1)

RETURN

END'

EXEC (@COMMAND)
END

IF EXISTS(SELECT * 
            FROM sysobjects SO
           WHERE SO.[name] = 'MatterLedger'
             AND SO.[xtype] = 'V')
BEGIN
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDMatLedger
 *
 * Lists Matter Ledger. With support for Paging.
 *
 **************************************************************************************/
 CREATE FUNCTION
        [dbo].[ky_WDMatLedger]
       (@casecode varchar(20),
        @startno  int,
        @count    int)
RETURNS @ML TABLE
       ([mlid]                  int               IDENTITY(1, 1),
        [DATE]                  varchar(11),
        [REF]                   varchar(20),
        [NARR]                  varchar(300),
        [VALUED]                decimal(17,2),
        [VALUEO]                decimal(17,2),
        [VALUECC]               decimal(17,2),
        [VALUECD]               decimal(17,2),
        [BATCHNO]               int,
        [PREF]                  int,
        [UNDERTAKING]           varchar(1),
        [FEE]                   varchar(10))
AS
BEGIN

INSERT
  INTO @ML
      ([DATE],
       [REF],
       [NARR],
       [VALUED],
       [VALUEO],
       [VALUECC],
       [VALUECD],
       [BATCHNO],
       [PREF],
       [UNDERTAKING],
       [FEE])
  select CONVERT(varchar, ML.[TransDate], 106),
         RTrim(IsNull(ML.[TransRef], '''')) AS [REF],
         RTrim(IsNull(ML.[Narrative], '''')) AS [NARR],
         IsNull(ML.[DebtorsValue], 0) AS [VALUED],
         IsNull(ML.[OutlayValue], 0) AS [VALUEO],
         IsNull(ML.[ClientCurrent], 0) AS [VALUECC],
         IsNull(ML.[ClientDeposit], 0) AS [VALUECD],
         IsNull(ML.[BatchNo], 0) AS [BATCHNO],
         IsNull(ML.[PostRef], 0) AS [PREF],
         IsNull(MAT.[UNDERTAKING], ''N'') AS [UNDERTAKING],
         RTrim(IsNull(MAT.[FECode], '''')) AS [FEE]
    from [dbo].[MatterLedger] ML 
         LEFT OUTER JOIN [dbo].[matters] MAT
                      ON MAT.[code] = ML.[MatterCode]
   where ML.[MatterCode] = @CASECODE
ORDER BY ML.[TransDate] ASC,
         ML.[BATCHNO] ASC,
         ML.[PostRef] ASC

    DELETE @ML
     WHERE [mlid] < @startno

    DELETE @ML
     WHERE [mlid] > (@startno + @count - 1)

RETURN

END'

EXEC (@COMMAND)
END

GO

DECLARE @COMMAND varchar(8000)
DECLARE @ChargeField varchar(10)
DECLARE @Units int

IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeDayBook'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'CHARGE')
BEGIN
  SET @ChargeField = 'Charge'
END
ELSE
BEGIN
  SET @ChargeField = 'CHARGED'
END

IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeDayBook'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'UNITS')
BEGIN
  SET @Units = 1
END
ELSE
BEGIN
  SET @Units = 0
END
  
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDSetTimeDayBookRateCharge
 *
 * Sets the Rate and Charge values according to the Charge Out Rates indicators and/or
 *     the Task Code used in the TimeDayBook.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDSetTimeDayBookRateCharge]
      (@recordid int)
AS
BEGIN
UPDATE TDB
   SET TDB.[Time] = Ceiling(TDB.[Time] / IsNull(TUT.[NumValue], 1)) * IsNull(TUT.[NumValue], 1),
       TDB.[RATE] = 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,
       TDB.[' + @ChargeField + '] = Convert(numeric(7, 2),
                              (  (  Ceiling(TDB.[Time] / IsNull(TUT.[NumValue], 1))
                                  * IsNull(TUT.[NumValue], 1)
                                  * 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))' +
       CASE WHEN @Units = 0
                 THEN ''
            ELSE ',
       TDB.[Units] = Ceiling(TDB.[Time] / IsNull(TUT.[NumValue], 1))' END + '
  from [dbo].[TimeDayBook] TDB
       LEFT OUTER JOIN [dbo].[matters] MAT
                       INNER JOIN [dbo].[contacts] CON
                               ON CON.[Code] = MAT.[ClientCode]
                    ON MAT.[code] = TDB.[MATTER]
       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] = TDB.[MATTER]) 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' + 
       CASE WHEN @Units = 0
                 THEN '
       OUTER APPLY (SELECT 1 AS [NumValue]) TUT'
            ELSE '
       OUTER APPLY (SELECT CTN.[NumValue]
                      FROM [dbo].[CtrlNum] CTN
                     WHERE CTN.[Code] = ''TimeUnit'') TUT' END + '
       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.[RECORDID] = @RECORDID

END'

EXEC (@COMMAND)

GO

/**************************************************************************************
 *
 * ky_WDReleaseAction_DiaryDel
 *
 * Step 1 of assigning an Action: release the Diary Delegation record
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDReleaseAction_DiaryDel]
      (@ActionID int,
       @Handler varchar(10),
       @RESULT int OUTPUT)
AS
BEGIN

  DECLARE @DATETIME DATETIME

  SET @DATETIME = GETDATE()

  SET @RESULT = 0

  BEGIN TRY
    BEGIN
      UPDATE DEL  
         SET DEL.[Owner] = 'N',
             DEL.[Status] = 1,
             DEL.[dater] = convert(DATETIME, REPLACE(CONVERT(VARCHAR, @DATETIME, 112), '-', '')),
             DEL.[timer] = [dbo].[ky_ConvertTimeToClarion](@DATETIME),
             DEL.[DelegateStatus] = 1
        FROM [dbo].[DiaryDelegations] DEL
       WHERE DEL.[ACTIONID] = @ActionID 
         AND DEL.[HANDLER] = @HANDLER
         AND DEL.[STATUS] = 0
    END
  END TRY
  BEGIN CATCH
    SET @RESULT = -1
  END CATCH
   
  IF (@@ERROR <> 0)
    BEGIN
      SET @RESULT = -1
    END
   
END
GO

/**************************************************************************************
 *
 * ky_WDAssignAction_DiaryDel
 *
 * Step 2 of assigning an Action: write a new Diary Delegation record
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDAssignAction_DiaryDel]
      (@ActionID int,
       @AssignNo int,
       @Handler varchar(10),
       @AssignTo varchar(10),
       @Release int,
       @RESULT int OUTPUT)
AS
BEGIN

  SET @RESULT = 0

  BEGIN TRY
    BEGIN
      INSERT
        INTO [dbo].[DiaryDelegations] 
            ([ActionID],
             [DATE],
             [Handler],
             [TEAM],
             [TIME],
             [OWNER],
             [DELTYPE],
             [Status],
             [DueDate],
             [DueTime],
             [ActionType],
             [FromHandler])
      SELECT DIA.[ActionID] As [ActionID],
             DEL1.[DATE] As [DATE],
             RES.[CODE] As [Handler],
             CASE RTRIM(IsNull(RES.[TEAMCODE], 'N'))
                  WHEN 'Y' 
                       THEN RES.[CODE]
                  ELSE RES.[TEAM] END AS [TEAM],
             [dbo].[ky_ConvertTimeToClarion]([dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL1.[DATE], DEL1.[TIME])) As [TIME],
             CASE WHEN ((@Release = 1) AND (@Handler = DIA.[FNCODE]))
                       THEN 'Y'
                  ELSE 'N' END AS [OWNER],
             CASE WHEN ((@Release = 1) AND (@Handler = DIA.[FNCODE]))
                       THEN 'Released'
                  ELSE 'Delegated' END AS [DELTYPE],
             0 As [Status],
             DEL1.[DATE] As [DueDate],
             [dbo].[ky_ConvertTimeToClarion]([dbo].[ky_ConvertDateAndClarionTimeToDateTime](DEL1.[DATE], DEL1.[TIME])) As [DueTime],
             DIA.[ACTIONTYPE] AS [ActionType],
             @Handler As [FromHandler]
        FROM [dbo].[diary] DIA
             INNER JOIN [dbo].[DiaryDelegations] DEL1
                     ON DEL1.[AssignNo] = @AssignNo
                    AND DEL1.[ACTIONID] = @ActionID
             INNER JOIN [dbo].[Handlers] RES
                     ON RES.[CODE] = @AssignTo 
       WHERE DIA.[ACTIONID] = @ActionID 
    END
  END TRY
  BEGIN CATCH
    SET @RESULT = -1
  END CATCH
   
  IF (@@ERROR <> 0)
    BEGIN
      SET @RESULT = -1
    END
   
END
GO

/**************************************************************************************
 *
 * ky_WDUpdateAction_DiaryDel
 *
 * Step 3 of assigning an Action: update the Diary record
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateAction_DiaryDel]
      (@ActionID int,
       @AssignNo int,
       @Handler varchar(10),
       @AssignTo varchar(10),
       @Release int,
       @RESULT int OUTPUT)
AS
BEGIN
  
  SET @RESULT = 0
  
  BEGIN TRY
    BEGIN
      UPDATE DIA 
         SET DIA.[DELEGATIONSTATUS] = CASE WHEN ((@Release = 1) AND (@Handler = DIA.[FNCODE]))
                                                THEN 0
                                           ELSE 1 END,
             DIA.[FNCODE] = CASE WHEN ((@Release = 1) AND (@Handler = DIA.[FNCODE]))
                                      THEN @AssignTo 
                                 ELSE DIA.[FNCODE] END,
             DIA.[DATE] = CASE WHEN ((@Release = 1) AND (@Handler = DIA.[FNCODE]))
                                    THEN Convert(datetime, Replace(CONVERT(varchar, getDate(), 112), '-', ''))
                               ELSE DIA.[DATE] END,
             DIA.[TEAMCODE] = CASE RTRIM(IsNull(RES.[TEAMCODE], 'N'))
                                   WHEN 'Y' 
                                        THEN RES.[CODE]
                                   ELSE RES.[TEAM] END,
             DIA.[DELEGATEDFNR] = @AssignTo,
             DIA.[DELEGATEDDATE] = Convert(datetime, Replace(CONVERT(varchar, getDate(), 112), '-', ''))
        FROM [dbo].[diary] DIA
             INNER JOIN [dbo].[Handlers] RES
                     ON RES.[CODE] = @AssignTo 
       WHERE DIA.[ACTIONID] = @ActionID
    END
  END TRY
  BEGIN CATCH
    SET @RESULT = -1
  END CATCH
    
  IF (@@ERROR <> 0)
    BEGIN
      SET @RESULT = -1
    END
END
GO


/**************************************************************************************
 *
 * ky_WDDelegateAction_DiaryDel
 *
 * Delegate an action. This is performed in 4 steps:
 * 1) If requested, the action is released.
 * 2) The action is delegated
 * 3) The action is updated
 * 4) An alarm is set
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDDelegateAction_DiaryDel]
      (@ActionID int,
       @AssignNo int,
       @Handler varchar(10),
       @AssignTo varchar(10),
       @Release int)
AS
BEGIN

DECLARE @AIDParm varchar(50)
DECLARE @RESULT int

BEGIN TRANSACTION

SET @RESULT = 0

IF (@Release = 1)
  BEGIN
    BEGIN TRY
      BEGIN
        EXEC [dbo].[ky_WDReleaseAction_DiaryDel] @ActionId,
                                                 @Handler,
                                                 @RESULT OUTPUT

        IF (@@ERROR <> 0)
          BEGIN
            SET @RESULT = -1
          END

      END
    END TRY
    BEGIN CATCH
      SET @RESULT = -1
    END CATCH
  END

IF (@RESULT = 0)
  BEGIN
    BEGIN TRY
      BEGIN  
        EXEC [dbo].[ky_WDAssignAction_DiaryDel] @ActionId,
                                                @AssignNo,
                                                @Handler,
                                                @AssignTo,
                                                @Release,
                                                @RESULT OUTPUT
        IF (@@ERROR <> 0)
          BEGIN
            SET @RESULT = -1
          END

      END
    END TRY
    BEGIN CATCH
      SET @RESULT = -1
    END CATCH
  END

IF (@RESULT = 0)
  BEGIN
    BEGIN TRY
      BEGIN  
        EXEC [dbo].[ky_WDUpdateAction_DiaryDel] @ActionId,
                                                @AssignNo,
                                                @Handler,
                                                @AssignTo,
                                                @Release,
                                                @RESULT OUTPUT
        IF (@@ERROR <> 0)
          BEGIN
            SET @RESULT = -1
          END

      END
    END TRY
    BEGIN CATCH
      SET @RESULT = -1
    END CATCH
  END

IF (@RESULT = 0)
  BEGIN
    BEGIN TRY
      BEGIN
        SET @AIDParm = convert(varchar(50), @ActionID)

        IF (@@ERROR <> 0)
          BEGIN
            SET @RESULT = -1
          END

        EXEC [dbo].[ky_AddAlarmDelegate] @AIDParm, @AssignTo

        IF (@@ERROR <> 0)
          BEGIN
            SET @RESULT = -1
          END

      END
    END TRY
    BEGIN CATCH
      SET @RESULT = -1
    END CATCH
  END

  IF (@RESULT = 0)
    COMMIT
  ELSE
	ROLLBACK

END
GO

DECLARE @command varchar(2000)

IF EXISTS (SELECT sc.[name]
             from sysobjects so
                  inner join syscolumns sc
                          on sc.[id] = so.[id]
                         and sc.[name] = 'AuthorisationRequired'
            where so.[name] = 'TemplateActions')
  BEGIN
    SET @command = 'CREATE FUNCTION
       [dbo].[ky_WDActionAuthorisedToComplete]
      (@ActionID        int,
       @CurFee          varchar(10))
RETURNS @DV TABLE
       ([IsAuthorisedToComplete]         int)
AS
BEGIN

INSERT
  INTO @DV
      ([IsAuthorisedToComplete])
SELECT CASE RTRIM(ISNULL(TAC.[AuthorisationRequired], ''L''))
            WHEN '''' 
                 THEN convert(int, 0)
            WHEN ''L'' 
                 THEN convert(int, 0)
            WHEN ''C''
                 THEN CASE WHEN RTRIM(ISNULL(MAT.[FECode], '''')) = @CurFee
                                THEN CONVERT(int, 0)
                           ELSE CONVERT(int, 1) END
            WHEN ''P''
                 THEN CASE WHEN RTRIM(ISNULL(MAT.[Partner], '''')) = @CurFee
                                THEN CONVERT(int, 0)
                           ELSE CONVERT(int, 2) END
            WHEN ''F''
                 THEN CASE WHEN RTRIM(ISNULL(CNT.[FE], '''')) = @CurFee
                                THEN CONVERT(int, 0)
                           ELSE CONVERT(int, 3) END
            WHEN ''A''
                 THEN CASE WHEN RTRIM(ISNULL(FHA.[Type], '''')) = ''P''
                                THEN CONVERT(int, 0)
                           ELSE CONVERT(int, 4) END
            WHEN ''O''
                 THEN CASE WHEN RTRIM(ISNULL(FHA.[Type], '''')) = ''P''
                                THEN CONVERT(int, 0)
                           ELSE CONVERT(int, 5) END
            ELSE convert(int, 6) END AS [IsAuthorisedToComplete]
  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

RETURN

END'
  END
ELSE
  BEGIN
    SET @command = 'CREATE FUNCTION
       [dbo].[ky_WDActionAuthorisedToComplete]
      (@ActionID        int,
       @CurFee          varchar(10))
RETURNS @DV TABLE
       ([IsAuthorisedToComplete]         int)
AS
BEGIN

INSERT
  INTO @DV
      ([IsAuthorisedToComplete])
VALUES(1)

RETURN

END'
END

EXEC (@command)
GO

CREATE FUNCTION
       [dbo].[ky_WDActionCheckDependentActions]
      (@ActionID        int)
RETURNS @DV TABLE
       ([ErrorMessage]         varchar(1000))
AS
BEGIN

INSERT
  INTO @DV
      ([ErrorMessage])
SELECT CONVERT(varchar(1000),
               LTRIM(  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

RETURN

END
GO

/**************************************************************************************
 *
 * ky_WDNextActionMissingCasePartner
 *
 * Check that no "Next Actions" would require being assigned to a matter's missing Partner.
 * This check can be performed BEFORE any database changes are in progress, so that we can
 * ignore this eventuality in procedures that make actual database changes. 
 *
 * It checks the TemplateAction's column AssignActionTo, and if this contains a 'P', i.e.
 *   "assign the Action to the Partner associated with this Case", it goes and checks
 *   whether the Partner column in the matter has been set.
 *
 * It returns the number of rows that failed this test, so
 *   the desired result is to receive 0 in the TOTAL column.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDNextActionMissingCasePartner]
      (@ActionID int,
       @CurFee varchar(10),
       @NextActionsXML varchar(4000))
AS
BEGIN
DECLARE @Owner int

DECLARE @IsAuthorisedToComplete int
DECLARE @CountFailedDependentActions int
DECLARE @idoc int

/* This is irrelevant if the current fee earner isn't the owner. */
SELECT @Owner = CASE DIA.[FNCODE] 
                     WHEN @CurFee
                          THEN 1
                     ELSE 0 END
  FROM [dbo].[Diary] DIA
 WHERE DIA.[ACTIONID] = @ActionID

/* 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)

/* 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)
  
/* Example of @NextActionsXML:
   <NA>
     <NextAction>
       <Process>Y</Process>
       <Decision>Do</Decision>
       <Code>XXX</Code>
     </NextAction>
     <NextAction>
       <Process>Y</Process>
       <Decision>Do not</Decision>
       <Code>YYY</Code>
     </NextAction>
     <NextAction>
       <Process>N</Process>
       <Decision>Do</Decision>
       <Code>ZZZ</Code>
     </NextAction>
   </NA>
*/

EXEC sp_xml_preparedocument @idoc OUTPUT, @NextActionsXML 

SELECT COUNT(1) As [TOTAL]
  from OPENXML(@idoc, 'NA/NextAction', 2)
          WITH(Process   varchar(1)    'Process',
               Decision  varchar(10)   'Decision',
               Code      varchar(5)    'Code') 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'
   AND @Owner = 1
   AND @CountFailedDependentActions = 0
   AND @IsAuthorisedToComplete = 0

EXEC sp_xml_removedocument @idoc

END
GO

/**************************************************************************************
 *
 * ky_WDActionComplete
 *
 * Completes / Returns an Action - depending on whether this SP is invoked by the owner
 *   or a delegate.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDActionComplete]
      (@ActionID int,
       @CurFee varchar(10),
       @NextActionsXML varchar(4000))
AS
BEGIN

DECLARE @Now datetime
DECLARE @NowDateOnly datetime
DECLARE @NowClarionTime 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 @NA TABLE
       ([ID]          int identity(1, 1),
        [ActionID]    int,
        [Code]        varchar(5))

DECLARE @AlarmType int
DECLARE @DisabledAlarmStatusID int
DECLARE @ActionTypeID int

SELECT @AlarmType = ISNULL(ALT1.[TypeID], ALT2.[TypeID])
  FROM AlarmTypes ALT2
       LEFT OUTER JOIN 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(nvarchar(500), 'Actioned')
 WHERE ALS1.[Description] = N'Disabled'

Select @ActionTypeID = ALT1.[TypeID]
  from [dbo].[AlarmTypes] ALT1
 WHERE ALT1.[Description] = N'Action'
   
/* 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
  FROM [dbo].[Diary] DIA
 WHERE DIA.[ACTIONID] = @ActionID

/* 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)

/* if not authorised, do not do anything else */
SET @Continue = @IsAuthorisedToComplete 

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 */
    SET @Continue = @CountFailedDependentActions 
  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
        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))

        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
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID
                   AND DIA.[ACTIONTYPE] IN ('T', 'E')

                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 isn't a phone or e-mail, update some date information too */
                UPDATE DIA
                   SET DIA.[STATUS] = 1,
                       DIA.[PROCESSSTATUS] = 0,
                       DIA.[DATE] = @Now,
                       DIA.[DYSTARTTIME] = @NowClarionTime
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID
                   AND IsNull(DIA.[ACTIONTYPE], '') NOT IN ('T', 'E')

                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

                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>
                     </NextAction>
                     <NextAction>
                       <Process>Y</Process>
                       <Decision>Do not</Decision>
                       <Code>YYY</Code>
                     </NextAction>
                     <NextAction>
                       <Process>N</Process>
                       <Decision>Do</Decision>
                       <Code>ZZZ</Code>
                     </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') 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') 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, 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') 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 */

                    SELECT @MaxActionID = IsNull(MAX(DIA.[ActionID]), 0)
                      FROM [dbo].[Diary] DIA

                    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])
                        SELECT @MaxActionID,
                               BLCH.[Code]
                          from OPENXML(@idoc, 'NA/NextAction', 2)
                                  WITH(Process   varchar(1)    'Process',
                                       Decision  varchar(10)   'Decision',
                                       Code      varchar(5)    'Code') 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],
                           [DYStartTime],
                           [DYEndTime],
                           [DueDate],
                           [ImageNo],
                           [Publish],
                           [Priority],
                           [Highlighted],
                           [Billable],
                           [ProcessStatus],
                           [BillDescription],
                           [MILESTEONETYPE],
                           [ORGINALACTIONID],
                           [DraftBillNo])
                    SELECT NA.[ActionID],
                           DIA.[CASECODE] AS [CASECODE],
                           [dbo].[ky_WDGetDate](@Now,
                                                TNA.[WHENTYPE],
                                                TNA.[WHEN]) 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],
                           @NowClarionTime AS [DYStartTime],
                           @NowClarionTime AS [DYEndTime],
                           [dbo].[ky_WDGetDate](@NowDateOnly,
                                                TNA.[WHENTYPE],
                                                TNA.[WHEN]) 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]               
                      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)

                    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],
                               DIA.[FNCODE] AS [HANDLER],
                               DIA.[TEAMCODE] 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 RTRIM(substring(DIA.[TEXT1], 1, 255))
                                    WHEN DIA.[ProcessType] = 'I'
                                         THEN RTRIM(substring(  'Email From:'
                                                              + RTrim([dbo].[ky_GetNameFromEmailAddress](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 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 */

                        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 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
                  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) */

                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],
                       DEL.[DATE],
                       @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],
                       DEL.[TIME],
                       @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
    COMMIT
  END
ELSE -- ELSE (IF (@Continue = 0))
  BEGIN
    ROLLBACK
  END
-- END IF (@Continue = 0) 

END
GO

/**************************************************************************************
 *
 * ky_WDActionComplete2
 *
 * Completes / Returns an Action - depending on whether this SP is invoked by the owner
 *   or a delegate. Also allows for taking ownership
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDActionComplete2]
      (@ActionID int,
       @CurFee varchar(10),
       @NextActionsXML varchar(4000),
       @TakeOwnership int)
AS
BEGIN

DECLARE @CurTeam varchar(10)
DECLARE @Now datetime
DECLARE @NowDateOnly datetime
DECLARE @NowClarionTime 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 @NA TABLE
       ([ID]          int identity(1, 1),
        [ActionID]    int,
        [Code]        varchar(5))

DECLARE @AlarmType int
DECLARE @DisabledAlarmStatusID int
DECLARE @ActionTypeID int

SELECT @AlarmType = ISNULL(ALT1.[TypeID], ALT2.[TypeID])
  FROM AlarmTypes ALT2
       LEFT OUTER JOIN 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(nvarchar(500), 'Actioned')
 WHERE ALS1.[Description] = N'Disabled'

Select @ActionTypeID = ALT1.[TypeID]
  from [dbo].[AlarmTypes] ALT1
 WHERE ALT1.[Description] = N'Action'

Select @CurTeam = HAN.[TEAM]
  from [dbo].[Handlers] HAN
 WHERE HAN.[CODE] = @CurFee
 
/* 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)

/* if not authorised, do not do anything else */
SET @Continue = @IsAuthorisedToComplete 

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 */
    SET @Continue = @CountFailedDependentActions 
  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
        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))

        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
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID
                   AND DIA.[ACTIONTYPE] IN ('T', 'E')

                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 isn't a phone or e-mail, update some date information too */
                UPDATE DIA
                   SET DIA.[STATUS] = 1,
                       DIA.[PROCESSSTATUS] = 0,
                       DIA.[DATE] = @Now,
                       DIA.[DYSTARTTIME] = @NowClarionTime
                  FROM [dbo].[Diary] DIA
                 WHERE DIA.[ACTIONID] = @ActionID
                   AND IsNull(DIA.[ACTIONTYPE], '') NOT IN ('T', 'E')

                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

                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>
                     </NextAction>
                     <NextAction>
                       <Process>Y</Process>
                       <Decision>Do not</Decision>
                       <Code>YYY</Code>
                     </NextAction>
                     <NextAction>
                       <Process>N</Process>
                       <Decision>Do</Decision>
                       <Code>ZZZ</Code>
                     </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') 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') 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, 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') 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 */

                    SELECT @MaxActionID = IsNull(MAX(DIA.[ActionID]), 0)
                      FROM [dbo].[Diary] DIA

                    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])
                        SELECT @MaxActionID,
                               BLCH.[Code]
                          from OPENXML(@idoc, 'NA/NextAction', 2)
                                  WITH(Process   varchar(1)    'Process',
                                       Decision  varchar(10)   'Decision',
                                       Code      varchar(5)    'Code') 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],
                           [DYStartTime],
                           [DYEndTime],
                           [DueDate],
                           [ImageNo],
                           [Publish],
                           [Priority],
                           [Highlighted],
                           [Billable],
                           [ProcessStatus],
                           [BillDescription],
                           [MILESTEONETYPE],
                           [ORGINALACTIONID],
                           [DraftBillNo])
                    SELECT NA.[ActionID],
                           DIA.[CASECODE] AS [CASECODE],
                           [dbo].[ky_WDGetDate](@Now,
                                                TNA.[WHENTYPE],
                                                TNA.[WHEN]) 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],
                           @NowClarionTime AS [DYStartTime],
                           @NowClarionTime AS [DYEndTime],
                           [dbo].[ky_WDGetDate](@NowDateOnly,
                                                TNA.[WHENTYPE],
                                                TNA.[WHEN]) 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]               
                      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)

                    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],
                               DIA.[FNCODE] AS [HANDLER],
                               DIA.[TEAMCODE] 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 RTRIM(substring(DIA.[TEXT1], 1, 255))
                                    WHEN DIA.[ProcessType] = 'I'
                                         THEN RTRIM(substring(  'Email From:'
                                                              + RTrim([dbo].[ky_GetNameFromEmailAddress](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 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 */

                        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 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
                  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],
                           DEL.[DATE],
                           DEL.[TIME],
                           '' 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],
                       DEL.[DATE],
                       @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],
                       DEL.[TIME],
                       @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
    COMMIT
  END
ELSE -- ELSE (IF (@Continue = 0))
  BEGIN
    ROLLBACK
  END
-- END IF (@Continue = 0) 

END

GO

DECLARE @COMMAND varchar(MAX)
DECLARE @HasClientGroup int
DECLARE @HasChildCare int
DECLARE @HasAxleTask int
DECLARE @HasPost int

SELECT @HasClientGroup = CASE COUNT(1)
                              WHEN 0 THEN 0
                         ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'ClientGroup'
 WHERE so.[name] = 'contacts'
   AND so.[xtype] = 'U'

SELECT @HasChildCare = CASE COUNT(1)
                            WHEN 0 THEN 0
                       ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'ChildCare'
 WHERE so.[name] = 'WorkTypes'
   AND so.[xtype] = 'U'
   
SELECT @HasAxleTask = CASE COUNT(1)
                           WHEN 0 THEN 0
                      ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'AxleTask'
 WHERE so.[name] = 'TasksCodes'
   AND so.[xtype] = 'U'

SELECT @HasPost = CASE COUNT(1)
                       WHEN 0 THEN 0
                  ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'Post'
 WHERE so.[name] = 'TimeDayBook'
   AND so.[xtype] = 'U'
      
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDTimeDayBookWithAxleErrors
 *
 * Lists the current Day Book Entries plus information about Axle errors
 *
 **************************************************************************************/
Create Function
       [dbo].[ky_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(255),
        [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 MAT.[Code] IS NULL
                   -- Missing matter. This is an error
                   THEN ''Y''
              WHEN ***clientgroupcheck***
                   -- 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 ***childcarecheck***
                   -- 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 ***axletaskcheck***
                   -- 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 ***clientgroupcheck***
                   -- 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 ***childcarecheck***
                   -- 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 ***axletaskcheck***
                   -- 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(7, 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],
         ***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] = TDB.[MATTER]) 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'

IF (@HasClientGroup = 0)
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***clientgroupcheck***', '@HSEClientGroup = @HSEClientGroup')
  END
ELSE
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***clientgroupcheck***', 'RTRIM(IsNull(CON.[ClientGroup], '''')) <> @HSEClientGroup')
  END

IF (@HasChildCare = 0)
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***childcarecheck***', '1 = 1')
  END
ELSE
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***childcarecheck***', 'RTRIM(ISNULL(WTY.[ChildCare], '''')) <> ''Y''')
  END

IF (@HasAxleTask = 0)
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***axletaskcheck***', '1 = 1')
  END
ELSE
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***axletaskcheck***', 'RTRIM(ISNULL(TAC.[AxleTask], '''')) <> ''Y''')
  END

IF (@HasPost = 0)
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***post***', '''Y''')
  END
ELSE
  BEGIN
    SET @COMMAND = REPLACE(@COMMAND, '***post***', 'RTRIM(IsNULL(TDB.[Post], ''''))')
  END

EXEC (@COMMAND)

GO

/**************************************************************************************
 *
 * ky_WDAlterTimeDayBook
 *
 * Sets Day Book values OR creates a new Day Book entry
 * NOTE: this does not set RATE or CHARGE as CHARGE is named CHARGED (with a final D)
 *       in SAM4, so this is taken care of elsewhere.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDAlterTimeDayBook]
      (@RECID int,
       @matter               varchar(20),
       @FEEEARN              varchar(10),
       @TEAM                 varchar(10),
       @DATE                 varchar(8),
       @TIME                 int,
       @TASKORNCC            varchar(10),
       @COMMENT              varchar(600),
       @REC_IRR              varchar(1),
       @STOPWATCH            int,
       @RUNNINGTIME          int,
       @ActionID             int)
AS
BEGIN

DECLARE @STARTTIME            int
DECLARE @NCCCODE              varchar(10)
DECLARE @TRACKREF             int
DECLARE @DOCKET               varchar(8)
DECLARE @STOPWATCHSTARTTIME   datetime
DECLARE @STOPWATCHSTATUS      int
DECLARE @TIMEORCHARGE         varchar(1)
DECLARE @COMLEN               int
DECLARE @TASK                 varchar(10)
DECLARE @CONTINUE             int

BEGIN TRANSACTION

SET @CONTINUE = 0

BEGIN TRY
  BEGIN

    select @comlen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'COMMENT'
     where so.[name] = 'TimeDayBook'
       and so.[xtype] = 'U'
   
    SET @TIMEORCHARGE = 'T'

    SET @STOPWATCHSTARTTIME = CASE @STOPWATCH
                                   WHEN 1
                                        THEN GETDATE()
                                   ELSE NULL END
                               
    SET @STOPWATCHSTATUS = CASE @STOPWATCH
                                WHEN 1
                                     THEN 1
                                ELSE 0 END

    SET @NCCCODE = CASE RTRIM(IsNull(@matter, ''))
                        WHEN '' THEN @TASKORNCC
                        ELSE NULL END

    SET @TASK = CASE RTRIM(IsNull(@matter, ''))
                     WHEN '' THEN ''
                     ELSE IsNull(@TASKORNCC, '') END
                    
    IF (ISNULL(@RECID, 0) = 0)
      BEGIN
	    INSERT
    	  INTO [dbo].[TimeDayBook]
	          ([ActionID],
	           [COMMENT],
    	       [DATE],
	           [FEEEARN],
	           [MATTER],
    	       [NCCCODE],
	           [REC_IRR],
	           [StopwatchStartTime],
    	       [StopwatchStatus],
	           [TASK],
    	       [TEAM],
	           [TIME],
    	       [TIMEORCHARGE])
    	VALUES(@ACTIONID,
	           SUBSTRING(@COMMENT, 1, @COMLEN),
	           @DATE,
    	       @FEEEARN,
	           @matter,
	           @NCCCODE,
    	       @REC_IRR,
	           @STOPWATCHSTARTTIME,
    	       @STOPWATCHSTATUS,
	           @TASK,
    	       @TEAM,
	           @TIME,
	           @TIMEORCHARGE)

    	IF (@@ERROR = 0)
	      BEGIN
            SELECT @RECID = ISNULL(MAX(TDB.[RECORDID]), 0)
              FROM [dbo].[TimeDayBook] TDB
             WHERE [FEEEARN] = @feeearn
    	  END
    	ELSE
    	  BEGIN
            SET @CONTINUE = 1
          END
      END
    ELSE
      BEGIN
        UPDATE TDB
    	   SET [ActionID] = @ACTIONID,
	           [COMMENT] = SUBSTRING(@COMMENT, 1, @COMLEN),
	           [DATE] = @DATE,
    	       [FEEEARN] = @FEEEARN,
	           [MATTER] = @matter,
	           [NCCCODE] = @NCCCODE,
    	       [REC_IRR] = @REC_IRR,
	           [StopwatchStartTime] = @STOPWATCHSTARTTIME,
    	       [StopwatchStatus] = @STOPWATCHSTATUS,
	           [TASK] = @TASK,
	           [TEAM] = @TEAM,
    	       [TIME] = @TIME + CASE @STOPWATCH
	                                 WHEN 1 then 0
	                                 WHEN 0 then 0
	                                 ELSE datediff(n, TDB.[StopwatchStartTime], getDate()) END,
    	       [TIMEORCHARGE] = @TIMEORCHARGE
          FROM [dbo].[TimeDayBook] TDB
         WHERE TDB.[RECORDID] = @RECID
      END

  END

  IF (@STOPWATCH = 1)
  BEGIN
    UPDATE TDB
       SET TDB.[TIME] = [TIME] + datediff(n, TDB.[StopwatchStartTime], getDate()),
           TDB.[StopwatchStartTime] = NULL,
           TDB.[StopwatchStatus] = NULL
      from [dbo].[TimeDayBook] TDB
     where TDB.[FEEEARN] = @FEEEARN
       AND TDB.[RECORDID] <> @RECID
       AND TDB.[StopwatchStartTime] is not null
  END
  
END TRY
BEGIN CATCH
  SET @CONTINUE = 1  
END CATCH

     
IF (@CONTINUE = 0)
  COMMIT
ELSE
  ROLLBACK
  
END
GO

DECLARE @SAM4 int
DECLARE @SAM35 int
DECLARE @AXLE int
DECLARE @HasBilledAmount int
DECLARE @HasIncludeInBill int

SELECT @SAM4 = CASE COUNT(1)
                    WHEN 0 THEN 0
                    ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'CHARGED'
 WHERE SO.[name] = 'TimeDayBook'

SELECT @AXLE = CASE COUNT(1)
                    WHEN 0 THEN 0
                    ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'AxleNumber'
 WHERE SO.[name] = 'TimeEntry'

SELECT @SAM35 = CASE COUNT(1)
                     WHEN 0 THEN 0
                     ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'CHARGE'
 WHERE SO.[name] = 'TimeDayBook'

SELECT @HasBilledAmount = CASE COUNT(1)
                               WHEN 0 THEN 0
                          ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'BilledAmount'
 WHERE SO.[name] = 'TimeEntry'

SELECT @HasIncludeInBill = CASE COUNT(1)
                                WHEN 0 THEN 0
                           ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'IncludeInBill'
 WHERE SO.[name] = 'TimeEntry'

DECLARE @COMMAND varchar(MAX)

IF (@SAM4 <> 0)
  BEGIN
    SET @COMMAND = 
'/**************************************************************************************
 *
 * ky_WDUpdateTimeEntryFromDayBook
 *
 * Update TimeEntry values
 * NOTE: This procedure is VERSION SPECIFIC. This is the SAM4 version of this procedure
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateTimeEntryFromDayBook]
      (@HANDLER varchar(10))
AS
BEGIN
  UPDATE TIE
     SET TIE.[Charged] = CASE WHEN RTRIM(ISNULL(TIE.[MATTER], ''~'')) <> ''~''
                                   THEN TDB.[CHARGED]
                              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.[TEAM] = HAN.[TEAM],
         TIE.[INVOICENO] = ISNULL(MAT.[OpenInvoiceNo], 0),
         TIE.[OPENINV] = CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                              WHEN 0 THEN ''N''
                              ELSE ''Y'' END,
         TIE.[BilledAmount] = CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                   WHEN 0 THEN 0
                                   ELSE TDB.[Charged] END,
         TIE.[Period] = CON.[CurPer],
         TIE.[Year] = CON.[Year]'

    IF (@AXLE = 1)
      BEGIN
	    SET @COMMAND = @COMMAND + ',
         TIE.[AxleNumber] = 0'
      END
      
    SET @COMMAND = @COMMAND + '
    FROM 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]
         CROSS APPLY [dbo].[control] CON
   WHERE NTEID.[HANDLER] = @Handler

  UPDATE MAT
     SET MAT.[ChargeBal] =   MAT.[ChargeBal]
                           + CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                  WHEN 0 THEN TDB.[Charged]
                                  ELSE 0 END,
         MAT.[TimeBal] =   MAT.[ChargeBal]
                         + CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                WHEN 0 THEN TDB.[Time]
                                ELSE 0 END
    FROM 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'
  END

IF (@SAM35 <> 0)
  BEGIN
    SET @COMMAND = 
'/**************************************************************************************
 *
 * ky_WDUpdateTimeEntryFromDayBook
 *
 * Update TimeEntry values
 * NOTE: This procedure is VERSION SPECIFIC. This is the SAM3.5 version of this procedure
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateTimeEntryFromDayBook]
      (@HANDLER VARCHAR(10))
AS
BEGIN
  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.[Leave] = TDB.[Leave],
         TIE.[TEAM] = HAN.[TEAM],
         TIE.[INVOICENO] = ISNULL(MAT.[OpenInvoiceNo], 0),
         TIE.[OPENINV] = CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                              WHEN 0 THEN ''N''
                              ELSE ''Y'' END,' + CASE WHEN @HasBilledAmount = 1 THEN '
         TIE.[BilledAmount] = CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                   WHEN 0 THEN 0
                                   ELSE TDB.[Charge] END,' ELSE '' END + CASE WHEN @HasIncludeInBill = 1 THEN '
         TIE.[IncludeInBill] = CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                    WHEN 0 THEN 0
                                    ELSE 1 END,' ELSE '' END + '
         TIE.[Period] = CON.[CurPer],
         TIE.[Year] = CON.[Year]'

    IF (@AXLE = 1)
      BEGIN
	    SET @COMMAND = @COMMAND + ',
         TIE.[AxleNumber] = 0'
      END

SET @COMMAND = @COMMAND + '
    FROM 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]
         CROSS APPLY [dbo].[control] CON
   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.[ChargeBal]
                         + CASE ISNULL(MAT.[OpenInvoiceNo], 0)
                                WHEN 0 THEN TDB.[Time]
                                ELSE 0 END
    FROM 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'
  END

EXEC (@COMMAND)

GO

DECLARE @COMMAND varchar(8000)
DECLARE @ChargeField varchar(10)
DECLARE @Units int
DECLARE @COMLEN int

select @COMLEN = CASE WHEN sc.[length] > 16
                           THEN sc.[length]
                      ELSE 2000 end
  from sysobjects so
       inner join syscolumns sc
               on sc.[id] = so.[id]
              and sc.[name] = 'COMMENT'
 where so.[name] = 'TimeEntry'
 
IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeEntry'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'CHARGE')
BEGIN
  SET @ChargeField = 'CHARGE'
END
ELSE
BEGIN
  SET @ChargeField = 'CHARGED'
END

IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeEntry'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'UNITS')
BEGIN
  SET @Units = 1
END
ELSE
BEGIN
  SET @Units = 0
END
  
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDUpdateTimeEntry
 *
 * Sets the Rate and Charge values according to the Charge Out Rates indicators and/or
 *     the Task Code used in the TimeEntry Table.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateTimeEntry]
      (@recordid int,
       @fe varchar(10),
       @task varchar(10),
       @comment varchar(' + CONVERT(varchar(4), @COMLEN) + '),
       @sysrate int,
       @rate decimal(7, 2),
       @date datetime,
       @time int,
       @REC_IRR varchar(1))
AS
BEGIN
UPDATE TIE
   SET TIE.[FEEEARN] = RTRIM(ISNULL(@fe, '''')),
       TIE.[TASK] = RTRIM(ISNULL(@task, '''')),
       TIE.[COMMENT] = RTRIM(ISNULL(@COMMENT, '''')),
       TIE.[Date] = @Date,
       TIE.[Time] = IsNull(TUT.[NumValue], 1) * Ceiling(IsNull(@time, 0) / IsNull(TUT.[NumValue], 1)),
       TIE.[REC_IRR] = @REC_IRR,
       TIE.[RATE] = Case When @sysrate = 0
                              THEN @rate
                         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,
       TIE.[' + @ChargeField + '] = Convert(numeric(7, 2),
                              (  (  IsNull(TUT.[NumValue], 1) 
                                  * Ceiling(IsNull(@time, 0) / IsNull(TUT.[NumValue], 1))
                                  * Case When @sysrate = 0
                                              THEN @rate
                                         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))' +
       CASE WHEN @Units = 0
                 THEN ''
            ELSE ',
       TIE.[Units] = Ceiling(IsNull(@time, 0) / IsNull(TUT.[NumValue], 1))' END + '
  from [dbo].[TimeEntry] TIE
       LEFT OUTER JOIN [dbo].[matters] MAT
                       INNER JOIN [dbo].[contacts] CON
                               ON CON.[Code] = MAT.[ClientCode]
                    ON MAT.[code] = TIE.[MATTER]
       OUTER APPLY (SELECT MCOR.[Rate]
                      FROM [dbo].[MatterChargeOutRates] MCOR
                     WHERE MCOR.[FeCode] = TIE.[FEEEARN]
                       AND MCOR.[MatterCode] = TIE.[MATTER]) MCR
       OUTER APPLY (SELECT CCOR.[Rate]
                      FROM [dbo].[ClientChargeOutRates] CCOR
                     WHERE CCOR.[FeCode] = TIE.[FEEEARN]
                       AND CCOR.[ClientCode] = TIE.[MATTER]) 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] = TIE.[FEEEARN]) FER' + 
       CASE WHEN @Units = 0
                 THEN '
       OUTER APPLY (SELECT 1 AS [NumValue]) TUT'
            ELSE '
       OUTER APPLY (SELECT CTN.[NumValue]
                      FROM [dbo].[CtrlNum] CTN
                     WHERE CTN.[Code] = ''TimeUnit'') TUT' END + '
       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(TIE.MATTER, ''''))
                                             WHEN '''' THEN TIE.[NCCODE]
                                             ELSE TIE.[TASK] END) FEP
 WHERE TIE.[RECORDID] = @RECORDID

INSERT
  INTO [dbo].[TimeEntryLog]
      ([TimeId],
       [FromMatter],
       [ToMatter],
       [TrDate],
       [TrBy])
SELECT TIE.[RECORDID],
       TIE.[MATTER],
       TIE.[MATTER],
       getDate(),
       ''UP''
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[RECORDID] = @RECORDID
 
END'

EXEC (@COMMAND)

GO

DECLARE @COMMAND varchar(8000)
DECLARE @ChargeField varchar(10)
DECLARE @Units int
DECLARE @COMLEN int

select @COMLEN = CASE WHEN sc.[length] > 16
                           THEN sc.[length]
                      ELSE 2000 end
  from sysobjects so
       inner join syscolumns sc
               on sc.[id] = so.[id]
              and sc.[name] = 'COMMENT'
 where so.[name] = 'TimeEntry'
 
IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeEntry'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'CHARGE')
BEGIN
  SET @ChargeField = 'CHARGE'
END
ELSE
BEGIN
  SET @ChargeField = 'CHARGED'
END

IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeEntry'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'UNITS')
BEGIN
  SET @Units = 1
END
ELSE
BEGIN
  SET @Units = 0
END
  
SET @COMMAND = '
/**************************************************************************************
 *
 * ky_WDUpdateTimeEntry2
 *
 * Sets the Rate and Charge values according to the Charge Out Rates indicators and/or
 *     the Task Code used in the TimeEntry Table.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateTimeEntry2]
      (@recordid int,
       @fe varchar(10),
       @task varchar(10),
       @comment varchar(' + CONVERT(varchar(4), @COMLEN) + '),
       @sysrate int,
       @rate decimal(7, 2),
       @date datetime,
       @time int,
       @REC_IRR varchar(1),
       @TimeOrCharge varchar(1),
       @charge decimal(7, 2))
AS
BEGIN

SET @TimeOrCharge = ISNULL(@TimeOrCharge, ''T'')
SET @rate = ISNULL(@rate, 0)
SET @charge = ISNULL(@charge, 0)
SET @time = ISNULL(@time, 0)

UPDATE TIE
   SET TIE.[FEEEARN] = RTRIM(ISNULL(@fe, '''')),
       TIE.[TASK] = RTRIM(ISNULL(@task, '''')),
       TIE.[COMMENT] = RTRIM(ISNULL(@COMMENT, '''')),
       TIE.[Date] = @Date,
       TIE.[Time] = CASE WHEN (@TimeOrCharge <> ''C'') OR (@time <> 0)
                              THEN IsNull(TUT.[NumValue], 1) * Ceiling(IsNull(@time, 0) / IsNull(TUT.[NumValue], 1))
                         ELSE 1 END,
       TIE.[REC_IRR] = @REC_IRR,
       TIE.[RATE] = CASE WHEN @TimeOrCharge <> ''C''
                              THEN Case When @sysrate = 0
                                             THEN @rate
                                        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
                         ELSE @charge end,
       TIE.[' + @ChargeField + '] = CASE WHEN @TimeOrCharge = ''C''
                                THEN @charge
                           ELSE Convert(numeric(7, 2),
                                        (  (  IsNull(TUT.[NumValue], 1) 
                                            * Ceiling(IsNull(@time, 0) / IsNull(TUT.[NumValue], 1))
                                         * Case When @sysrate = 0
                                                     THEN @rate
                                                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)) END,
       TIE.[TIMEORCHARGE] = CASE WHEN @TimeOrCharge = ''C''
                                      THEN ''C''
                                 ELSE ''T'' END' +
       CASE WHEN @Units = 0
                 THEN ''
            ELSE ',
       TIE.[Units] = Ceiling(IsNull(@time, 0) / IsNull(TUT.[NumValue], 1))' END + '
  from [dbo].[TimeEntry] TIE
       LEFT OUTER JOIN [dbo].[matters] MAT
                       INNER JOIN [dbo].[contacts] CON
                               ON CON.[Code] = MAT.[ClientCode]
                    ON MAT.[code] = TIE.[MATTER]
       OUTER APPLY (SELECT MCOR.[Rate]
                      FROM [dbo].[MatterChargeOutRates] MCOR
                     WHERE MCOR.[FeCode] = TIE.[FEEEARN]
                       AND MCOR.[MatterCode] = TIE.[MATTER]) MCR
       OUTER APPLY (SELECT CCOR.[Rate]
                      FROM [dbo].[ClientChargeOutRates] CCOR
                     WHERE CCOR.[FeCode] = TIE.[FEEEARN]
                       AND CCOR.[ClientCode] = TIE.[MATTER]) 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] = TIE.[FEEEARN]) FER' + 
       CASE WHEN @Units = 0
                 THEN '
       OUTER APPLY (SELECT 1 AS [NumValue]) TUT'
            ELSE '
       OUTER APPLY (SELECT CTN.[NumValue]
                      FROM [dbo].[CtrlNum] CTN
                     WHERE CTN.[Code] = ''TimeUnit'') TUT' END + '
       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(TIE.MATTER, ''''))
                                             WHEN '''' THEN TIE.[NCCODE]
                                             ELSE TIE.[TASK] END) FEP
 WHERE TIE.[RECORDID] = @RECORDID

INSERT
  INTO [dbo].[TimeEntryLog]
      ([TimeId],
       [FromMatter],
       [ToMatter],
       [TrDate],
       [TrBy])
SELECT TIE.[RECORDID],
       TIE.[MATTER],
       TIE.[MATTER],
       getDate(),
       ''UP''
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[RECORDID] = @RECORDID
 
END'

EXEC (@COMMAND)

GO

DECLARE @COMMAND varchar(max)
DECLARE @POST int

SELECT @POST = CASE COUNT(1)
                    WHEN 0 THEN 0
                    ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'POST'
 WHERE SO.[name] = 'TimeDayBook'
 
IF (@POST <> 0)
  BEGIN
    SET @COMMAND = 
'/**************************************************************************************
 *
 * ky_WDCheckUnpostableEntries
 *
 * Update TimeEntry values
 * NOTE: This procedure is VERSION SPECIFIC. This is the SAM3.5 Build 78 / SAM4
 * version of this procedure
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDCheckUnpostableEntries]
      (@HANDLER varchar(10))
AS
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'
  END

IF (@POST = 0)
  BEGIN
    SET @COMMAND = 
'/**************************************************************************************
 *
 * ky_WDCheckUnpostableEntries
 *
 * Update TimeEntry values
 * NOTE: This procedure is VERSION SPECIFIC. This is the SAM3.5, Pre Build 78
 * version of this procedure
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDCheckUnpostableEntries]
      (@HANDLER varchar(10))
AS
BEGIN
  -- just so there is something between Begin and End 
  DECLARE @placeholder int
  SET @placeholder = 0
END'
  END

EXEC (@COMMAND)

GO

/**************************************************************************************
 *
 * ky_WDPostDayBook
 *
 * Posts all valid entries from the Time Day Book into the Time Entry
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDPostDayBook]
      (@Handler           varchar(10),
       @HSEClientGroup    varchar(20))
AS
BEGIN
  DECLARE @MAXID int
  DECLARE @Continue int
  DECLARE @COMMAND int
  DECLARE @AxleErrors int

  DECLARE @NTEID TABLE
         ([ID]            int      identity(1, 1),
          [NEWID]         int,
          [RECORDID]      int)     

  DECLARE @PDMAT TABLE
         ([ID]            int      identity(1, 1),
          [CODE]          varchar(20))     

  BEGIN TRANSACTION

  SET @Continue = 0

  BEGIN TRY
    BEGIN
      SELECT @AxleErrors = COUNT(1)
        FROM [dbo].[ky_WDTimeDayBookWithAxleErrors]
            (@HSEClientGroup,
             @Handler) AXER
       WHERE AXER.[IsAxleError] = 'Y'

      IF (@@Error <> 0)
        SET @Continue = 1     

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

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          SELECT @MAXID = ISNULL(MAX(TIE.[RECORDID]), 0)
            FROM [dbo].[TimeEntry] TIE
      
          IF (@@Error <> 0)
            SET @Continue = 1
      
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT

            INTO @NTEID
                ([NEWID],
                 [RECORDID])
          SELECT @MAXID,
                 TDB.[RECORDID]
            from TimeDayBook TDB
           WHERE TDB.[FEEEARN] = @Handler
        
          IF (@@ERROR <> 0)
            SET @Continue = 1
          
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT

            INTO @PDMAT
                ([CODE])
          SELECT DISTINCT
                 TDB.[MATTER]
            from TimeDayBook TDB
           WHERE TDB.[FEEEARN] = @Handler
        
          IF (@@ERROR <> 0)
            SET @Continue = 1
          
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          UPDATE NTEID
             SET NTEID.[NEWID] = NTEID.[ID] + NTEID.[NEWID]
            FROM @NTEID NTEID
        
          IF (@@ERROR <> 0)
            SET @Continue = 1
          
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  SET IDENTITY_INSERT [dbo].[TimeEntry] ON
  
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT
            INTO [dbo].[TimeEntry]
                ([MATTER],
                 [FEEEARN],
                 [DATE],
                 [TIME],
                 [RATE],
                 [TASK],
                 [TIMEORCHARGE],
                 [COMMENT],
                 [NCCODE],
                 [DOCKET],
                 [TEAM],
                 [TRACKREF],
                 [REC_IRR],
                 [PERIOD],
                 [YEAR],
                 [ACTIONID],
                 [StageCode],
                 [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 ''
                      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],
                 TDB.[PERIOD],
                 TDB.[YEAR],
                 TDB.[ACTIONID],
                 TDB.[StageCode],
                 NTEID.[NEWID]
            from @NTEID NTEID
                 INNER JOIN [dbo].[TimeDayBook] TDB
                         ON TDB.[RECORDID] = NTEID.[RECORDID]

          IF (@@ERROR <> 0)
            SET @Continue = 1

        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  SET IDENTITY_INSERT [dbo].[TimeEntry] OFF

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          SELECT @MAXID = ISNULL(MAX(TIE.[RECORDID]), 0)
            FROM [dbo].[TimeEntry] TIE

          DBCC CHECKIDENT([TimeEntry], RESEED, @MAXID)
          
          IF (@@Error <> 0)
            SET @Continue = 1
      
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          DELETE [dbo].[WDNTEID]
           WHERE [handler] = @Handler
         
          INSERT
            INTO [dbo].[WDNTEID] 
                ([Handler],
                 [id],
                 [NewId],
                 [RECORDID])
          SELECT @Handler,
                 [ID],
                 [NEWID],
                 [RECORDID] 
            FROM @NTEID
        END
      END TRY
      BEGIN CATCH
        BEGIN
          SET @Continue = 1
        END
      END CATCH
    END
    
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          EXEC [dbo].[ky_WDUpdateTimeEntryFromDayBook] @HANDLER

          IF (@@ERROR <> 0)
            SET @Continue = 1

        END
      END TRY
      BEGIN CATCH
        BEGIN
          SET @Continue = 1
        END
      END CATCH
    END
  
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          EXEC [dbo].[ky_WDCheckUnpostableEntries] @HANDLER

          IF (@@ERROR <> 0)
            SET @Continue = 1

        END
      END TRY
      BEGIN CATCH
        BEGIN
          SET @Continue = 1
        END
      END CATCH
    END
  
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          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

          IF (@@ERROR <> 0)
            SET @Continue = 1

        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          UPDATE MAT
             SET MAT.[ChargeBal] = RKT.[ChargeValue],
                 MAT.[TimeBal] = RKT.[TIME]
            FROM @PDMAT PDM
                 INNER JOIN [dbo].[Matters] MAT
                         ON MAT.[Code] = PDM.[CODE]
                 CROSS APPLY (SELECT IsNull(SUM(KTE.[TIME]), 0) AS [TIME],
                                     IsNull(SUM(KTE.[ChargeValue]), 0) AS [ChargeValue]
                                FROM [dbo].[ky_wdTimeEntry](PDM.[code], '19000101', '21000101') KTE) RKT
           WHERE MAT.[Code] IS NOT NULL

          IF (@@ERROR <> 0)
            SET @Continue = 1

        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
  
  SELECT @Continue

  IF (@Continue = 0)
    COMMIT
  ELSE  
    ROLLBACK
    
END
GO

/**************************************************************************************
 *
 * ky_WDPushTask
 *
 * Push a task forward and/or change its text.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDPushTask]
      (@AssignNo   int,
       @Date       varchar(8),
       @NewText    varchar(4000),
       @Shuffle    int,
       @Handler    varchar(10))
AS
BEGIN       
  DECLARE @Continue int
  DECLARE @ActionID int
  DECLARE @Shuffled int

  BEGIN TRANSACTION

  SET @Continue = 0

  If (RTRIM(ISNULL(@Date, '')) <> '')
    BEGIN
      If (@Continue = 0)
        BEGIN
          BEGIN TRY
		    SELECT @ActionID = DEL.[ActionID],
		           @Shuffled = DateDiff(DD, DEL.[DATE], @Date)
		      FROM [dbo].[DiaryDelegations] DEL
		     WHERE DEL.[AssignNo] = @AssignNo
          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END

      If (@Continue = 0)
        BEGIN
          BEGIN TRY
            UPDATE DEL
               SET DEL.[DATE] = CONVERT(datetime, @DATE)
              FROM [dbo].[DiaryDelegations] DEL
                   INNER JOIN [dbo].[Diary] DIA
                           ON DIA.[ACTIONID] = DEL.[ActionID]
             WHERE DEL.[AssignNo] = @AssignNo

             IF (@@ERROR <> 0)
               SET @Continue = 1

          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END

      If (@Continue = 0)
        BEGIN
          BEGIN TRY
            UPDATE DIA
               SET DIA.[DATE] = CONVERT(datetime, @DATE),
                   DIA.[TEXT1] = @NewText
              FROM [dbo].[DiaryDelegations] DEL
                   INNER JOIN [dbo].[Diary] DIA
                           ON DIA.[ACTIONID] = DEL.[ActionID]
             WHERE DEL.[AssignNo] = @AssignNo

             IF (@@ERROR <> 0)
               SET @Continue = 1

          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END

      If ((@Continue = 0) AND (@Shuffle = 1) AND (@Shuffled <> 0))
        BEGIN
          BEGIN TRY
            UPDATE DIA
               SET DIA.[DATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DIA.[DATE])))
                                     WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DIA.[DATE])
                                     WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DIA.[DATE])
                                                ELSE DATEADD(DD, @Shuffled, DIA.[DATE]) END,
                   DIA.[DUEDATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DIA.[DUEDATE])))
                                        WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DIA.[DUEDATE])
                                        WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DIA.[DUEDATE])
                                                   ELSE DATEADD(DD, @Shuffled, DIA.[DUEDATE]) END
              FROM (SELECT DELS.[ActionID] AS [ActionID],
                           DIAS.[CASECODE]
                      FROM [dbo].[DiaryDelegations] DELS
                           INNER JOIN [dbo].[Diary] DIAS
                                   ON DIAS.[ACTIONID] = DELS.[ACTIONID] 
                     WHERE DELS.[AssignNo] = @AssignNo
                       AND @Shuffle = 1) SHUF
                    INNER JOIN [dbo].[Diary] DIA
                               CROSS APPLY [dbo].[ky_WDActionAuthorisedToComplete](DIA.[ActionID], @Handler) AUT
			            	ON DIA.[CASECODE] = SHUF.[CASECODE]
            			   AND DIA.[ACTIONTYPE] IN ('A', 'R')
            			   AND DIA.[STATUS] = 0
            			   AND DIA.[ACTIONID] <> SHUF.[ACTIONID]
            			   AND AUT.[IsAuthorisedToComplete] = 0
          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END

      If ((@Continue = 0) AND (@Shuffle = 1) AND (@Shuffled <> 0))
        BEGIN
          BEGIN TRY
            UPDATE DEL
               SET DEL.[DATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DEL.[DATE])))
                                     WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DEL.[DATE])
                                     WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DEL.[DATE])
                                                ELSE DATEADD(DD, @Shuffled, DEL.[DATE]) END,
                   DEL.[DUEDATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DEL.[DUEDATE])))
                                        WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DEL.[DUEDATE])
                                        WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DEL.[DUEDATE])
                                                   ELSE DATEADD(DD, @Shuffled, DEL.[DUEDATE]) END
              FROM (SELECT DELS.[ActionID] AS [ActionID],
                           DIAS.[CASECODE]
                      FROM [dbo].[DiaryDelegations] DELS
                           INNER JOIN [dbo].[Diary] DIAS
                                   ON DIAS.[ACTIONID] = DELS.[ACTIONID] 
                     WHERE DELS.[AssignNo] = @AssignNo
                       AND @Shuffle = 1) SHUF
                    INNER JOIN [dbo].[Diary] DIA
                               INNER JOIN [dbo].[DiaryDelegations] DEL
                                       ON DEL.[ACTIONID] = DIA.[ACTIONID]
                                      AND DEL.[STATUS] = 0
                               CROSS APPLY [dbo].[ky_WDActionAuthorisedToComplete](DIA.[ActionID], @Handler) AUT
			            	ON DIA.[CASECODE] = SHUF.[CASECODE]
            			   AND DIA.[ACTIONTYPE] IN ('A', 'R')
            			   AND DIA.[STATUS] = 0
            			   AND DIA.[ACTIONID] <> SHUF.[ACTIONID]
            			   AND AUT.[IsAuthorisedToComplete] = 0
          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END

    END
  ELSE
    BEGIN
      If (@Continue = 0)
        BEGIN
          BEGIN TRY
            UPDATE DIA
               SET DIA.[TEXT1] = @NewText
              FROM [dbo].[DiaryDelegations] DEL
                   INNER JOIN [dbo].[Diary] DIA
                           ON DIA.[ACTIONID] = DEL.[ActionID]
             WHERE DEL.[AssignNo] = @AssignNo

             IF (@@ERROR <> 0)
               SET @Continue = 1

          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END
    END
    
  IF (@Continue = 0)
    COMMIT
  ELSE
    ROLLBACK
      
END
GO

/**************************************************************************************
 *
 * ky_WDPushTask2
 *
 * Push a task forward and/or change its text.
 *
 **************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDPushTask2]
      (@AssignNo    int,
       @Date        varchar(8),
       @DueDate     varchar(8),
       @NewText     varchar(4000),
       @NewSubject  varchar(150),
       @Shuffle     int,
       @Handler     varchar(10))
AS
BEGIN       
  DECLARE @Continue int
  DECLARE @ActionID int
  DECLARE @Shuffled int

  BEGIN TRANSACTION

  SET @Continue = 0
  SET @Shuffled = 0

  If (RTRIM(ISNULL(@Date, '')) <> '')
    BEGIN
      If (@Continue = 0)
        BEGIN
          BEGIN TRY
		    SELECT @ActionID = DEL.[ActionID],
		           @Shuffled = DateDiff(DD, DEL.[DATE], @Date)
		      FROM [dbo].[DiaryDelegations] DEL
		     WHERE DEL.[AssignNo] = @AssignNo
          END TRY
          BEGIN CATCH
            SET @Continue = 1
          END CATCH
        END
    END
    
  If (@Continue = 0)
    BEGIN
      BEGIN TRY
        UPDATE DEL
           SET DEL.[DATE] = CASE WHEN RTRIM(ISNULL(@Date, '')) = ''
                                         THEN DEL.[DATE]
                                 ELSE CONVERT(datetime, @DATE) END,
               DEL.[DUEDATE] = CASE WHEN RTRIM(ISNULL(@DueDate, '')) = ''
                                         THEN DEL.[DUEDATE]
                                    ELSE CONVERT(datetime, @Duedate) END
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                       ON DIA.[ACTIONID] = DEL.[ActionID]
         WHERE DEL.[AssignNo] = @AssignNo
          IF (@@ERROR <> 0)
           SET @Continue = 1

      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  If (@Continue = 0)
    BEGIN
      BEGIN TRY
        UPDATE DIA
           SET DIA.[DATE] = CASE WHEN RTRIM(ISNULL(@Date, '')) = ''
                                         THEN DIA.[DATE]
                                 ELSE CONVERT(datetime, @DATE) END,
               DIA.[DUEDATE] = CASE WHEN RTRIM(ISNULL(@DueDate, '')) = ''
                                         THEN DIA.[DUEDATE]
                                    ELSE CONVERT(datetime, @Duedate) END,
               DIA.[TEXT1] = @NewText,
               DIA.[SUBJECT] = @NewSubject
          FROM [dbo].[DiaryDelegations] DEL
               INNER JOIN [dbo].[Diary] DIA
                       ON DIA.[ACTIONID] = DEL.[ActionID]
         WHERE DEL.[AssignNo] = @AssignNo

        IF (@@ERROR <> 0)
          SET @Continue = 1
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  If ((@Continue = 0) AND (@Shuffle = 1) AND (@Shuffled <> 0))
    BEGIN
      BEGIN TRY
        UPDATE DIA
           SET DIA.[DATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DIA.[DATE])))
                                 WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DIA.[DATE])
                                 WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DIA.[DATE])
                                            ELSE DATEADD(DD, @Shuffled, DIA.[DATE]) END,
               DIA.[DUEDATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DIA.[DUEDATE])))
                                    WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DIA.[DUEDATE])
                                    WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DIA.[DUEDATE])
                                               ELSE DATEADD(DD, @Shuffled, DIA.[DUEDATE]) END
          FROM (SELECT DELS.[ActionID] AS [ActionID],
                       DIAS.[CASECODE]
                  FROM [dbo].[DiaryDelegations] DELS
                       INNER JOIN [dbo].[Diary] DIAS
                               ON DIAS.[ACTIONID] = DELS.[ACTIONID] 
                 WHERE DELS.[AssignNo] = @AssignNo
                   AND @Shuffle = 1) SHUF
                INNER JOIN [dbo].[Diary] DIA
                           CROSS APPLY [dbo].[ky_WDActionAuthorisedToComplete](DIA.[ActionID], @Handler) AUT
                        ON DIA.[CASECODE] = SHUF.[CASECODE]
          			   AND DIA.[ACTIONTYPE] IN ('A', 'R')
           			   AND DIA.[STATUS] = 0
           			   AND DIA.[ACTIONID] <> SHUF.[ACTIONID]
           			   AND AUT.[IsAuthorisedToComplete] = 0
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  If ((@Continue = 0) AND (@Shuffle = 1) AND (@Shuffled <> 0))
    BEGIN
      BEGIN TRY
        UPDATE DEL
           SET DEL.[DATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DEL.[DATE])))
                                 WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DEL.[DATE])
                                 WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DEL.[DATE])
                                            ELSE DATEADD(DD, @Shuffled, DEL.[DATE]) END,
               DEL.[DUEDATE] = CASE Convert(varchar(3), DATENAME(WEEKDAY, DATEADD(DD, @Shuffled, DEL.[DUEDATE])))
                                    WHEN 'Sat' THEN DATEADD(DD, @Shuffled + 2, DEL.[DUEDATE])
                                    WHEN 'Sun' THEN DATEADD(DD, @Shuffled + 1, DEL.[DUEDATE])
                                               ELSE DATEADD(DD, @Shuffled, DEL.[DUEDATE]) END
          FROM (SELECT DELS.[ActionID] AS [ActionID],
                       DIAS.[CASECODE]
                  FROM [dbo].[DiaryDelegations] DELS
                       INNER JOIN [dbo].[Diary] DIAS
                               ON DIAS.[ACTIONID] = DELS.[ACTIONID] 
                 WHERE DELS.[AssignNo] = @AssignNo
                   AND @Shuffle = 1) SHUF
                INNER JOIN [dbo].[Diary] DIA
                           INNER JOIN [dbo].[DiaryDelegations] DEL
                                   ON DEL.[ACTIONID] = DIA.[ACTIONID]
                                  AND DEL.[STATUS] = 0
                           CROSS APPLY [dbo].[ky_WDActionAuthorisedToComplete](DIA.[ActionID], @Handler) AUT
                        ON DIA.[CASECODE] = SHUF.[CASECODE]
           			   AND DIA.[ACTIONTYPE] IN ('A', 'R')
           			   AND DIA.[STATUS] = 0
           			   AND DIA.[ACTIONID] <> SHUF.[ACTIONID]
           			   AND AUT.[IsAuthorisedToComplete] = 0
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
    
  IF (@Continue = 0)
    COMMIT
  ELSE
    ROLLBACK
      
END


GO

/************************************************************************
*
* Create Diary Step WinDev/WebDev version - Version 2, suitable for Add Task
*    as well as assigning a mail to Case
*
*************************************************************************/
CREATE PROCEDURE [dbo].[ky_WDCreateDiaryStep2]
                (@pStatus       Int=0,
                 @pDate         datetime,
                 @pDueDate      datetime,
                 @pSentDate     datetime,
                 @pCaseCode     varchar(20),
                 @pActionCode   char(15),
                 @pActionType   char(1),
                 @pActionStatus char(3),
                 @pPriority     char(1),
                 @pHighlighted  char(1),
                 @pBillable     int,
                 @pWorkProcess  int,
                 @pPublish      char(1),
                 @pFnCode       varchar(10),
                 @pTeamCode     varchar(10),
                 @pText1        varchar(8000),
                 @pAttachments  char(1),
                 @pEmailAddress varchar(150),
                 @pAddressTo    varchar(2000),
                 @pccTo         varchar(2000),
                 @pbccTo        varchar(2000),
                 @pemail        char(1),
                 @pSubject      varchar(500),
                 @pProcessType  char(1),
                 @pActionID     int)
AS

    SET NOCOUNT ON
    DECLARE @strcasecode        nVarChar(17)
    DECLARE @intAssignno        int
    DECLARE @SubjectLen         int
    DECLARE @CaseCodeLen        int
    DECLARE @FELen              int
    DECLARE @TeamLen            int
    DECLARE @dDate              datetime
    DECLARE @pTime              char(10)
    DECLARE @dDueDate           datetime
    DECLARE @pDueTime           char(10)

    -- Get only the DATE portion of the date that was passed in
    IF (@pDate is null)
      SET @pDate = GETDATE()
      
    IF (@pDueDate is null)
      SET @pDueDate = @pDate
      
    SET @dDate = convert(datetime, convert(varchar, @pDate, 112))
    SET @pTime = convert(char(10), (1000 * convert(int, DATEDIFF(ms, @dDate, @pDate) / 10000)) + 1)

    SET @dDueDate = convert(datetime, convert(varchar, @pDueDate, 112))
    SET @pDueTime = convert(char(10), (1000 * convert(int, DATEDIFF(ms, @dDueDate, @pDueDate) / 10000)) + 1)

    select @SubjectLen = CASE WHEN sc.xtype = 35
                                   THEN 150
                              ELSE sc.[length] END
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'subject'
     where so.[name] = 'diary'

    select @CaseCodeLen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'casecode'
     where so.[name] = 'diary'

    select @FELen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'fncode'
     where so.[name] = 'diary'

    select @TeamLen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'teamcode'
     where so.[name] = 'diary'

-- Start Transaction -----------------------------------------------------------------------------------------------------------------------------------------

    BEGIN TRAN Key_Tran_01
    
    IF @@error <> 0 GOTO Tran_Fail

-- Get CaseCode From Matters Table -----------------------------------------------------------------------------------------------------------------------------------------

    SELECT @strCaseCode = (SELECT Top 1
                                  [Code]
                             From [dbo].[Matters]
                            WHERE [code] = @pCaseCode)

    IF @@error <> 0 GOTO Tran_Fail

    SET @strCaseCode = RTrim(Isnull(@strCaseCode, ''))
    Set @pFNCode = RTrim(@pFNCode)
    Set @pTeamCode = RTrim(@pTeamCode)

    IF LEN(@strCaseCode) < 2 GOTO Tran_Fail
    IF LEN(@strCaseCode) > @CaseCodeLen GOTO Tran_Fail
    IF LEN(@pFNCode) > @FELen GOTO Tran_Fail
    IF LEN(@pTeamCode) > @TeamLen GOTO Tran_Fail

-- Set Publish and Subject -----------------------------------------------------------------------------------------------------------------------------------

    Select @pPublish = CASE WHEN RTRIM(ISNULL(@pPublish, '')) <> ''
                                 THEN @pPublish
                            ELSE TAC.[PUBLISHER] END,
           @pProcessType = CASE WHEN RTRIM(ISNULL(@pProcessType, '')) <> ''
                                     THEN @pProcessType
                                ELSE TAC.[PROCESSTYPE] END
      From TemplateActions TAC
     where TAC.[ACTIONCODE] = @pActionCode

    IF (RTRIM(IsNull(@pPublish, '')) = '')
      BEGIN
        SET @pPublish = 'N'
      END

    IF (RTRIM(IsNull(@pProcessType, '')) = '')
      BEGIN
        SET @pProcessType = ''
      END

    SET @pSubject = LTrim(RTrim(@pSubject))
      
    IF LEN(@pSubject) > @SubjectLen
       BEGIN
          SET @pSubject = Substring(@pSubject, 1, @SubjectLen)
       End

-- Write Diary Record -----------------------------------------------------------------------------------------------------------------------------------------

    INSERT INTO [dbo].[Diary]
               ([ActionID],
                [Status],
                [CaseCode],
                [ActionCode],
                [ActionStatus],
                [PRIORITY],
                [HIGHLIGHTED],
                [BILLABLE],
                [WORKPROCESS],
                [FnCode],
                [TeamCode],
                [Text1],
                [Attachments],
                [EmailAddress],
                [AddressTo],
                [ccTo],
                [bccTo],
                [email],
                [Subject],
                [Publish],
                [ActionType],
                [ProcessType],
                [DYStartTime],
                [Date],
                [TxmDate])
         VALUES(@pActionID,
                @pStatus,
                @pCaseCode,
                @pActionCode,
                @pActionStatus,
                @pPriority,
                @pHighlighted,
                @pBillable,
                @pWorkProcess,
                @pFnCode,
                @pTeamCode,
                convert(text, @pText1),
                @pAttachments,
                @pEmailAddress,
                @pAddressTo,
                @pccTo,
                @pbccTo,
                @pemail,
                @pSubject,
                @pPublish,
                @pActionType,
                @pProcessType,
                @pTime,
                @pDate,
                @pSentDate)

    IF @@error <> 0 GOTO Tran_Fail

-- Write the diary delegation record ------------------------------------------------------------

    INSERT INTO [DiaryDelegations]
               ([ACTIONID],
                [HANDLER],
                [TEAM],
                [DATE],
                [TIME],
                [DATER],
                [TIMER],
                [DUEDATE],
                [DUETIME],
                [REVIEW],
                [STATUS],
                [OWNER],
                [DELEGATE],
                [DELEGATESTATUS],
                [ActionType],
                [FromHandler],
                [ReturnedBy],
                [DelType])
         VALUES(@pActionID,
                @pFnCode,
                @pTeamCode,
                @dDate,
                @pTime,
                @dDate,
                @pTime,
                @dDueDate,
                @pDueTime,
                ' ',
                @pStatus,
                'Y',
                @pFnCode,
                0,
                @pActionType,
                ' ',
                ' ',
                'Created')

-- Commit Transaction ------------------------------------------------------------------------------------------------------------------

    COMMIT TRAN Key_Tran_01

    IF @@error <> 0 GOTO Tran_Fail

-- End Of Processing --------------------------------------------------------------------------------------------------------------------

ExitPoint:

    Return

--  Error Processing -------------------------------------------------------------------------------------------------------------------------------------

Tran_Fail:

    rollback tran Key_Tran_01

    GoTo ExitPoint

GO

/************************************************************************
*
* Create Diary Step WinDev/WebDev version
*
*************************************************************************/
CREATE PROCEDURE [dbo].[ky_WDCreateDiaryStep]
                (@pStatus       Int=0,
                 @pDate         datetime,
                 @pSentDate     datetime,
                 @pCaseCode     char(17),
                 @pActionCode   char(15),
                 @pActionStatus char(3),
                 @pFnCode       char(5),
                 @pTeamCode     char(5),
                 @pText1        varchar(8000),
                 @pAttachments  char(1),
                 @pEmailAddress varchar(150),
                 @pAddressTo    varchar(2000),
                 @pccTo         varchar(2000),
                 @pbccTo        varchar(2000),
                 @pemail        char(1),
                 @pSubject      varchar(500),
                 @pProcessType  char(1),
                 @pActionID     int)
AS
  EXEC [dbo].[ky_WDCreateDiaryStep2] @pStatus, 
                                     @pDate,
                                     NULL,
                                     @pSentDate,
                                     @pCaseCode,
                                     @pActionCode,
                                     'E',
                                     @pActionStatus,
                                     NULL,
                                     NULL,
                                     NULL,
                                     NULL,
                                     NULL,
                                     @pFnCode,
                                     @pTeamCode,
                                     @pText1,
                                     @pAttachments,
                                     @pEmailAddress,
                                     @pAddressTo,
                                     @pccTo,
                                     @pbccTo,
                                     @pemail,
                                     @pSubject,
                                     @pProcessType,
                                     @pActionID 

/*  ORIGINAL CODE
    SET NOCOUNT ON
    DECLARE @strcasecode        nVarChar(17)
    DECLARE @intAssignno        int
    DECLARE @pPublish           char(1)
    DECLARE @SubjectLen         int
    DECLARE @CaseCodeLen        int
    DECLARE @FELen              int
    DECLARE @TeamLen            int
    DECLARE @dDate              datetime
    DECLARE @pTime              char(10)

    -- Get only the DATE portion of the date that was passed in
    SET @dDate = convert(datetime, convert(varchar, @pDate, 112))
    SET @pTime = convert(char(10), (1000 * convert(int, DATEDIFF(ms, @dDate, @pDate) / 10000)) + 1)

    select @SubjectLen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'subject'
     where so.[name] = 'diary'

    select @CaseCodeLen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'casecode'
     where so.[name] = 'diary'

    select @FELen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'fncode'
     where so.[name] = 'diary'

    select @TeamLen = sc.[length]
      from sysobjects so
           inner join syscolumns sc
                   on sc.[id] = so.[id]
                  and sc.[name] = 'teamcode'
     where so.[name] = 'diary'

-- Start Transaction -----------------------------------------------------------------------------------------------------------------------------------------

    BEGIN TRAN Key_Tran_01
    
    IF @@error <> 0 GOTO Tran_Fail

-- Get CaseCode From Matters Table -----------------------------------------------------------------------------------------------------------------------------------------

    SELECT @strCaseCode = (SELECT Top 1
                                  [Code]
                             From [dbo].[Matters]
                            WHERE [code] = @pCaseCode)

    IF @@error <> 0 GOTO Tran_Fail

    SET @strCaseCode = RTrim(Isnull(@strCaseCode, ''))
    Set @pFNCode = RTrim(@pFNCode)
    Set @pTeamCode = RTrim(@pTeamCode)

    IF LEN(@strCaseCode) < 2 GOTO Tran_Fail
    IF LEN(@strCaseCode) > @CaseCodeLen GOTO Tran_Fail
    IF LEN(@pFNCode) > @FELen GOTO Tran_Fail
    IF LEN(@pTeamCode) > @TeamLen GOTO Tran_Fail

-- Set Publish and Subject -----------------------------------------------------------------------------------------------------------------------------------

    Select @pPublish = (Select PUBLISHER
                          From TemplateActions
                         where actioncode=@pActionCode)

    IF @pPublish  IS NULL SELECT @pPublish = 'N'

    SET @pSubject = LTrim(RTrim(@pSubject))

    IF LEN(@pSubject) > @SubjectLen
       BEGIN
          SET @pSubject = Substring(@pSubject, 1, @SubjectLen)
       End

-- Write Diary Record -----------------------------------------------------------------------------------------------------------------------------------------

    INSERT INTO [dbo].[Diary]
               ([ActionID],
                [Status],
                [CaseCode],
                [ActionCode],
                [ActionStatus],
                [FnCode],
                [TeamCode],
                [Text1],
                [Attachments],
                [EmailAddress],
                [AddressTo],
                [ccTo],
                [bccTo],
                [email],
                [Subject],
                [Publish],
                [ActionType],
                [ProcessType],
                [DYStartTime],
                [Date],
                [TxmDate])
         VALUES(@pActionID,
                @pStatus,
                @pCaseCode,
                @pActionCode,
                @pActionStatus,
                @pFnCode,
                @pTeamCode,
                convert(text, @pText1),
                @pAttachments,
                @pEmailAddress,
                @pAddressTo,
                @pccTo,
                @pbccTo,
                @pemail,
                @pSubject,
                @pPublish,
                'E',
                @pProcessType,
                @pTime,
                @pDate,
                @pSentDate)

    IF @@error <> 0 GOTO Tran_Fail

-- Write the diary delegation record ------------------------------------------------------------

    INSERT INTO [DiaryDelegations]
               ([ACTIONID],
                [HANDLER],
                [TEAM],
                [DATE],
                [TIME],
                [DATER],
                [TIMER],
                [DUEDATE],
                [DUETIME],
                [REVIEW],
                [STATUS],
                [OWNER],
                [DELEGATE],
                [DELEGATESTATUS],
                [ActionType],
                [FromHandler],
                [ReturnedBy],
                [DelType])
         VALUES(@pActionID,
                @pFnCode,
                @pTeamCode,
                @dDate,
                @pTime,
                0,
                '',
                @pDate,
                @pTime,
                ' ',
                @pStatus,
                'Y',
                @pFnCode,
                0,
                'E',
                ' ',
                ' ',
                'Created')

-- Commit Transaction ------------------------------------------------------------------------------------------------------------------

    COMMIT TRAN Key_Tran_01

    IF @@error <> 0 GOTO Tran_Fail

-- End Of Processing --------------------------------------------------------------------------------------------------------------------

ExitPoint:

    Return

--  Error Processing -------------------------------------------------------------------------------------------------------------------------------------

Tran_Fail:

    rollback tran Key_Tran_01

    GoTo ExitPoint

*/
GO

/************************************************************************
*
* List mail associations - links e-mail to Case Diary via mail date and
* subject
*
*************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDListMailAssociations]
      (@EmailsXML varchar(max))
AS
BEGIN

DECLARE @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @EmailsXML 

SELECT EML.[id],
       DIS.[ACTIONID],
       EML.[date],
       ISNULL(DIS.[Code], '') AS [casecode],
       ISNULL(DIS.[Description], '') As [description]
  FROM OPENXML(@idoc, 'emails/email', 2)
          WITH([id]       int             'id',
               [date]     datetime        'date',
               [from]     varchar(150)    'from',
               [fromname] varchar(150)    'fromname',
               [subject]  varchar(2000)   'subject') EML
       OUTER APPLY (SELECT TOP 1
                           DIA.[ActionID],
                           MAT.[code],
                           MAT.[description]
                      FROM [dbo].[Diary] DIA
                           CROSS APPLY (SELECT DI2.[actionid],
                                               RTRIM(Convert(Varchar(2000), DI2.[SUBJECT])) + '*#*' + RTRIM(Convert(varchar(150), DI2.[EMAILADDRESS])) AS [MEH]
                                          FROM [dbo].[diary] DI2
                                         WHERE DI2.[ACTIONID] = DIA.[actionid]) DIB
                           INNER JOIN [dbo].[matters] MAT
                                   ON MAT.[Code] = DIA.[CASECODE]
                     WHERE DIA.[EMAIL] = 'Y'
                       AND (   (    DIA.[TxmDATE] >= DATEADD(mi, -1, EML.[date])
                                AND DIA.[TxmDATE] <= DATEADD(mi, 1, EML.[date]))
                            OR (    DIA.[TxmDate] is null
                                AND DIA.[DATE] >= DATEADD(mi, -1, EML.[date])
                                AND DIA.[DATE] <= DATEADD(mi, 1, EML.[date])))
                       AND (   Replace(DIB.[MEH], '"', '') = EML.[subject] + '*#*' + Replace(EML.[from], '"', '')
                            OR DIB.[MEH] = EML.[subject] + '*#*' + EML.[fromname])) DIS
ORDER BY EML.[id] ASC

EXEC sp_xml_removedocument @idoc

END
GO

/************************************************************************
*
* List mail associations - links e-mail to Case Diary via mail date and
* subject. Version 2 - improved performance
*
*************************************************************************/
CREATE PROCEDURE 
       [dbo].[ky_WDListMailAssociations2]
      (@handler    varchar(10),
       @EmailsXML  varchar(MAX))
AS
BEGIN

DELETE DMC
  FROM [dbo].[DiaMailCandidates] DMC
 WHERE DMC.[handler] = @handler
 
DECLARE @idoc int

EXEC sp_xml_preparedocument @idoc OUTPUT, @EmailsXML 

INSERT
  INTO [dbo].[DiaMailCandidates]
      ([handler],
       [id],
       [date],
       [from],
       [fromname],
       [actionid],
       [subject],
       [casecode])
SELECT @handler,
       EML.[id],
       EML.[date],
       Replace(EML.[from], '"', ''),
       EML.[fromname],
       IsNull(DIA.[actionid], 0),
       SUBSTRING(EML.[subject], 1, 150),
       DIA.[CASECODE]
  FROM OPENXML(@idoc, 'emails/email', 2)
          WITH([id]       int             'id',
               [date]     datetime        'date',
               [from]     varchar(150)    'from',
               [fromname] varchar(150)    'fromname',
               [subject]  varchar(2000)   'subject') EML
       LEFT OUTER JOIN [dbo].[Diary] DIA
                    ON (   DIA.[TxmDate] IN (SELECT DISTINCT [date]
                                               FROM OPENXML(@idoc, 'emails/email', 2)
                                                       WITH([id]       int             'id',
                                                            [date]     datetime        'date',
                                                            [from]     varchar(150)    'from',
                                                            [fromname] varchar(150)    'fromname',
                                                            [subject]  varchar(2000)   'subject') EML2)
                        OR DIA.[DATE] IN (SELECT DISTINCT [date]
                                            FROM OPENXML(@idoc, 'emails/email', 2)
                                                    WITH([id]       int             'id',
                                                         [date]     datetime        'date',
                                                         [from]     varchar(150)    'from',
                                                         [fromname] varchar(150)    'fromname',
                                                         [subject]  varchar(2000)   'subject') EML2))
                   AND DIA.[EMAIL] = 'Y'

UPDATE DIC
   SET DIC.[diasubject] = SUBSTRING(DIA.[subject], 1, 150),
       DIC.[diaemail] = Replace(SUBSTRING(DIA.[EMAILADDRESS], 1, 150), '"', '')
  from [dbo].[DiaMailCandidates] DIC
       INNER JOIN [dbo].[diary] DIA
               ON DIA.[ACTIONID] = DIC.[actionid]
              AND DIA.[ACTIONID] <> 0
              AND (   DIA.[date] = DIC.[date]
                   OR DIA.[TxmDate] = DIC.[date])
 where DIC.[handler] = @handler

DELETE DIC
  from [dbo].[DiaMailCandidates] DIC
 WHERE DIC.[handler] = @handler
   AND DIC.[casecode] is not null
   AND (   DIC.[subject] <> IsNull(DIC.[diasubject], '')
        OR DIC.[from] <> IsNull(DIC.[diaemail], ''))

DELETE DIC
  from [dbo].[DiaMailCandidates] DIC
       CROSS APPLY (SELECT COUNT(1) AS [TOTAL]
                      FROM [dbo].[DiaMailCandidates] DIC2
                     WHERE DIC2.[handler] = DIC.[handler]
                       AND DIC2.[id] = DIC.[id]
                       AND DIC2.[actionid] < DIC.[actionid]) OTH
 WHERE DIC.[handler] = @handler
   AND DIC.[casecode] is not null
   AND OTH.[TOTAL] > 0

EXEC sp_xml_removedocument @idoc

END
GO

/************************************************************************
*
* Populate Day Book - Table Function returning the content of the Day Book
*
*************************************************************************/
create function
       [dbo].[ky_WDPopDayBook]
      (@HANDLER VARCHAR(10),
       @RECORDID Int)
RETURNS @TDB TABLE
       ([id]                  int          identity(1, 1),
        [MATTER]              varchar(20),
        [ClientCode]          varchar(10),
        [FEEEARN]             varchar(10),
        [DATE]                varchar(11),
        [TIME]                int,
        [FMTTIME]             varchar(6),
        [RATE]                decimal(7, 2),
        [CHARGE]              decimal(7, 2),
        [COMMENT]             varchar(255),
        [TIMEORCHARGE]        varchar(1),
        [REC_IRR]             varchar(1),
        [RECORDID]            int,
        [NAME]                varchar(100),
        [Description]         varchar(300),
        [STOPWATCHSTARTTIME]  datetime,
        [STOPWATCHSTATUS]     int,
        [SWInactive]          int,
        [SWRunning]           int,
        [SWPaused]            int,
        [TASK]                varchar(10),
        [NCCCODE]             varchar(5),
        [ActionId]            int,
        [DBDescription]       varchar(80),
        [MATChargeLevel]      int,
        [MATChargeOutRateInd] varchar(1),
        [CTCChargeOutRateInd] varchar(1),
        [MCORRate]            decimal(18, 2),
        [CCRRate]             decimal(18, 2),
        [FERRate]             decimal(18, 2),
        [FEPChargeFct]        decimal(18, 2))
AS
BEGIN

IF (ISNULL(@RECORDID, 0) = 0)
  BEGIN
    INSERT
      INTO @TDB
          ([MATTER],
           [ClientCode],
           [FEEEARN],
           [DATE],
           [TIME],
           [FMTTIME],
           [RATE],
           [CHARGE],
           [COMMENT],
           [TIMEORCHARGE],
           [REC_IRR],
           [RECORDID],
           [NAME],
           [Description],
           [STOPWATCHSTARTTIME],
           [STOPWATCHSTATUS],
           [SWInactive],
           [SWRunning],
           [SWPaused],
           [TASK],
           [NCCCODE],
           [ActionId],
           [DBDescription],
           [MATChargeLevel],
           [MATChargeOutRateInd],
           [CTCChargeOutRateInd])
    SELECT CASE WHEN RTRIM(ISNULL(TDB.[MATTER], '')) = ''
                     THEN 'n/a' 
                ELSE RTRIM(ISNULL(TDB.[MATTER], '')) END AS [MATTER],
           ISNULL(MAT.[ClientCode], '') AS [ClientCode],
           RTRIM(ISNULL(TDB.[FEEEARN], '')) AS [FEEEARN],
           Convert(VARCHAR, TDB.[DATE], 106) AS [DATE],
           TDB.[TIME] AS [TIME],
           [dbo].[ky_TimeFromMinutes](TDB.[Time]) AS [FMTTIME],
           0 AS [RATE],
           Convert(numeric(7, 2),
                   0) AS [CHARGE],
           RTRIM(ISNULL(TDB.[COMMENT], '')) AS [COMMENT],
           TDB.[TIMEORCHARGE] AS [TIMEORCHARGE],
           TDB.[REC_IRR] AS [REC_IRR],
           TDB.[RECORDID] AS [RECORDID],
           RTRIM(ISNULL(CTC.[NAME], 'n/a')) AS [NAME],
           RTRIM(ISNULL(MAT.[Description], 'Admin')) AS [Description],
           TDB.[StopwatchStartTime] AS [StopwatchStartTime],
           TDB.[StopwatchStatus] AS [StopwatchStatus],
           CASE WHEN ISNULL(TDB.[StopwatchStatus], 0) = 0 
                     THEN 1
                ELSE 0 END AS [SWInactive],
           CASE WHEN ISNULL(TDB.[StopwatchStatus], 0) = 1 
                     THEN 1
                ELSE 0 END AS [SWRunning],
           CASE WHEN ISNULL(TDB.[StopwatchStatus], 0) = 2 
                     THEN 1
                ELSE 0 END AS [SWPaused],
           RTRIM(ISNULL(TDB.[TASK], '')) AS [TASK],
           RTRIM(ISNULL(TDB.[NCCCODE], '')) AS [NCCCODE],
           ISNULL(TDB.[ActionId], 0) AS [ActionId],
           [dbo].[ky_removespuriouswhitespace](ISNULL(TDB.[COMMENT], ''), 80) AS [DBDescription],
           ISNULL(MAT.[ChargeLevel], 3) AS [MATChargeLevel],
           ISNULL(MAT.[ChargeOutRateInd], 'N') AS [MATChargeOutRateInd],
           ISNULL(CTC.[ChargeOutRateInd], 'N') AS [CTCChargeOutRateInd]
      FROM [dbo].[TimeDayBook] TDB
           LEFT OUTER JOIN [dbo].[matters] MAT
                           INNER JOIN [dbo].[Contacts] CTC
                                   ON CTC.[CODE] = MAT.[ClientCode]
                        ON MAT.[CODE] = TDB.[MATTER]
     WHERE TDB.[FEEEARN] = @HANDLER
     
  END
ELSE
  BEGIN
    INSERT
      INTO @TDB
          ([MATTER],
           [ClientCode],
           [FEEEARN],
           [DATE],
           [TIME],
           [FMTTIME],
           [RATE],
           [CHARGE],
           [COMMENT],
           [TIMEORCHARGE],
           [REC_IRR],
           [RECORDID],
           [NAME],
           [Description],
           [STOPWATCHSTARTTIME],
           [STOPWATCHSTATUS],
           [SWInactive],
           [SWRunning],
           [SWPaused],
           [TASK],
           [NCCCODE],
           [ActionId],
           [DBDescription],
           [MATChargeLevel],
           [MATChargeOutRateInd],
           [CTCChargeOutRateInd])
    SELECT CASE WHEN RTRIM(ISNULL(TDB.[MATTER], '')) = ''
                     THEN 'n/a' 
                ELSE RTRIM(ISNULL(TDB.[MATTER], '')) END AS [MATTER],
           ISNULL(MAT.[ClientCode], '') AS [ClientCode],
           RTRIM(ISNULL(TDB.[FEEEARN], '')) AS [FEEEARN],
           Convert(VARCHAR, TDB.[DATE], 106) AS [DATE],
           TDB.[TIME] AS [TIME],
           [dbo].[ky_TimeFromMinutes](TDB.[Time]) AS [FMTTIME],
           0 AS [RATE],
           Convert(numeric(7, 2),
                   0) AS [CHARGE],
           RTRIM(ISNULL(TDB.[COMMENT], '')) AS [COMMENT],
           TDB.[TIMEORCHARGE] AS [TIMEORCHARGE],
           TDB.[REC_IRR] AS [REC_IRR],
           TDB.[RECORDID] AS [RECORDID],
           RTRIM(ISNULL(CTC.[NAME], 'n/a')) AS [NAME],
           RTRIM(ISNULL(MAT.[Description], 'Admin')) AS [Description],
           TDB.[StopwatchStartTime] AS [StopwatchStartTime],
           TDB.[StopwatchStatus] AS [StopwatchStatus],
           CASE WHEN ISNULL(TDB.[StopwatchStatus], 0) = 0 
                     THEN 1
                ELSE 0 END AS [SWInactive],
           CASE WHEN ISNULL(TDB.[StopwatchStatus], 0) = 1 
                     THEN 1
                ELSE 0 END AS [SWRunning],
           CASE WHEN ISNULL(TDB.[StopwatchStatus], 0) = 2 
                     THEN 1
                ELSE 0 END AS [SWPaused],
           RTRIM(ISNULL(TDB.[TASK], '')) AS [TASK],
           RTRIM(ISNULL(TDB.[NCCCODE], '')) AS [NCCCODE],
           ISNULL(TDB.[ActionId], 0) AS [ActionId],
           [dbo].[ky_removespuriouswhitespace](ISNULL(TDB.[COMMENT], ''), 80) AS [DBDescription],
           ISNULL(MAT.[ChargeLevel], 3) AS [MATChargeLevel],
           ISNULL(MAT.[ChargeOutRateInd], 'N') AS [MATChargeOutRateInd],
           ISNULL(CTC.[ChargeOutRateInd], 'N') AS [CTCChargeOutRateInd]
      FROM [dbo].[TimeDayBook] TDB
           LEFT OUTER JOIN [dbo].[matters] MAT
                           INNER JOIN [dbo].[Contacts] CTC
                                   ON CTC.[CODE] = MAT.[ClientCode]
                        ON MAT.[CODE] = TDB.[MATTER]
     WHERE TDB.[FEEEARN] = @HANDLER
       AND TDB.[RECORDID] = @RECORDID
  END

UPDATE TDB
   SET TDB.[MCORRate] = IsNull(MCOR.[RATE], 0)
  FROM @TDB TDB
       LEFT OUTER JOIN [dbo].[MatterChargeOutRates] MCOR
                    ON MCOR.[FECode] = TDB.[FEEEARN]
                   AND MCOR.[MatterCode] = TDB.[MATTER]

UPDATE TDB
   SET TDB.[CCRRate] = IsNull(CCOR.[RATE], 0)
  FROM @TDB TDB
       LEFT OUTER JOIN [dbo].[ClientChargeOutRates] CCOR
                    ON CCOR.[FECode] = TDB.[FEEEARN]
                   AND CCOR.[ClientCode] = TDB.[ClientCode]
                      
UPDATE TDB
   SET TDB.[FERRate] = CASE TDB.[MATCHARGELEVEL]
                            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 @TDB TDB
       LEFT OUTER JOIN [dbo].[Handlers] HDL
                    ON HDL.[Code] = TDB.[FEEEARN]


UPDATE TDB
   SET [FEPChargeFct] = 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 @TDB TDB
       LEFT OUTER JOIN [dbo].[TasksCodes] TAC
                    ON TAC.[CODE] = CASE RTRIM(ISNULL(TDB.MATTER, ''))
                                         WHEN '' THEN '***'
                                         ELSE TDB.[TASK] END

UPDATE TDB
   SET TDB.[RATE] = CASE WHEN [MATChargeOutRateInd] = 'Y'
                              THEN [MCORRate]
                         WHEN [CTCChargeOutRateInd] = 'Y'
                              THEN ISNULL(TDB.[CCRRATE], 0)
                         ELSE ISNULL(TDB.[FEPChargeFct], 1.00) * TDB.[FERRATE] END,
       TDB.[CHARGE] = Convert(numeric(7, 2),
                              (  (  ISNULL(TDB.[TIME], 0)
                                  * CASE WHEN [MATChargeOutRateInd] = 'Y'
                                              THEN ISNULL([MCORRATE], 0)
                                         WHEN [CTCChargeOutRateInd] = 'Y'
                                              THEN ISNULL([CCRRATE], 0)
                                         ELSE ISNULL([FEPChargeFct], 1.00) * [FERRATE] END)
                                  / 60))
  FROM @TDB TDB  
RETURN

END

GO

/************************************************************************
*
* Day Book
*
*************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDDayBook]
      (@HANDLER VARCHAR(10),
       @RECORDID Int)
AS
BEGIN

SELECT * from [dbo].[ky_WDPopDayBook](@HANDLER, @RECORDID)

END
GO

/************************************************************************
*
* Time Entry (SAM3.5 as well as SAM4)
*
*************************************************************************/
DECLARE @SAM4 int
DECLARE @Units int
DECLARE @command varchar(4000)
DECLARE @ChargeField varchar(10)
DECLARE @UnitsField varchar(20)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeEntry'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'UNITS')
BEGIN
  SET @Units = 1
  SET @UnitsField = 'TEN.[Units]'
END
ELSE
BEGIN
  SET @Units = 0
  SET @UnitsField = 'TEN.[TIME]'
END

IF (@SAM4 = 17)
  BEGIN
    SET @ChargeField = 'CHARGED'
  END
ELSE
  BEGIN
    SET @ChargeField = 'CHARGE'
  END


   SET @command =
'CREATE FUNCTION
       [dbo].[ky_WDTimeEntry]
      (@Matter               varchar(20),
       @FromDateP            varchar(8),
       @ToDateP              varchar(8))
RETURNS @WDT TABLE
       ([MATTER]             varchar(20),
        [FEEEARN]            varchar(10),
        [DATE]               datetime,
        [TIME]               int,
        [UNITS]              decimal(11, 2),
        [Comment]            varchar(1000),
        [TimeOrCharge]       varchar(1),
        [ChargeValue]        decimal(10, 2),
        [Task]               varchar(10),
        [REC_IRR]            varchar(1),
        [InvoiceNo]          varchar(10),
        [RecordID]           int,
        [WriteOffDate]       varchar(20),
        [WriteOffID]         int)
AS
BEGIN

DECLARE @FromDate datetime
DECLARE @ToDate datetime

SET @FromDate = @FromDateP
SET @ToDate = @ToDateP

INSERT
  INTO @WDT
      ([MATTER],
       [FEEEARN],
       [DATE],
       [TIME],
       [UNITS],
       [Comment],
       [TimeOrCharge],
       [ChargeValue],
       [Task],
       [REC_IRR],
       [InvoiceNo],
       [RecordID],
       [WriteOffDate],
       [WriteOffID])
SELECT RTRIM(IsNull(TEN.[MATTER], '''')) AS [MATTER],
       RTRIM(IsNull(TEN.[FEEEARN], '''')) AS [FEEEARN],
       TEN.[DATE],
       TEN.[TIME],
       ' + @UnitsField + ',
       RTRIM(IsNull(TEN.[COMMENT], '''')) AS [COMMENT],
       RTRIM(IsNull(TEN.[TIMEORCHARGE], '''')) AS [TIMEORCHARGE],
       IsNull(TEN.[' + @ChargeField + '], 0) AS [CHARGEVALUE],
       RTRIM(IsNull(TEN.[TASK], '''')) AS [TASK],
       RTRIM(IsNull(TEN.[REC_IRR], '''')) AS [REC_IRR],
       CASE WHEN TEN.[WriteOffDT] IS NOT NULL
                 THEN ''w/o''
            WHEN IsNull(TEN.[INVOICENO], 0) = 0
                 THEN ''unbilled''
            ELSE Convert(varchar(10), TEN.[INVOICENO]) END AS [InvoiceNo],
       IsNull(TEN.[RECORDID], 0) AS [RecordID],
       IsNull(CONVERT(varchar(20), TEN.[WriteOffDT], 106), '''') AS [WriteOffDate],
       IsNull(TEN.[WriteOffID], 0) AS [WriteOffID]
  FROM [dbo].[TimeEntry] TEN
 WHERE TEN.[MATTER] = @MATTER
   AND TEN.[DATE] >= @FromDate
   AND TEN.[DATE] < DateAdd(dd, 1, @ToDate)
  
RETURN
END'

EXEC (@Command)

GO

/************************************************************************
*
* Time Entry By Record ID (SAM3.5 as well as SAM4)
*
*************************************************************************/
DECLARE @SAM4 int
DECLARE @Units int
DECLARE @command varchar(4000)
DECLARE @ChargeField varchar(10)
DECLARE @UnitsField varchar(20)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

IF EXISTS(SELECT *
            FROM sysobjects SO
                 inner join syscolumns SC
                         ON SC.[id] = SO.[id]
           WHERE so.[name] = 'TimeEntry'
             AND so.[xtype] = 'U'
             AND UPPER(sc.[name]) = 'UNITS')
BEGIN
  SET @Units = 1
  SET @UnitsField = 'TEN.[Units]'
END
ELSE
BEGIN
  SET @Units = 0
  SET @UnitsField = 'TEN.[TIME]'
END

IF (@SAM4 = 17)
  BEGIN
    SET @ChargeField = 'CHARGED'
  END
ELSE
  BEGIN
    SET @ChargeField = 'CHARGE'
  END


   SET @command =
'CREATE FUNCTION
       [dbo].[ky_WDTimeEntryByRecordID]
      (@RecordID             int)
RETURNS @WDT TABLE
       ([MATTER]             varchar(20),
        [FEEEARN]            varchar(10),
        [FEEEARNNAME]        varchar(100),
        [DATE]               datetime,
        [TIME]               int,
        [UNITS]              decimal(11, 2),
        [Comment]            varchar(1000),
        [TimeOrCharge]       varchar(1),
        [Rate]               decimal(10, 2),
        [ChargeValue]        decimal(10, 2),
        [Task]               varchar(10),
        [REC_IRR]            varchar(1),
        [InvoiceNo]          varchar(10),
        [RecordID]           int,
        [WriteOffDate]       varchar(20),
        [WriteOffID]         int)
AS
BEGIN

INSERT
  INTO @WDT
      ([MATTER],
       [FEEEARN],
       [FEEEARNNAME],
       [DATE],
       [TIME],
       [UNITS],
       [Comment],
       [TimeOrCharge],
       [Rate],
       [ChargeValue],
       [Task],
       [REC_IRR],
       [InvoiceNo],
       [RecordID],
       [WriteOffDate],
       [WriteOffID])
SELECT RTRIM(IsNull(TEN.[MATTER], '''')) AS [MATTER],
       RTRIM(IsNull(TEN.[FEEEARN], '''')) AS [FEEEARN],
       RTRIM(IsNull(HAN.[NAME], '''')) AS [FEEEARNNAME],
       TEN.[DATE],
       TEN.[TIME],
       ' + @UnitsField + ',
       RTRIM(IsNull(TEN.[COMMENT], '''')) AS [COMMENT],
       RTRIM(IsNull(TEN.[TIMEORCHARGE], '''')) AS [TIMEORCHARGE],
       RTRIM(IsNull(TEN.[Rate], 0)) AS [Rate],
       IsNull(TEN.[' + @ChargeField + '], 0) AS [CHARGEVALUE],
       RTRIM(IsNull(TEN.[TASK], '''')) AS [TASK],
       RTRIM(IsNull(TEN.[REC_IRR], '''')) AS [REC_IRR],
       CASE WHEN TEN.[WriteOffDT] IS NOT NULL
                 THEN ''w/o''
            WHEN IsNull(TEN.[INVOICENO], 0) = 0
                 THEN ''unbilled''
            ELSE Convert(varchar(10), TEN.[INVOICENO]) END AS [InvoiceNo],
       IsNull(TEN.[RECORDID], 0) AS [RecordID],
       IsNull(CONVERT(varchar(20), TEN.[WriteOffDT], 106), '''') AS [WriteOffDate],
       IsNull(TEN.[WriteOffID], 0) AS [WriteOffID]
  FROM [dbo].[TimeEntry] TEN
       LEFT OUTER JOIN [dbo].[Handlers] HAN
                    ON HAN.[CODE] = TEN.[FEEEARN]
 WHERE TEN.[RECORDID] = @RECORDID
  
RETURN
END'

EXEC (@Command)

GO

/************************************************************************
*
* LIST BILLS - This is SAM4, but there is a "placeholder" function for SAM3.5
*
*************************************************************************/
DECLARE @command varchar(2000)
DECLARE @SAM4 int
DECLARE @BHTable varchar(20)
DECLARE @MATCode varchar(20)
DECLARE @InvoiceNo varchar(20)
DECLARE @BillDesc varchar(20)
DECLARE @Addressee varchar(20)
DECLARE @InvoiceTo varchar(20)
DECLARE @Address varchar(20)
DECLARE @REF varchar(20)
DECLARE @FECODE varchar(20)
DECLARE @TYPE varchar(20)
DECLARE @BILLINGID varchar(20)
DECLARE @BillDate varchar(20)

SET @SAM4 = 0
IF EXISTS(SELECT *
            FROM sysobjects SO
           WHERE SO.[name] = 'BillHead')
   SET @SAM4 = 1           

IF (@SAM4 = 0)
  BEGIN
    SET @BHTable = 'BillHeader'
    SET @MATCode = 'MATTER'
    SET @InvoiceNo = 'BillNo'
    SET @BillDesc = 'MATTERDESCRIPTION'
    SET @Addressee = 'ADDRESSEE'
    SET @InvoiceTo = ''''''
    SET @Address = ''''''
    SET @REF = 'YOURREF'
    SET @FECODE = 'OURREF'
    SET @TYPE = 'INVCR'
    SET @BILLINGID = 'BATCHNO'
    SET @BillDate = 'Date'
  END
ELSE
  BEGIN
    SET @BHTable = 'BillHead'
    SET @MATCode = 'MatterCode'
    SET @InvoiceNo = 'InvoiceNo'
    SET @BillDesc = 'BillDescription'
    SET @Addressee = 'ADDRESSEE'
    SET @InvoiceTo = 'BH.[InvoiceTo]'
    SET @Address = 'BH.[Address]'
    SET @REF = 'REF'
    SET @FECODE = 'FECODE'
    SET @TYPE = 'TYPE'
    SET @BILLINGID = 'BILLINGID'
    SET @BillDate = 'BillDate'
  END

DECLARE @MATTER varchar(20)

SET @command = 
'CREATE FUNCTION
       [dbo].[ky_WDListBills](@MATTER  varchar(20))
RETURNS @BILLS TABLE
       ([MatterCode]            varchar(20),
        [InvoiceNo]             int,
        [BillDescription]       varchar(500),
        [Addressee]             varchar(500),
        [InvoiceTo]             varchar(200),
        [Address]               varchar(500),
        [Ref]                   varchar(50),
        [FECODE]                varchar(10),
        [TYPE]                  varchar(1),
        [BILLINGID]             int,
        [BillDate]              datetime)
AS
  BEGIN
    INSERT
      INTO @BILLS
          ([MatterCode],
           [InvoiceNo],
           [BillDescription],
           [Addressee],
           [InvoiceTo],
           [Address],
           [Ref],
           [FECODE],
           [TYPE],
           [BILLINGID],
           [BillDate])
    SELECT RTRIM(ISNULL(BH.[' + @MATCode + '], '''')) AS [MatterCode],
           BH.[' + @InvoiceNo + '] AS [InvoiceNo],
           RTRIM(ISNULL(BH.[' + @BillDesc + '], '''')) AS [BillDescription],
           RTRIM(ISNULL(BH.[' + @Addressee + '], '''')) AS [Addressee],
           RTRIM(ISNULL(' + @InvoiceTo + ', '''')) AS [InvoiceTo],
           RTRIM(ISNULL(' + @Address + ', '''')) AS [Address],
           RTRIM(ISNULL(BH.[' + @REF + '], '''')) AS [REF],
           RTRIM(ISNULL(BH.[' + @FECODE + '], '''')) AS [FECODE],
           RTRIM(ISNULL(BH.[' + @TYPE + '], '''')) AS [TYPE],
           BH.[' + @BILLINGID + '] AS [BILLINGID],
           BH.[' + @BillDate + '] AS [BillDate]
      FROM [dbo].[' + @BHTable + '] BH
     WHERE BH.[' + @MATCode + '] = @MATTER
  
  RETURN
END'
   
EXEC (@command)
GO

DECLARE @SAM4 int
DECLARE @Command varchar(max)
DECLARE @ChargeCol varchar(10)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

IF (@SAM4 = 17)
  BEGIN
    SET @ChargeCol = 'Charged'
  END
ELSE
  BEGIN
    SET @ChargeCol = 'CHARGE'
  END

DECLARE @HasBilledAmount int

SELECT @HasBilledAmount = CASE COUNT(1)
                               WHEN 0 THEN 0
                          ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'BilledAmount'
 WHERE SO.[name] = 'TimeEntry'

SET @Command = 
'/************************************************************************
*
* Update Matter Time Balance
*
*************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateMatterTimeBalance]
      (@MATTER varchar(20))
AS
BEGIN   
UPDATE MAT
   SET MAT.[TimeBal] = TTL.[TOTALTIME],
       MAT.[ChargeBal] = TTL.[TOTALCHARGED] 
  FROM [dbo].[matters] MAT
       cross apply (SELECT IsNull(SUM(CASE WHEN IsNull(TIE.[' + @ChargeCol + '], 0)' + CASE WHEN @HasBilledAmount = 1 THEN ' - IsNull(TIE.[BilledAmount], 0)' ELSE '' END + ' <> 0
                                                THEN IsNull(TIE.[time], 0) 
                                           ELSE 0 END), 0) AS [TOTALTIME],
                           IsNull(SUM(IsNull(TIE.[' + @ChargeCol + '], 0)' + CASE WHEN @HasBilledAmount = 1 THEN ' - IsNull(TIE.[BilledAmount], 0)' ELSE '' END + '), 0) AS [TOTALCHARGED]
                      FROM [dbo].[TimeEntry] TIE
                     WHERE TIE.[MATTER] = MAT.[Code]
                       AND TIE.[REC_IRR] <> ''N''
                       AND TIE.[TimeorCharge] <> ''B'') TTL
 WHERE MAT.[Code] = @MATTER
 
END'
                       
EXEC (@Command)
GO

DECLARE @SAM4 int
DECLARE @Command varchar(max)
DECLARE @ChargeCol varchar(10)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

IF (@SAM4 = 17)
  BEGIN
    SET @ChargeCol = 'Charged'
  END
ELSE
  BEGIN
    SET @ChargeCol = 'CHARGE'
  END

DECLARE @HasBilledAmount int

SELECT @HasBilledAmount = CASE COUNT(1)
                               WHEN 0 THEN 0
                          ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'BilledAmount'
 WHERE SO.[name] = 'TimeEntry'

SET @Command = 
'/************************************************************************
*
* Update All Matter Time Balances
*
*************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDUpdateAllMatterTimeBalances]
AS
BEGIN   
UPDATE MAT
   SET MAT.[TimeBal] = TTL.[TOTALTIME],
       MAT.[ChargeBal] = TTL.[TOTALCHARGED] 
  FROM [dbo].[matters] MAT
       cross apply (SELECT IsNull(SUM(CASE WHEN IsNull(TIE.[' + @ChargeCol + '], 0)' + CASE WHEN @HasBilledAmount = 1 THEN ' - IsNull(TIE.[BilledAmount], 0)' ELSE '' END + ' <> 0
                                                THEN IsNull(TIE.[time], 0) 
                                           ELSE 0 END), 0) AS [TOTALTIME],
                           IsNull(SUM(IsNull(TIE.[' + @ChargeCol + '], 0)' + CASE WHEN @HasBilledAmount = 1 THEN ' - IsNull(TIE.[BilledAmount], 0)' ELSE '' END + '), 0) AS [TOTALCHARGED]
                      FROM [dbo].[TimeEntry] TIE
                     WHERE TIE.[MATTER] = MAT.[Code]
                       AND TIE.[REC_IRR] <> ''N'' 
                       AND TIE.[TimeorCharge] <> ''B'') TTL
 
END'
                       
EXEC (@Command)
GO

/************************************************************************
*
* Recent Matter List
*
*************************************************************************/
Create Function [dbo].[ky_WDRecentMatterList](@Handler varchar(10))
RETURNS @MATZ TABLE
       ([CODE]      varchar(20))
AS       
BEGIN  
  INSERT
    INTO @MATZ
        ([CODE])
  SELECT MAT.[Code] AS [MatterCode]
    FROM [dbo].[matters] MAT
         --INNER JOIN [dbo].[CONTACTS] CON
         --        ON CON.[CODE] = MAT.[CLIENTCODE]
         INNER JOIN [dbo].[Handlers] HAN
                    LEFT OUTER JOIN [dbo].[Handlers] TEA
                                 ON TEA.[Code] = HAN.[Team]
                 ON HAN.[Code] = MAT.[FECode]
         --LEFT OUTER JOIN [dbo].[Departments] DEP
         --             ON DEP.[Code] = MAT.[Dept]
         --LEFT OUTER JOIN [dbo].[WorkTypes] WKT
         --             ON WKT.[Code] = MAT.[WType]
         LEFT OUTER JOIN [dbo].[RecentMatterList] RML
                      ON RML.[FEE] = @Handler
                     AND RML.[Matter] = MAT.[Code]
   WHERE [MAT].[Code] is not null
ORDER BY RML.[datefield] desc, MAT.[Code]

RETURN
END
GO

DECLARE @command varchar(max)
DECLARE @SAM4 int
DECLARE @CHARGECOLUMN varchar(10)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

IF (@SAM4 = 17)
  BEGIN
    SET @CHARGECOLUMN = 'CHARGED'
  END
ELSE
  BEGIN
    SET @CHARGECOLUMN = 'CHARGE'
  END
  
DECLARE @HasBilledAmount int

SELECT @HasBilledAmount = CASE COUNT(1)
                               WHEN 0 THEN 0
                          ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'BilledAmount'
 WHERE SO.[name] = 'TimeEntry'

DECLARE @HasIncludeInBill int

SELECT @HasIncludeinBill = CASE COUNT(1)
                                WHEN 0 THEN 0
                           ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'IncludeInBill'
 WHERE SO.[name] = 'TimeEntry'

SET @command = 'CREATE PROCEDURE
       [dbo].[ky_WDTimeWriteoff]
      (@TIMSER      varchar(max),
       @FE          varchar(10),
       @matter      varchar(20),
       @woDate      varchar(8))
AS
BEGIN

BEGIN TRANSACTION

DECLARE @idoc int
DECLARE @Continue int
DECLARE @MAXID int
DECLARE @NEWMAXID int

DECLARE @WOT TABLE
       ([ID]           int identity(0, 1),
        [HANDLER]      varchar(10),
        [TOTALCHARGE]  decimal(7, 2),
        [TOTALTIME]    int)

EXEC sp_xml_preparedocument @idoc OUTPUT, @TIMSER 

SET @Continue = 0

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          SELECT @MAXID = IDENT_CURRENT(''[dbo].[TimeEntry]'')
      
          IF (@@Error <> 0)
            SET @Continue = 1
      
          SET @MAXID = @MAXID + 1
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT
            INTO [dbo].[TimeEntryLog]
                ([TimeId],
                 [FromMatter],
                 [ToMatter],
                 [TrDate],
                 [TrBy])
          SELECT TIE.[RECORDID],
                 TIE.[MATTER],
                 TIE.[MATTER],
                 @woDate,
                 ''w/o''
            FROM OPENXML(@idoc, ''ute/r'', 2)
                    WITH(RecordID   int    ''.'') UTE
                 INNER JOIN [dbo].[TimeEntry] TIE
                         ON TIE.[RECORDID] = UTE.[RecordID]
                        AND TIE.[TASK] <> ''WRI''
                        AND IsNull(TIE.[WriteOffID], 0) = 0
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT
            INTO @WOT
                ([HANDLER],
                 [TOTALCHARGE],
                 [TOTALTIME])
            SELECT TIE.[FEEEARN],
                   ISNULL(SUM(IsNull(TIE.[' + @CHARGECOLUMN + '], 0)), 0),
                   ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0)
              FROM OPENXML(@idoc, ''ute/r'', 2)
                    WITH(RecordID   int    ''.'') UTE
                   INNER JOIN [dbo].[TimeEntry] TIE
                           ON TIE.[RECORDID] = UTE.[RecordID]
                          AND TIE.[TASK] <> ''WRI''
                          AND IsNull(TIE.[WriteOffID], 0) = 0
          GROUP BY TIE.[FEEEARN]
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
        
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          UPDATE TIE
             SET TIE.[INVOICENO] = 0,
                 TIE.[WriteOffDT] = @woDate,
                 TIE.[WriteOffID] = @MAXID + WOT.[ID]' + CASE WHEN @HasBilledAmount = 1 THEN ',
                 TIE.[BilledAmount] = NULL' ELSE '' END + ' 
            FROM OPENXML(@idoc, ''ute/r'', 2)
                    WITH(RecordID   int    ''.'') UTE
                 INNER JOIN [dbo].[TimeEntry] TIE
                         ON TIE.[RECORDID] = UTE.[RecordID]
                        AND TIE.[TASK] <> ''WRI''
                        AND IsNull(TIE.[WriteOffID], 0) = 0
                 INNER JOIN @WOT WOT
                            ON WOT.[HANDLER] = TIE.[FEEEARN]
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

--  SET IDENTITY_INSERT [dbo].[TimeEntry] ON

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT
            INTO [dbo].[TimeEntry]
                ([MATTER],
                 [FEEEARN],
                 [DATE],
                 [TIME],
                 [' + @CHARGECOLUMN + '],
                 [RATE],
                 [TASK],
                 [TIMEORCHARGE],
                 [COMMENT],
                 [NCCODE],
                 [DOCKET],
                 [TEAM],
                 [TRACKREF],
                 [REC_IRR],
                 [PERIOD],
                 [YEAR],
                 [ACTIONID],
                 [StageCode],
--                 [RECORDID],
                 [BILLED],
                 [INVOICENO],
                 [BILLINGPERIOD],
                 [BILLINGYEAR],
                 [OPENINV]' + CASE WHEN @SAM4 = 17 THEN '' WHEN @HasIncludeInBill = 0 THEN '' ELSE ',
                 [IncludeInBill]' END + ')
          SELECT @matter,
                 HAN.[CODE],
                 @woDate,
                 -WOT.[TOTALTIME],
                 -WOT.[TOTALCHARGE],
                 1,
                 ''WRI'',
                 ''T'',
                 ''Write-off'',
                 '''',
                 0,
                 HAN.[TEAM],
                 0,
                 ''C'',
                 1,
                 LEFT(@woDate, 4),
                 NULL,
                 NULL,
--                 WOT.[ID] + @MAXID,
                 0,
                 0,
                 0,
                 0,
                 ''''' +  + CASE WHEN @SAM4 = 17 THEN '' WHEN @HasIncludeInBill = 0 THEN '' ELSE ',
                 1' END + '
            FROM @WOT WOT
                 INNER JOIN [dbo].[Handlers] HAN
                         ON HAN.[CODE] = WOT.[HANDLER]
           WHERE WOT.[TOTALCHARGE] <> 0
              OR WOT.[TOTALTIME] <> 0
        ORDER BY WOT.[ID]

        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

--  SET IDENTITY_INSERT [dbo].[TimeEntry] OFF

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
		  SELECT @NEWMAXID = ISNull(MAX([RECORDID]), 0) FROM [dbo].[TimeEntry]
		  SELECT @MAXID = ISNULL(MAX(@MAXID + [ID]), 0) FROM @WOT

--          SELECT @MAXID = ISNULL(MAX(TIE.[RECORDID]), 0)
--            FROM [dbo].[TimeEntry] TIE

--          DBCC CHECKIDENT([TimeEntry], RESEED, @MAXID)
          
          IF (@@Error <> 0)
            SET @Continue = 1

          IF (@MAXID <> @NEWMAXID)
            SET @Continue = 1    
      
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

EXEC sp_xml_removedocument @idoc

IF (@Continue = 0)
  COMMIT
ELSE
  ROLLBACK

END'

EXEC (@COMMAND)
GO

DECLARE @command varchar(max)
DECLARE @SAM4 int
DECLARE @CHARGECOLUMN varchar(10)

SELECT @SAM4 = SC.[length]
  FROM sysobjects SO
       inner join syscolumns SC
               on SC.[id] = SO.[id]
              and SC.[name] = 'MATTER'
 WHERE SO.[name] = 'TimeEntry'
   AND SO.[xtype] = 'U'

IF (@SAM4 = 17)
  BEGIN
    SET @CHARGECOLUMN = 'CHARGED'
  END
ELSE
  BEGIN
    SET @CHARGECOLUMN = 'CHARGE'
  END

DECLARE @HasBilledAmount int

SELECT @HasBilledAmount = CASE COUNT(1)
                               WHEN 0 THEN 0
                          ELSE 1 END
  FROM sysobjects SO
       INNER JOIN syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] = 'BilledAmount'
 WHERE SO.[name] = 'TimeEntry'

SET @command = 'CREATE PROCEDURE
       [dbo].[ky_WDSetTimeInvoiceNo]
      (@InvoiceNo int,
       @TIMSER VARCHAR(MAX))
AS
BEGIN

declare @msg VARCHAR(8)
DECLARE @Continue int
declare @updWO table
       (WriteOffID  int)

DECLARE @idoc int

BEGIN TRANSACTION

SET @Continue = 0

EXEC sp_xml_preparedocument @idoc OUTPUT, @TIMSER 

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT
            INTO @updWO
                ([WriteOffID])
          SELECT DISTINCT
                 TIE.[WriteOffID] 
            FROM OPENXML(@idoc, ''ute/r'', 2)
                    WITH(RecordID   int    ''.'') UTE
                 INNER JOIN [dbo].[TimeEntry] TIE
                         ON TIE.[RECORDID] = UTE.[RecordID]
                        AND IsNull(TIE.[WriteOffID], 0) <> 0
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          UPDATE TIE
             SET TIE.[INVOICENO] = @InvoiceNo,
                 TIE.[WriteOffDT] = NULL,
                 TIE.[WriteOffID] = NULL' + CASE WHEN @HasBilledAmount = 1 THEN ',
                 TIE.[BilledAmount] = CASE WHEN ISNULL(@InvoiceNo, 0) = 0
                                                THEN NULL
                                           ELSE TIE.' + @CHARGECOLUMN + ' END' ELSE '' END + '
            FROM OPENXML(@idoc, ''ute/r'', 2)
                    WITH(RecordID   int    ''.'') UTE
                 INNER JOIN [dbo].[TimeEntry] TIE
                         ON TIE.[RECORDID] = UTE.[RecordID]
                        AND TIE.[TASK] <> ''WRI''
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END

IF (@invoiceno = 0)
  BEGIN
    SET @msg = ''unbilled''
  END
ELSE
  BEGIN
    SET @msg = ''I'' + RIGHT(''00000000'' + convert(VARCHAR(8), @InvoiceNo), 7)
  END

  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          DELETE WOT
            FROM @updWO WO
                 INNER JOIN [dbo].[TimeEntry] WOT
                         ON WOT.[RECORDID] = WO.[WriteOffID]
                 CROSS APPLY (SELECT COUNT(1) AS [TOTAL]
                                FROM [dbo].[TimeEntry] TIE
                               WHERE TIE.[WriteOffID] = WO.[WriteOffID]) WOE
           WHERE WOE.[TOTAL] = 0
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
                     
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          UPDATE WOT
             SET WOT.[TIME] = -WOE.[TIME],
                 WOT.[' + @CHARGECOLUMN  + '] = -WOE.[CHARGE]
            FROM @updWO WO
                 INNER JOIN [dbo].[TimeEntry] WOT
                         ON WOT.[RECORDID] = WO.[WriteOffID]
                 CROSS APPLY (SELECT IsNull(SUM(IsNull(TIE.[TIME], 0)), 0) AS [TIME],
                                     IsNull(SUM(IsNull(TIE.[' + @CHARGECOLUMN  + '], 0)), 0) AS [CHARGE]
                                FROM [dbo].[TimeEntry] TIE
                               WHERE TIE.[WriteOffID] = WO.[WriteOffID]) WOE
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
  
  IF (@Continue = 0)
    BEGIN
      BEGIN TRY
        BEGIN
          INSERT
            INTO [dbo].[TimeEntryLog]
                ([TimeId],
                 [FromMatter],
                 [ToMatter],
                 [TrDate],
                 [TrBy])
          SELECT TIE.[RECORDID],
                 TIE.[MATTER],
                 TIE.[MATTER],
                 getDate(),
                 @msg
            FROM OPENXML(@idoc, ''ute/r'', 2)
                    WITH(RecordID   int    ''.'') UTE
                 INNER JOIN [dbo].[TimeEntry] TIE
                         ON TIE.[RECORDID] = UTE.[RecordID]
                        AND TIE.[TASK] <> ''WRI''
        END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
             
EXEC sp_xml_removedocument @idoc

IF (@Continue = 0)
  COMMIT
ELSE
  ROLLBACK

END'

EXEC (@command)
GO


/************************************************************************
*
* Delete Action - deletes the action, as well as associated 
* Diary Attachments, Diary Delegations, etc.
*
*************************************************************************/
Create Procedure [dbo].[ky_WDDeleteAction]
                (@ActionID int)
AS
BEGIN
  DECLARE @Continue int

  BEGIN TRANSACTION
  
  SET @Continue = 0
  
  If (@Continue = 0)
    BEGIN
      BEGIN TRY
          BEGIN
            DELETE [dbo].[DiaryAttachments]
             WHERE [DIARYID] = @ActionID

            DELETE [dbo].[DiaryDelegations]
             WHERE [ACTIONID] = @ActionID

            DELETE [dbo].[DiaryLinks]
             WHERE [ACTIONID] = @ActionID

            DELETE [dbo].[DiaryTemp]
             WHERE [ACTIONID] = @ActionID

            DELETE [dbo].[diary]
             WHERE [ACTIONID] = @ActionID
          END
      END TRY
      BEGIN CATCH
        SET @Continue = 1
      END CATCH
    END
    
  IF (@Continue = 0)
    COMMIT
  ELSE
    ROLLBACK
  
END
GO

/*******************************************************************************************
 *
 * ky_WDGetNoteTAs
 *    returns a list of likely candidates for the "Note" action.
 *
 *******************************************************************************************/
Create function 
       [dbo].[ky_WDGetNoteTAs]
      (@Case varchar(20))
RETURNS @TAC Table
       ([ACTIONCODE]     varchar(20),
        [WKTCODE]        varchar(20),
        [DESC]           varchar(300),
        [WKDESC]         varchar(300),
        [ISDEFAULT]      int)
AS
BEGIN
  INSERT
    INTO @TAC
        ([ACTIONCODE],
         [WKTCODE],
         [DESC],
         [WKDESC],
         [ISDEFAULT])
  select RTRIM(ISNULL(TAC.[ACTIONCODE], '')),
         RTRIM(ISNULL(TAC.[WKTCODE], '')),
         RTRIM(ISNULL(TAC.[DESC], '')),
         RTRIM(ISNULL(TMP.[WKDESC], '')),
         CASE WHEN RTRIM(ISNULL(DTA.[Action], '')) = TAC.[ActionCode]
                   THEN 1
              ELSE 0 END
    from [dbo].[TemplateActions] TAC
         INNER JOIN [dbo].[ActionWorkTypes] AWT
                 ON AWT.[ACTIONCODE] = TAC.[ACTIONCODE]
                AND AWT.[WORKTYPE] = TAC.[WKTCODE]
         LEFT OUTER JOIN [dbo].[Templates] TMP
                      ON TMP.[WKCODE] = TAC.[WKTCODE]
         LEFT OUTER JOIN [dbo].[CaseMaster] CSM
                      ON CSM.[CSCODE] = @Case
         OUTER APPLY (select top 1 [Action] From [dbo].[DefaultNoteTA]) DTA
ORDER BY CASE WHEN TAC.[ACTIONCODE] = DTA.[Action]
                   THEN 0
              WHEN TAC.[ACTIONCATEGORY] = 'N' AND TAC.[WKTCODE] = CSM.[CSWKTCODE] AND TAC.[DESC] LIKE '%note%'
                   THEN 1
              WHEN TAC.[ACTIONCATEGORY] = 'N' AND TAC.[WKTCODE] = CSM.[CSWKTCODE]
                   THEN 2
              WHEN TAC.[ACTIONCATEGORY] = 'N' AND TAC.[DESC] LIKE '%note%'
                   THEN 3
              WHEN TAC.[ACTIONCATEGORY] = 'N'
                   THEN 4
              WHEN TAC.[WKTCODE] = CSM.[CSWKTCODE]
                   THEN 5
              WHEN TAC.[DESC] = 'Note'
                   THEN 6
              WHEN TAC.[DESC] = 'Note to File'
                   THEN 7
              WHEN TAC.[DESC] LIKE '%note%'
                   THEN 8
              WHEN TAC.[DESC] >= 'a'
                   THEN 9
              ELSE 10 END,
         TAC.[ACTIONCODE],
         TAC.[DESC]
RETURN
END         


GO

/*******************************************************************************************
 *
 * ky_WDGetPhoneTAs
 *    returns a list of likely candidates for the "Phone" action.
 *
 *******************************************************************************************/
Create function 
       [dbo].[ky_WDGetPhoneTAs]
      (@Case varchar(20))
RETURNS @TAC Table
       ([ACTIONCODE]     varchar(20),
        [WKTCODE]        varchar(20),
        [DESC]           varchar(300),
        [WKDESC]         varchar(300),
        [ISDEFAULT]      int)
AS
BEGIN
  INSERT
    INTO @TAC
        ([ACTIONCODE],
         [WKTCODE],
         [DESC],
         [WKDESC],
         [ISDEFAULT])
  select RTRIM(ISNULL(TAC.[ACTIONCODE], '')),
         RTRIM(ISNULL(TAC.[WKTCODE], '')),
         RTRIM(ISNULL(TAC.[DESC], '')),
         RTRIM(ISNULL(TMP.[WKDESC], '')),
         CASE WHEN RTRIM(ISNULL(DTA.[Action], '')) = TAC.[ActionCode]
                   THEN 1
              ELSE 0 END
    from [dbo].[TemplateActions] TAC
         INNER JOIN [dbo].[ActionWorkTypes] AWT
                 ON AWT.[ACTIONCODE] = TAC.[ACTIONCODE]
                AND AWT.[WORKTYPE] = TAC.[WKTCODE]
         LEFT OUTER JOIN [dbo].[Templates] TMP
                      ON TMP.[WKCODE] = TAC.[WKTCODE]
         LEFT OUTER JOIN [dbo].[CaseMaster] CSM
                      ON CSM.[CSCODE] = @Case
         OUTER APPLY (select top 1 [Action] From [dbo].[DefaultPhoneTA]) DTA
ORDER BY CASE WHEN TAC.[ACTIONCODE] = DTA.[Action]
                   THEN 0
              WHEN TAC.[ACTIONCATEGORY] = 'T' AND TAC.[WKTCODE] = CSM.[CSWKTCODE] AND TAC.[DESC] LIKE '%phone%'
                   THEN 1
              WHEN TAC.[ACTIONCATEGORY] = 'T' AND TAC.[WKTCODE] = CSM.[CSWKTCODE]
                   THEN 2
              WHEN TAC.[ACTIONCATEGORY] = 'T' AND TAC.[DESC] LIKE '%phone%'
                   THEN 3
              WHEN TAC.[ACTIONCATEGORY] = 'T'
                   THEN 4
              WHEN TAC.[WKTCODE] = CSM.[CSWKTCODE]
                   THEN 5
              WHEN TAC.[DESC] LIKE '%phone%'
                   THEN 6
              WHEN TAC.[DESC] >= 'a'
                   THEN 7
              ELSE 8 END,
         TAC.[ACTIONCODE],
         TAC.[DESC]
RETURN
END         

GO

/*******************************************************************************************
 *
 * ky_WDGetEmailTAs
 *    returns a list of likely candidates for the "Email" action.
 *
 *******************************************************************************************/
Create function 
       [dbo].[ky_WDGetEmailTAs]
      (@Case varchar(20))
RETURNS @TAC Table
       ([ACTIONCODE]     varchar(20),
        [WKTCODE]        varchar(20),
        [DESC]           varchar(300),
        [WKDESC]         varchar(300),
        [ISDEFAULT]      int)
AS
BEGIN
  INSERT
    INTO @TAC
        ([ACTIONCODE],
         [WKTCODE],
         [DESC],
         [WKDESC],
         [ISDEFAULT])
  select RTRIM(ISNULL(TAC.[ACTIONCODE], '')),
         RTRIM(ISNULL(TAC.[WKTCODE], '')),
         RTRIM(ISNULL(TAC.[DESC], '')),
         RTRIM(ISNULL(TMP.[WKDESC], '')),
         CASE WHEN RTRIM(ISNULL(DTA.[Action], '')) = TAC.[ActionCode]
                   THEN 1
              ELSE 0 END
    from [dbo].[TemplateActions] TAC
         INNER JOIN [dbo].[ActionWorkTypes] AWT
                 ON AWT.[ACTIONCODE] = TAC.[ACTIONCODE]
                AND AWT.[WORKTYPE] = TAC.[WKTCODE]
         LEFT OUTER JOIN [dbo].[Templates] TMP
                      ON TMP.[WKCODE] = TAC.[WKTCODE]
         LEFT OUTER JOIN [dbo].[CaseMaster] CSM
                      ON CSM.[CSCODE] = @Case
         OUTER APPLY (select top 1 [Action] From [dbo].[DefaultEmailTA]) DTA
ORDER BY CASE WHEN TAC.[ACTIONCODE] = DTA.[Action]
                   THEN 0
              WHEN TAC.[ACTIONCATEGORY] = 'E' AND TAC.[WKTCODE] = CSM.[CSWKTCODE] AND TAC.[DESC] LIKE '%e%mail%'
                   THEN 1
              WHEN TAC.[ACTIONCATEGORY] = 'E' AND TAC.[WKTCODE] = CSM.[CSWKTCODE]
                   THEN 2
              WHEN TAC.[ACTIONCATEGORY] = 'E' AND TAC.[DESC] LIKE '%e%mail%'
                   THEN 3
              WHEN TAC.[ACTIONCATEGORY] = 'E'
                   THEN 4
              WHEN TAC.[WKTCODE] = CSM.[CSWKTCODE]
                   THEN 5
              WHEN TAC.[DESC] LIKE '%e%mail%'
                   THEN 6
              WHEN TAC.[DESC] >= 'a'
                   THEN 7
              ELSE 8 END,
         TAC.[ACTIONCODE],
         TAC.[DESC]
RETURN
END         

GO

/*******************************************************************************************
 *
 * ky_WDGetTAList
 *    Returns a list of Template Actions for the appropriate workflow. If there is a default Note
 *    action or a default Phone action, this will be listed at the top of the list, regardless of
 *    the workflow.
 *
 *******************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDGetTAList]
      (@matter           varchar(20),
       @WKTCode          varchar(10),
       @ActionCategory   varchar(1))
RETURNS @TA TABLE
       ([WORKTYPE]       varchar(10),
        [SEQ]            int,
        [ACTIONCODE]     varchar(20),
        [DESC]           varchar(255),
        [ActionCategory] varchar(1),
        [Highlighted]    varchar(1),
        [Publisher]      varchar(1),
        [Billable]       varchar(1),
        [Priority]       varchar(10),
        [Status]         varchar(5))
AS
BEGIN
  
  DECLARE @DEFAULTTA varchar(20)
     
  SET @ActionCategory = RTRIM(ISNULL(@ActionCategory, ''))
  SET @WKTCODE = RTRIM(ISNULL(@WKTCODE, ''))

  IF (@ActionCategory = 'N')
    BEGIN
      SELECT @DEFAULTTA = DA.[Action]  
        from [dbo].[DefaultNoteTA] DA
    END

  IF (@ActionCategory = 'T')
    BEGIN
      SELECT @DEFAULTTA = DA.[Action]  
        from [dbo].[DefaultPhoneTA] DA
    END    
  INSERT
    INTO @TA
        ([WORKTYPE],
         [SEQ],
         [ACTIONCODE],
         [DESC],
         [ActionCategory],
         [Highlighted],
         [Publisher],
         [Billable],
         [Priority],
         [Status])
  SELECT RTRIM(ISNULL(AWT.[WORKTYPE], '')) AS [WORKTYPE],
         AWT.[SEQ],
         RTRIM(ISNULL(AWT.[ACTIONCODE], '')) AS [ACTIONCODE],
         REPLACE(REPLACE(RTRIM(ISNULL(TA.[DESC], '')), CHAR(13) + CHAR(10), ' '), CHAR(10), ' ') AS [DESC],
         ISNULL(TA.[ACTIONCATEGORY], 'A') AS [ACTIONCATEGORY],
         CASE WHEN ISNULL(TA.[HIGHLIGHTED], 'N') = 'Y'
                   THEN 'Y' 
              ELSE 'N' END AS [HIGHLIGHTED],
         ISNULL(TA.[PUBLISHER], 'N') AS [PUBLISHER],
         ISNULL(TA.[BILLABLE], 'N') AS [BILLABLE],
         RTRIM(ISNULL(TA.[PRIORITY], 'Normal')) AS [PRIORITY],
         RTRIM(ISNULL(TA.[STATUS], 'NA')) AS [STATUS]
    FROM [dbo].[CaseMaster] CSM
         INNER JOIN [dbo].[ActionWorkTypes] AWT
                    INNER JOIN [dbo].[TemplateActions] TA
                            ON TA.[ACTIONCODE] = AWT.[ACTIONCODE]
                 ON (    @WKTCODE = ''
                     AND AWT.[WORKTYPE] = CSM.[CSWKTCODE])
                 OR (    @WKTCODE <> ''
                     AND AWT.[WORKTYPE] = @WKTCODE)
                 OR TA.[ACTIONCODE] = @DEFAULTTA
   WHERE CSM.[CSCODE] = @matter
ORDER BY CASE WHEN @ActionCategory = ''
                   THEN 0
              WHEN @ActionCategory = TA.[ActionCategory]
                   THEN CASE WHEN TA.[ACTIONCODE] = @DEFAULTTA 
                                  THEN 1
                             WHEN @ActionCategory = 'N' AND TA.[DESC] LIKE '%note%'
                                  THEN 2
                             WHEN @ActionCategory = 'P' AND TA.[DESC] LIKE '%appointment%'
                                  THEN 2
                             WHEN @ActionCategory = 'T' AND TA.[DESC] LIKE '%phone%'
                                  THEN 2
                             ELSE 3 END
              ELSE 4 END,
         AWT.[SEQ]
RETURN
END
GO

/*******************************************************************************************
 *
 * ky_WDStoreFileBlob
 *    Stores a file that is accessible from the SQL Server as a BLOB in the "HandlerImages" table
 *    for the current handler (with ImageType 101). The calling process can then retrieve the file
 *    directly from SQL, requiring no direct access to the file system. Nice for Web Servers.
 *
 *******************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDStoreFileBlob]
      (@handler   varchar(10),
       @filepath  varchar(300))
AS
BEGIN
  DECLARE @command varchar(2000)
  
  DELETE HIM
    FROM [dbo].[HandlerImages] HIM
   WHERE HIM.[Handler] = @handler
     AND HIM.[ImageType] = 101

  SET @command = '  INSERT
    INTO [dbo].[HandlerImages]
        ([Handler],
         [ImageType],
         [Image])
  SELECT ''' + REPLACE(@handler, '''', '''''') + ''',
         101,
		 BulkColumn 
    FROM OPENROWSET(Bulk ''' + REPLACE(@filepath, '''', '''''') + ''', SINGLE_BLOB) AS BLOB'
    
  EXEC (@command)
END
GO

Create Function
       [dbo].[ky_WDReadTimeEntryLog]
      (@timeID int)
RETURNS @TLG Table
       ([TrDate]      datetime,
        [TrDateFmt]   varchar(11),
        [FromMatter]  varchar(20),
        [ToMatter]    varchar(20),
        [Action]      varchar(50))
AS
BEGIN

  INSERT
    INTO @TLG
        ([TrDate],
         [TrDateFmt],
         [FromMatter],
         [ToMatter],
         [Action])
  select TEL.[TrDate],
         CONVERT(varchar(11), TEL.[trDate], 106) AS [TrDateFmt],
         CASE WHEN TEL.[FromMatter] = TEL.[ToMatter]
                   THEN ''
              ELSE TEL.[FromMatter] END AS [FromMatter],
         TEL.[ToMatter] AS [Matter],
         CASE WHEN TrBy = 'TR'
                   THEN 'Transfer'
              WHEN TrBy = 'UP'
                   THEN 'Updated'
              WHEN TrBy = 'w/o'
                   THEN 'Written Off'
              WHEN TrBy = 'unbilled'
                   THEN 'marked as unbilled'
              WHEN (    (LEFT(convert(nvarchar(20), trBy), 1) = N'I')
                    AND (ISNUMERIC(RIGHT(convert(nvarchar(20), trBy), len(trBy) - 1)) = 1))
                   THEN 'Invoiced to Invoice Number ' + convert(varchar(20), convert(int, RIGHT(convert(nvarchar(20), trBy), len(trBy) - 1)))
              ELSE trBY END AS [Action]
    from timeentrylog TEL
   where TEL.[TimeId] = @timeID
ORDER BY TEL.[Id] DESC
RETURN
END
GO

/*******************************************************************************************
 *
 * ky_WDCopyTimeEntry
 *    Copies a Time Entry, either to the same case as the original Time Entry or to a new case.
 *    This procedure is completely version independent.
 *
 *******************************************************************************************/
CREATE PROCEDURE
       [dbo].[ky_WDCopyTimeEntry]
      (@RECID             int,
       @MATTER varchar(20))
AS
BEGIN

DECLARE @FIELDS varchar(2000)
DECLARE @COMMAND varchar(2000)

SET @FIELDS = ''

select @FIELDS = @FIELDS 
               + CASE WHEN @FIELDS <> ''
                           THEN ',' + Char(13) + CHAR(10) + '       '
                      ELSE '' END
               + '[' + SC.[name] + ']'
  from sysobjects SO
       inner join syscolumns SC
               ON SC.[id] = SO.[id]
              AND SC.[name] <> 'RECORDID'
 where SO.[name] = 'TimeEntry'
 
SET @COMMAND = 'INSERT
  INTO [dbo].[TimeEntry]
      (' + @FIELDS + ')' + Char(13) + CHAR(10) + 
'SELECT ' + REPLACE(REPLACE(@FIELDS, 
                            '[MATTER]', 
                            CASE WHEN RTRIM(ISNULL(@matter, '')) = '' 
                                      THEN '[MATTER]' 
                                 ELSE '''' + @MATTER + '''' END),
                    '[',
                    'TIE.[') + Char(13) + CHAR(10) + 
'  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[RECORDID] = ' + CONVERT(varchar(10), @RECID)
      
EXEC (@COMMAND)

SELECT @MATTER = CASE WHEN RTRIM(ISNULL(@MATTER, '')) = '' 
                           THEN TIE.[MATTER] 
                      ELSE @MATTER END
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[RECORDID] = @RECID
 
EXEC ky_WDUpdateMatterTimeBalance @MATTER

END
GO

create function 
       [dbo].[ky_WDAllCaseAssociates]()
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100))
AS
BEGIN

    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email])
    SELECT CASE WHEN RTrim(IsNull(CAN.[NAME], '')) = ''
                     THEN CONVERT(varchar(200), RTRIM(ISNULL(CAN.[LEGALNAME], '')))
                ELSE CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) END AS [NAME],
           CASE WHEN RTrim(IsNull(CAN.[ADDRESS], '')) = ''
                     THEN SUBSTRING(CAN.[LegalAddress], 1, 200)
                ELSE SUBSTRING(CAN.[Address], 1, 200) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL]
      FROM [dbo].[CaseAssociatesNames] CAN
    UNION
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           SUBSTRING(CAN.[Address], 1, 200) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL]
      FROM (SELECT CAC.[NAMECODE],
                   CAC.[KEYID],
                   CASE WHEN RTrim(IsNull(CAC.[NAME], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CAC.[NAME], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CAC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CAC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CAC.[PHONE], '')) = ''
                             THEN RTRIM(IsNull(CNN.[PHONENO], ''))
                        ELSE RTrim(IsNull(CAC.[PHONE], '')) END AS [PHONENO],
                   RTrim(IsNull(CAC.[MOBILE], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CAC.[FAX], '')) = ''
                             THEN RTRIM(IsNull(CNN.[FAXNO], ''))
                        ELSE RTrim(IsNull(CAC.[FAX], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CAC.[EMAIL], '')) = ''
                             THEN RTRIM(IsNull(CNN.[EMAIL], ''))
                        ELSE RTrim(IsNull(CAC.[EMAIL], '')) END AS [EMAIL]
              FROM [dbo].[CaseAssociatesContacts] CAC
                   LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CNN
                                ON CNN.[CODE] = CAC.[NAMECODE]) CAN

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

  RETURN
END
GO
        
create function 
       [dbo].[ky_WDAllClientContacts]()
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100))
AS
BEGIN
    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           SUBSTRING(CAN.[Address], 1, 200) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL]
      FROM (SELECT CLC.[CLCODE],
                   CASE WHEN RTrim(IsNull(CLC.[CLNAMECON], '')) = ''
                             THEN RTRIM(IsNull(CNN.[NAME], ''))
                        ELSE RTrim(IsNull(CLC.[CLNAMECON], '')) END AS [NAME],
                   CASE WHEN RTrim(IsNull(CLC.[ADDRESS], '')) = ''
                             THEN RTRIM(IsNull(CNN.[ADDRESS], ''))
                        ELSE RTrim(IsNull(CLC.[ADDRESS], '')) END AS [ADDRESS],
                   CASE WHEN RTrim(IsNull(CLC.[HomePhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Tel], ''))
                        ELSE RTrim(IsNull(CLC.[HomePhone], '')) END AS [PHONENO],
                   RTrim(IsNull(CLC.[Mobile], '')) AS [MOBILENO],
                   CASE WHEN RTrim(IsNull(CLC.[WorkPhone], '')) = ''
                             THEN RTRIM(IsNull(CNN.[Fax], ''))
                        ELSE RTrim(IsNull(CLC.[WorkPhone], '')) END AS [FAXNO],
                   CASE WHEN RTrim(IsNull(CLC.[EmailAddress], '')) = ''
                             THEN RTRIM(IsNull(CNN.[email], ''))
                        ELSE RTrim(IsNull(CLC.[EmailAddress], '')) END AS [EMAIL]
              FROM [dbo].[ClientContacts] CLC
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = CLC.[CLCODE]) CAN
UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])

RETURN
END
GO

create function 
       [dbo].[ky_WDAllContacts]()
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100))
AS
BEGIN

    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CON.[NAME], ''))) AS [NAME],
           CASE WHEN RTrim(IsNull(CON.[ADDRESS], '')) = ''
                     THEN SUBSTRING(CON.[OtherAddress], 1, 200)
                ELSE SUBSTRING(CON.[Address], 1, 200) END AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CON.[Tel], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CON.[Tel], '')))
                WHEN RTrim(IsNull(CLI.[CLMOBNO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CON.[Fax], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CLI.[CLMOBNO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CON.[FAX], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CON.[email], ''))) AS [EMAIL]
      FROM [dbo].[Contacts] CON
           INNER JOIN [dbo].[client] CLI
                   ON CLI.[clcode] = CON.[code]

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])
RETURN
END
GO

create function 
       [dbo].[ky_WDAllMatterContacts]()
RETURNS @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100))
AS
BEGIN

    INSERT
      INTO @SR
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email])
    SELECT CONVERT(varchar(200), RTRIM(ISNULL(CAN.[NAME], ''))) AS [NAME],
           SUBSTRING(CAN.[Address], 1, 200) AS [ADDRESS],
           CASE WHEN RTrim(IsNull(CAN.[PHONENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[PHONENO], '')))
                WHEN RTrim(IsNull(CAN.[MOBILENO], '')) <> ''
                     THEN convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], '')))
                ELSE convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) END AS [PHONE],
           convert(varchar(30), RTrim(IsNull(CAN.[MOBILENO], ''))) AS [MOBILE],
           convert(varchar(30), RTrim(IsNull(CAN.[FAXNO], ''))) AS [FAX],
           convert(varchar(100), RTrim(IsNull(CAN.[EMAIL], ''))) AS [EMAIL]
      FROM (SELECT MAT.[CODE],
                   CNN.[CODE] AS [CLIENTCODE],
                   RTRIM(IsNull(CNN.[NAME], '')) AS [NAME],
                   RTRIM(IsNull(CNN.[ADDRESS], '')) AS [ADDRESS],
                   RTRIM(IsNull(CNN.[Tel], '')) AS [PHONENO],
                   RTRIM(IsNull(CLN.[CLMOBNO], '')) AS [MOBILENO],
                   RTRIM(IsNull(CNN.[Fax], '')) AS [FAXNO],
                   RTRIM(IsNull(CNN.[email], '')) AS [EMAIL]
              FROM [dbo].[matters] MAT
                   LEFT OUTER JOIN [dbo].[Contacts] CNN
                                ON CNN.[CODE] = MAT.[ClientCode]
                   LEFT OUTER JOIN [dbo].[client] CLN
                                ON CLN.[CLCODE] = MAT.[ClientCode]) CAN

UPDATE @SR
   SET [Phone] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Phone]),
       [Mobile] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Mobile]),
       [Fax] = [dbo].[ky_HeuristicPhoneNumber]([Address], [Fax])
RETURN
END
GO

DECLARE @command varchar(4000)
DECLARE @hasclosed int

SET @hasclosed = 0
IF exists(SELECT SC.[NAME]
            FROM sys.objects SO
                 inner join sys.columns SC
                         ON SC.[object_id] = so.[object_id]
                        and SC.[name] = 'CLOSED'
           WHERE SO.[name] = 'matters')
  BEGIN
    SET @hasclosed = 1
  END

SET @command = 'CREATE FUNCTION [dbo].[ky_WDMatSearch]
               (@SEARCH       VARCHAR(100),
                @feeearn      VARCHAR(10),
                @start        int,
                @pagesize     int)
RETURNS @MatRes TABLE
       ([id]                     int identity(1, 1),
        [CODE]                   varchar(20),
        [NAME]                   varchar(200),
        [Description]            varchar(300),
        [FECode]                 varchar(10),
        [Tel]                    varchar(30),
        [EMAIL]                  varchar(100),
        [TDBTime]                varchar(10),
        [TDBStopwatchRunning]    int,
        [TDBRecordID]            int)
AS
BEGIN
DECLARE @fePerm int

SELECT @fePerm = ISNULL(JPM.[JPER_Permissions], 0)
  FROM [dbo].[HandlerOPE] HOP
       LEFT OUTER JOIN [dbo].[JPermissions] JPM
                    ON JPM.[JPER_UserNumber] = HOP.[OPE_NUMBER]
 WHERE HOP.[HANDLER] = @feeearn

INSERT
  INTO @MatRes
      ([CODE],
       [NAME],
       [Description],
       [FECode],
       [Tel],
       [EMAIL],
       [TDBTime],
       [TDBStopwatchRunning],
       [TDBRecordID])
SELECT RTRIM(ISNULL(MAT.[CODE], '''')) AS [CODE],
       RTRIM(ISNULL(CON.[NAME], '''')) AS [NAME],
       RTRIM(ISNULL(MAT.[Description], '''')) AS [Description],
       RTRIM(ISNULL(MAT.[FECode], '''')) AS [FECode],
       RTRIM(ISNULL(CON.[Tel], '''')) AS [Tel],
       RTRIM(ISNULL(CON.[EMAIL], '''')) AS [EMAIL],
       CASE WHEN ISNULL(TDB.[TIME], 0) = 0
                 THEN ''''
            ELSE CASE WHEN ISNULL(TDB.[TIME], 0) < 0 
                           THEN ''-'' 
                      ELSE '''' END +
                      RIGHT(''00'' + convert(VARCHAR(2), FLOOR(ABS(ISNULL(TDB.[TIME], 0)) / 60)), 2) 
                            + '':'' 
                            + RIGHT(''00'' + convert(VARCHAR(2), ABS(ISNULL(TDB.[TIME], 0)) - (60 * FLOOR(ABS(ISNULL(TDB.[TIME], 0)) / 60))), 2) END AS [TDBTime],
       CASE WHEN TDB.[StopwatchStartTime] IS NULL
                 THEN 0
            ELSE 1 END AS [TDBStopwatchRunning],
       CASE WHEN TDB.[RECORDID] IS NULL
                 THEN 0
            ELSE TDB.[RECORDID] END AS [TDBRecordID]
  FROM [dbo].[Matters] MAT
       INNER JOIN [dbo].[Contacts] CON
               ON CON.[CODE] = MAT.[ClientCode]
       LEFT OUTER JOIN [dbo].[TimeDayBook] TDB
                    ON TDB.[MATTER] = MAT.[CODE]
                   AND TDB.[FEEEARN] = @feeearn
 WHERE (  MAT.[Description] LIKE @SEARCH
        OR MAT.[CODE] LIKE @SEARCH
        OR MAT.[User1] LIKE @SEARCH
        OR MAT.[User2] LIKE @SEARCH
        OR MAT.[User3] LIKE @SEARCH
        OR MAT.[YourRef] LIKE @SEARCH
        OR CON.[NAME] LIKE @SEARCH)
   AND (   (ISNULL(MAT.[Permissions], 0) = 0)
        OR ((ISNULL(MAT.[Permissions], 0) & @fePerm) <> 0))
' + CASE WHEN @hasclosed = 1
              THEN '   AND  IsNull(MAT.[Closed], '''') <> ''Y'''
         ELSE '' END + '

DELETE MR
  FROM @MatRes MR
 WHERE MR.[ID] < @start

DELETE MR
  FROM @MatRes MR
 WHERE MR.[ID] >= @start + @pagesize

RETURN

END'

EXEC (@command)
GO

CREATE FUNCTION
       [dbo].[ky_WDContactSearch]
      (@fe               varchar(10),
       @search           varchar(50),
       @mattersearch     varchar(50),
       @includeCA        int,
       @includeCC        int,
       @includeCO        int,
       @includeMC        int,
       @clientcode       varchar(10),
       @namecode         varchar(10),
       @IncludePhone     int,
       @IncludeEmails    int,
       @expand           int,
       @bycase           int,
       @start            int,
       @pagesize         int)
RETURNS @SR2 TABLE
       ([ID]                int identity(1, 1),
        [Name]              varchar(200),
        [Address]           varchar(200),
        [Phone]             varchar(30),
        [Mobile]            varchar(30),
        [Fax]               varchar(30),
        [Email]             varchar(100),
        [Case]              varchar(20),
        [Clientcode]        varchar(10),
        [Namecode]          varchar(10),
        [Cases]             int,
        [CaseCode]          varchar(20),
        [ClientName]        varchar(300),
        [CaseDescription]   varchar(300))
AS
BEGIN

DECLARE @SR TABLE
       ([Name]           varchar(200),
        [Address]        varchar(200),
        [Phone]          varchar(30),
        [Mobile]         varchar(30),
        [Fax]            varchar(30),
        [Email]          varchar(100),
        [Case]           varchar(20),
        [Clientcode]     varchar(10),
        [Namecode]       varchar(10))
        
INSERT
  INTO @SR
      ([Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode])
SELECT [Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode]
  from [dbo].[ky_WDSearchCaseAssociates3]
      (@fe,
       @search,
       @mattersearch,
       @includeCA,
       1,
       @clientcode,
       @namecode,
       @IncludePhone,
       @IncludeEmails)
       
INSERT
  INTO @SR
      ([Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode])
SELECT [Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode]
  from [dbo].[ky_WDSearchClientContacts3]
      (@fe,
       @search,
       @mattersearch,
       @includeCC,
       1,
       @clientcode,
       @namecode,
       @IncludePhone,
       @IncludeEmails)

INSERT
  INTO @SR
      ([Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode])
SELECT [Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode]
  from [dbo].[ky_WDSearchContacts3]
      (@fe,
       @search,
       @mattersearch,
       @includeCO,
       1,
       @clientcode,
       @namecode,
       @IncludePhone,
       @IncludeEmails)

INSERT
  INTO @SR
      ([Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode])
SELECT [Name],
       [Address],
       [Phone],
       [Mobile],
       [Fax],
       [Email],
       [Case],
       [ClientCode],
       [Namecode]
  from [dbo].[ky_WDSearchMatterContacts3]
      (@fe,
       @search,
       @mattersearch,
       @includeMC,
       1,
       @clientcode,
       @namecode,
       @IncludePhone,
       @IncludeEmails)
       
IF @expand = 0
  BEGIN
    INSERT
      INTO @SR2
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [Namecode],
           [Cases],
           [CaseCode],
           [ClientName],
           [CaseDescription])
      SELECT RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             Max(RES.[Case]) AS [Case],
             Max(RES.[ClientCode]) AS [ClientCode],
             Max(RES.[NameCode]) As [NameCode],
             COUNT(DISTINCT RES.[Case]) AS [Cases],
             '' AS [CaseCode],
             '' As [ClientName],
             '' As [CaseDescription]
        FROM @SR RES
    GROUP BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email]
    ORDER BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email]
  END

IF (@expand = 1) AND (@bycase = 1)
  BEGIN
    INSERT
      INTO @SR2
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [Namecode],
           [Cases],
           [CaseCode],
           [ClientName],
           [CaseDescription])
      SELECT '' AS [Name],
             '' AS [Address],
             '' AS [Phone],
             '' AS [Mobile],
             '' AS [Fax],
             '' AS [Email],
             '' AS [Case],
             @clientcode AS [ClientCode],
             @namecode As [NameCode],
             1 AS [Cases],
             RES.[Case] AS [CaseCode],
             '' As [ClientName],
             '' As [CaseDescription]
        FROM @SR RES
    GROUP BY RES.[Case]
    ORDER BY RES.[Case]
    
    UPDATE RES
       SET RES.[CaseDescription] = MS.[Description],
           RES.[ClientName] = MS.[Name]
      FROM @SR2 RES
           CROSS APPLY (SELECT MAT.[DESCRIPTION],
                               CON.[Name]
                          FROM [dbo].[matters] MAT
                               INNER JOIN [dbo].[Contacts] CON
                                       ON CON.[Code] = MAT.[ClientCode] 
                         WHERE MAT.[Code] = RES.[CaseCode]) MS
  END

IF (@expand = 1) AND (@bycase = 0)
  BEGIN
    INSERT
      INTO @SR2
          ([Name],
           [Address],
           [Phone],
           [Mobile],
           [Fax],
           [Email],
           [Case],
           [ClientCode],
           [Namecode],
           [Cases],
           [CaseCode],
           [ClientName],
           [CaseDescription])
      SELECT RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             Max(RES.[Case]) AS [Case],
             Max(RES.[ClientCode]) AS [ClientCode],
             Max(RES.[NameCode]) As [NameCode],
             1 AS [Cases],
             '' AS [CaseCode],
             '' As [ClientName],
             '' As [CaseDescription]
        FROM @SR RES
    GROUP BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             RES.[Case]
    ORDER BY RES.[Name],
             RES.[Address],
             RES.[Phone],
             RES.[Mobile],
             RES.[Fax],
             RES.[Email],
             RES.[Case]
  END

DELETE SR
  FROM @SR2 SR
 WHERE SR.[ID] < @start

DELETE SR
  FROM @SR2 SR
 WHERE SR.[ID] >= @start + @pagesize
  
RETURN
END
GO

/*******************************************************************************************
 *
 * ky_WDMatterSearch
 *    matter search based on selection criteria and searching fields such as matter description,
 *    client name, user fields etc.
 *
 *******************************************************************************************/
CREATE FUNCTION
       [dbo].[ky_WDMatterSearch]
      (@fe varchar(10),
       @contactsearch varchar(50),
       @mattersearch varchar(50),
       @docontactsearch int)
RETURNS @MS TABLE
       ([ID]                    int,
        [CODE]                  varchar(20),
        [NAME]                  varchar(300),
        [Description]           varchar(300),
        [FECode]                varchar(10),
        [Tel]                   varchar(30),
        [EMAIL]                 varchar(100),
        [TDBTime]               varchar(10),
        [TDBStopwatchRunning]   int,
        [TDBRecordID]           int)
AS
BEGIN

SET @contactsearch = RTRIM(Isnull(@contactsearch, ''))

IF (@contactsearch <> '')
  BEGIN
    SET @docontactsearch = 1
  END
ELSE
  BEGIN
    SET @docontactsearch = CASE WHEN ISNULL(@docontactsearch, 0) = 1
                                     THEN 1
                                ELSE 0 END
  END
  
IF (@docontactsearch = 1)
  BEGIN
    INSERT
      INTO @MS
          ([ID],
           [CODE],
           [NAME],
           [Description],
           [FECode],
           [Tel],
           [EMAIL],
           [TDBTime],
           [TDBStopwatchRunning],
           [TDBRecordID])
    select CS.[ID] AS [id],
           CS.[CaseCode] AS [CODE],
           CS.[ClientName] AS [NAME],
           CS.[CaseDescription] AS [CaseDescription],
           MAT.[FECode] AS [FECode],
           CON.[Tel] AS [Tel],
           CON.[email] as [EMAIL],
           CASE WHEN ISNULL(TDB.[TIME], 0) = 0
                     THEN ''
                ELSE CASE WHEN ISNULL(TDB.[TIME], 0) < 0 
                               THEN '-' 
                          ELSE '' END +
                          RIGHT('00' + convert(VARCHAR(2), FLOOR(ABS(ISNULL(TDB.[TIME], 0)) / 60)), 2) 
                                + ':' 
                                + RIGHT('00' + convert(VARCHAR(2), ABS(ISNULL(TDB.[TIME], 0)) - (60 * FLOOR(ABS(ISNULL(TDB.[TIME], 0)) / 60))), 2) END AS [TDBTime],
           CASE WHEN TDB.[StopwatchStartTime] IS NULL
                     THEN 0
                ELSE 1 END AS [TDBStopwatchRunning],
           CASE WHEN TDB.[RECORDID] IS NULL
                     THEN 0
                ELSE TDB.[RECORDID] END AS [TDBRecordID]
      from [dbo].[ky_WDContactSearch](@fe, @contactsearch, @mattersearch, 0, 1, 0, 1, '', '', 0, 0, 1, 1, 1, 100) CS
           INNER JOIN [dbo].[matters] MAT
                      inner join [dbo].[Contacts] CON
                              ON CON.[Code] = MAT.[ClientCode] 
                      LEFT OUTER JOIN [dbo].[TimeDayBook] TDB
                                   ON TDB.[MATTER] = MAT.[CODE]
                                  AND TDB.[FEEEARN] = @fe
                   ON MAT.[Code] = CS.[CaseCode]
  END
ELSE               
  BEGIN
    set @mattersearch = REPLACE('%' + @mattersearch + '%', '%%','%')

    INSERT
      INTO @MS
          ([CODE],
           [NAME],
           [Description],
           [FECode],
           [Tel],
           [EMAIL],
           [TDBTime],
           [TDBStopwatchRunning],
           [TDBRecordID])
    SELECT MS.[CODE],
           MS.[NAME],
           MS.[Description],
           MS.[FECode],
           MS.[Tel],
           MS.[EMAIL],
           MS.[TDBTime],
           MS.[TDBStopwatchRunning],
           MS.[TDBRecordID]
      FROM [dbo].[ky_WDMatSearch](@mattersearch,
                                  @fe,
                                  1,
                                  100) MS
  END
  
  RETURN
END
GO

DECLARE @command varchar(4000)
DECLARE @hasclosed int

SET @hasclosed = 0
IF exists(SELECT SC.[NAME]
            FROM sys.objects SO
                 inner join sys.columns SC
                         ON SC.[object_id] = so.[object_id]
                        and SC.[name] = 'CLOSED'
           WHERE SO.[name] = 'matters')
  BEGIN
    SET @hasclosed = 1
  END

SET @command = '/*******************************************************************************************
 *
 * WDMatterSearch
 *    simple matter search for matter search dropdown, searches ONLY the matter code
 *
 *******************************************************************************************/
CREATE FUNCTION
       [dbo].[WDMatterSearch]
      (@matter      varchar(20))
RETURNS @WK TABLE
       ([OpenOrClosed]         varchar(10),
        [MatterCode]           varchar(20),
        [ClientCode]           varchar(10),
        [MatterNo]             varchar(10),
        [ClientName]           varchar(500),
        [MatterDescription]    varchar(500))
AS
BEGIN

DECLARE @OpenCount int

IF (charindex(''/'', @matter) > 0)
    SET @matter = REPLACE(RTRIM(LTRIM(ISNULL(@matter, ''''))), ''/'', ''%/%'')
ELSE
    SET @matter = RTRIM(LTRIM(ISNULL(@matter, ''''))) + ''%''

SET @matter = REPLACE(@matter, ''%%'', ''%'')

INSERT
  INTO @WK
      ([OpenOrClosed],
       [MatterCode],
       [ClientCode],
       [MatterNo],
       [ClientName],
       [MatterDescription])
SELECT TOP 100
       ''Open'' AS [OpenOrClosed],
       MAT.[code] AS [MatterCode],
       MAT.[clientcode] AS [ClientCode],
       MAT.[matter] AS [MatterNo],
       RTRIM(ISNULL(CON.[name], '''')) AS [ClientName],
       RTRIM(ISNULL(MAT.[description], '''')) AS [MatterDescription]
  FROM [dbo].[Matters] MAT
       INNER JOIN [dbo].[contacts] CON
               ON CON.[code] = MAT.[ClientCode]
 WHERE MAT.[code] LIKE @matter' + CASE WHEN @hasclosed = 1 THEN '
   AND IsNull(MAT.[Closed], '''') <> ''Y''' ELSE '' END + '

SELECT @OpenCount = COUNT(1)
  FROM @WK

IF (@OpenCount) < 100
  BEGIN
    INSERT
      INTO @WK
          ([OpenOrClosed],
           [MatterCode],
           [ClientCode],
           [MatterNo],
           [ClientName],
           [MatterDescription])
    SELECT TOP (100 - @OpenCount)
           ''Closed'' AS [OpenOrClosed],
           MAT.[code] AS [MatterCode],
           MAT.[clientcode] AS [ClientCode],
           MAT.[matter] AS [MatterNo],
           RTRIM(ISNULL(CON.[name], '''')) AS [ClientName],
           RTRIM(ISNULL(MAT.[description], '''')) AS [MatterDescription]
      FROM [dbo].[' + CASE WHEN @hasclosed = 1 THEN 'Matters' ELSE 'Closed' END + '] MAT
           INNER JOIN [dbo].[contacts] CON
                   ON CON.[code] = MAT.[ClientCode]
     WHERE MAT.[code] LIKE @matter' + CASE WHEN @hasclosed = 1 THEN '
       AND IsNull(MAT.[Closed], '''') = ''Y''' ELSE '' END + '
  END
  
RETURN

END'

EXEC (@command)

GO       

/**************************************************************************************
 *
 * Final scripts
 *
 **************************************************************************************/

/**************************************************************************************
 *
 * Correct the CHARGE column in the TimeDayBook
 *
 **************************************************************************************/
/*
UPDATE TDB
   SET TDB.[RATE] = 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,
       TDB.[Charge] = Convert(numeric(7, 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))
  from [dbo].[TimeDayBook] TDB
       LEFT OUTER JOIN [dbo].[matters] MAT
                       INNER JOIN [dbo].[contacts] CON
                               ON CON.[Code] = MAT.[ClientCode]
                    ON MAT.[code] = TDB.[MATTER]
       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] = TDB.[MATTER]) 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.[TimeOrCharge] = 'T'
*/