SET NOCOUNT ON
GO

IF [dbo].[ISSAM4]() = 1
BEGIN
    SET NOEXEC ON
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_AutoAllocateTransactions] (
       @XML NVARCHAR(MAX))
AS
/*************************************************************************************************************
 *                                                                                                           *
 * KAAS_AutoAllocateTransactions                                                                             *
 * This is used when updating/posting a receipt which 'pre-allocated' against an invoice                     *
 * When used to handle payments and supplier bills the payment is the 'receipt' and the supplier bill is     *
 * the 'invoice'                                                                                             *
 * @XML:                                                                                                     *
 * <Allocations User="ADM">                                                                                  *
 *   <Allocation ReceiptBatchNo="12"                                                                         *
 *               ReceiptPostRef="34"                                                                         *
 *               InvoiceBatchNo="56"                                                                         *
 *               InvoicePostRef="78"                                                                         *
 *               AllocateValue="123.45"                                                                      *
 *               WriteOffRemainder="1"/>                                                                     *
 * </Allocations>                                                                                            *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * Original:                                -                                                        *   *
 *   * First compatible version:                5.9.2.76                                                 *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History:                                                                                     *
 * 2022-05-09   John Ginnane      Created                                                                    *
 * 2022-07-14   John Ginnane      Added support to pay for supplier bills                                    *
 * 2024-02-13   John Ginnane      17968 - Fixed allocation going the wrong way                               *
 *                                                                                                           *
 *************************************************************************************************************/
BEGIN
    SET NOCOUNT ON

    DECLARE @USER VARCHAR(8)
    DECLARE @iSL INT

    BEGIN TRY
    EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
    END TRY
    BEGIN CATCH
    EXEC sp_xml_preparedocument @iSL OUTPUT, N'<data />'
    END CATCH

    SELECT @USER = [XML].[User]
      FROM OPENXML (@iSL, N'Allocations')
              WITH ([User] VARCHAR(20) '@User') AS [XML]

    -- Expand this later to include breakdown of fees/VAT/outlay
    DECLARE @ALLOCATIONS TABLE (
            [id]                INT             PRIMARY KEY,
            [Type]              VARCHAR(1)      NULL,
            [ReceiptBatchNo]    INT             NOT NULL,
            [ReceiptPostRef]    INT             NOT NULL,
            [InvoiceBatchNo]    INT             NOT NULL,
            [InvoicePostRef]    INT             NOT NULL,
            [AllocateValue]     DECIMAL(19, 2)  NOT NULL,
            [WriteOffRemainder] BIT             NOT NULL,
        
            [FoundTransaction]  BIT             NOT NULL DEFAULT(0),
            [AllocDate]         DATETIME        NULL,
            [AllNo]             INT             NULL,
            [ReceiptRef]        VARCHAR(10)     NULL,
            [InvoiceRef]        VARCHAR(10)     NULL,
            [InvoiceVATCode]    VARCHAR(1)      NULL)

    INSERT INTO @ALLOCATIONS (
            [id],
            [ReceiptBatchNo],      [ReceiptPostRef],
            [InvoiceBatchNo],      [InvoicePostRef],
            [AllocateValue],       [WriteOffRemainder])
    SELECT ROW_NUMBER() OVER(ORDER BY [XML].[ReceiptBatchNo]),
           [XML].[ReceiptBatchNo], [XML].[ReceiptPostRef],
           [XML].[InvoiceBatchNo], [XML].[InvoicePostRef],
           [XML].[AllocateValue],  CASE WHEN ISNULL([XML].[WriteOffRemainder], '') IN ('Y', '1') THEN 1 ELSE 0 END
      FROM OPENXML (@iSL, N'Allocations/Allocation')
              WITH ([ReceiptBatchNo]    INT            '@ReceiptBatchNo',
                    [ReceiptPostRef]    INT            '@ReceiptPostRef',
                    [InvoiceBatchNo]    INT            '@InvoiceBatchNo',
                    [InvoicePostRef]    INT            '@InvoicePostRef',
                    [AllocateValue]     DECIMAL(19, 2) '@AllocateValue',
                    [WriteOffRemainder] VARCHAR(1)     '@WriteOffRemainder') AS [XML]

    DECLARE @TODAY          DATETIME
    DECLARE @BASECURRENCY   VARCHAR(10)
    DECLARE @IECONVERT      DECIMAL(19, 6)
    DECLARE @LASTALLOC      INT
    
    DECLARE @DEBTORS        VARCHAR(10)
    DECLARE @CREDITORS      VARCHAR(10)
    DECLARE @OUTLAYWRITEOFF VARCHAR(10)
    DECLARE @FEESWRITEOFF   VARCHAR(10)
    DECLARE @BILLSWRITEOFF  VARCHAR(10)
    DECLARE @VATEXCLUDE     VARCHAR(1)
    DECLARE @CONVERT        DECIMAL(19, 6)
    DECLARE @YEAR           INT
    DECLARE @PERNO          INT

    SELECT @TODAY          = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
           @LASTALLOC      = CASE WHEN ISNULL([CON].[LASTALLOC], 0) > ISNULL([ALO].[LastAllocNo], 0)
                                       THEN ISNULL([CON].[LASTALLOC], 0)
                                  ELSE ISNULL([ALO].[LastAllocNo], 0) END,
           @BASECURRENCY   = [CON].[BASECURRENCY],
           @IECONVERT      = [CON].[IECONVERT],
           @DEBTORS        = [CON].[DEBTORS],
           @CREDITORS      = [CON].[CREDITOR],
           @VATEXCLUDE     = [CON].[VATEXCLUDE],
           @CONVERT        = [CON].[IECONVERT],
           @YEAR           = [CON].[YEAR],
           @PERNO          = [CON].[CURPER],
           @OUTLAYWRITEOFF = [CON].[OUTLAYWRITEOFF],
           @FEESWRITEOFF   = [CON].[FEESWRITEOFF],
           @BILLSWRITEOFF  = [CON].[BILLSWRITEOFF]
      FROM [dbo].[control] AS [CON]
           OUTER APPLY (SELECT MAX([ALO].[AllNo]) AS [LastAllocNo]
                          FROM [dbo].[Allocations] AS [ALO]) AS [ALO]
    
    IF ISNULL(@BASECURRENCY, '') NOT IN ('I', 'E')
    BEGIN
        SET @BASECURRENCY = 'E'
    END

    -- If the pre-allocations target debt invoices
    UPDATE [TMP]
       SET [TMP].[ReceiptRef]       = [Receipt_BAD].[REF],
           [TMP].[InvoiceRef]       = [Invoice_DTL].[REF],
           [TMP].[InvoiceVATCode]   = [Invoice_DTL].[VATCODE],
           [TMP].[FoundTransaction] = 1,
           -- Make sure we don't over-allocate
           [TMP].[AllocateValue] = CASE WHEN [TMP].[AllocateValue] > [Invoice_DTL].[OSVALUE]
                                             THEN [Invoice_DTL].[OSVALUE]
                                        ELSE [TMP].[AllocateValue] END,
           [TMP].[Type] = 'D',
           [TMP].[AllocDate] = @TODAY
      FROM @ALLOCATIONS AS [TMP]
           -- Use inner join to make absolutely sure both sides of the allocation exist
           INNER JOIN [dbo].[BatchDetails] AS [Receipt_BAD]
                   ON [TMP].[ReceiptBatchNo] = [Receipt_BAD].[BATCHNO]
                  AND [TMP].[ReceiptPostRef] = [Receipt_BAD].[PREF]
           INNER JOIN [dbo].[DebtorsLedger] AS [Invoice_DTL]
                   ON [TMP].[InvoiceBatchNo] = [Invoice_DTL].[BATCHNO]
                  AND [TMP].[InvoicePostRef] = [Invoice_DTL].[PREF]
    
    -- or the pre-allocations target supplier invoices
    UPDATE [TMP]
       SET [TMP].[ReceiptRef] = [Payment_BAD].[REF],
           [TMP].[InvoiceRef] = [Bill_SPL].[REF],
           [TMP].[InvoiceVATCode] = '',
           [TMP].[FoundTransaction] = 1,
           [TMP].[AllocateValue] = CASE WHEN [TMP].[AllocateValue] > [Bill_SPL].[OSVALUE] * -1
                                             THEN [Bill_SPL].[OSVALUE] * -1
                                        ELSE [TMP].[AllocateValue] END,
           [TMP].[Type] = 'S',
           [TMP].[AllocDate] = [Payment_BAH].[DATE]
      FROM @ALLOCATIONS AS [TMP]
           INNER JOIN [dbo].[BatchDetails] AS [Payment_BAD]
                   ON [TMP].[ReceiptBatchNo] = [Payment_BAD].[BATCHNO]
                  AND [TMP].[ReceiptPostRef] = [Payment_BAD].[PREF]
           INNER JOIN [dbo].[BatchH] AS [Payment_BAH]
                   ON [TMP].[ReceiptBatchNo] = [Payment_BAH].[BATCHNO]
           INNER JOIN [dbo].[SupplierLedger] AS [Bill_SPL]
                   ON [TMP].[InvoiceBatchNo] = [Bill_SPL].[BATCHNO]
                  AND [TMP].[InvoicePostRef] = [Bill_SPL].[PREF]

    -- Delete allocations which we are not processing
    DELETE [TMP]
      FROM @ALLOCATIONS AS [TMP]
     WHERE [TMP].[FoundTransaction] = 0

    -- "Reseed" our ID column
    ;WITH [OrderedItems] ([id], [newid], [AllNo]) AS (
    SELECT [id],
           ROW_NUMBER() OVER (ORDER BY [TMP].[id] ASC),
           @LASTALLOC + ROW_NUMBER() OVER (ORDER BY [TMP].[id] ASC)
      FROM @ALLOCATIONS AS [TMP])
    UPDATE [TMP]
       SET [TMP].[id] = [OI].[newid],
           [TMP].[AllNo] = [OI].[AllNo]
      FROM @ALLOCATIONS AS [TMP]
           INNER JOIN [OrderedItems] AS [OI]
                   ON [TMP].[id] = [OI].[id]

    UPDATE [CON]
       SET [CON].[LASTALLOC] = [TMP].[LastAllNo]
      FROM [dbo].[control] AS [CON]
           OUTER APPLY (SELECT TOP 1 MAX([AllNo]) AS [LastAllNo] FROM @ALLOCATIONS) AS [TMP]
    
    -- Enter receipt side of the allocation
    INSERT INTO [dbo].[Allocations] (
           [BATCHNO],
           [PREF],
           [DATE],
           [ABATCHNO],
           [OPREF],
           [OREF],
           [VALUE],
           [FEES],
           [OUTLAY],
           [VAT],
           [USERCODE],
           [AllNo],
           [VATCODE])
    SELECT [TMP].[ReceiptBatchNo],
           [TMP].[ReceiptPostRef],
           [TMP].[AllocDate],
           [TMP].[InvoiceBatchNo],
           [TMP].[InvoicePostRef],
           [TMP].[InvoiceRef],
           [TMP].[AllocateValue] * CASE WHEN [TMP].[Type] IN ('D') THEN -1 ELSE 1 END,
           0,
           0,
           0,
           @USER,
           [TMP].[AllNo],
           [TMP].[InvoiceVATCode]
      FROM @ALLOCATIONS AS [TMP]

    -- Enter the invoice side of the allocation
    INSERT INTO [dbo].[Allocations] (
           [BATCHNO],
           [PREF],
           [DATE],
           [ABATCHNO],
           [OPREF],
           [OREF],
           [VALUE],
           [FEES],
           [OUTLAY],
           [VAT],
           [USERCODE],
           [AllNo],
           [VATCODE])
    SELECT [TMP].[InvoiceBatchNo],
           [TMP].[InvoicePostRef],
           [TMP].[AllocDate],
           [TMP].[ReceiptBatchNo],
           [TMP].[ReceiptPostRef],
           [TMP].[ReceiptRef],
           [TMP].[AllocateValue] * CASE WHEN [TMP].[Type] IN ('D') THEN -1 ELSE 1 END,
           0,
           0,
           0,
           @USER,
           [TMP].[AllNo],
           ''
      FROM @ALLOCATIONS AS [TMP]

    -- "! Now Process Allocations for this Receipt"
    
    -- Iterate over each allocation and calculate the breakdown
    DECLARE @MAX               INT
    DECLARE @I                 INT
    DECLARE @WRITEOFFREMAINDER BIT
    DECLARE @WO_BATCHNO        INT
    DECLARE @WO_PREF           INT

    SELECT @I = 1,
           @MAX = MAX([TMP].[id])
      FROM @ALLOCATIONS AS [TMP]

    WHILE @I <= @MAX
    BEGIN
        SET @WRITEOFFREMAINDER = 0

        -- If the allocation is targetting the debtors ledger
        IF ISNULL((SELECT TOP 1 [Type] FROM @ALLOCATIONS WHERE [id] = @I), '') = 'D'
        BEGIN
            DECLARE @INV_DTL_RECORDID INT

            -- Update the receipt's DTL record
            UPDATE [DTL]
               SET [DTL].[OSVALUE] = [DTL].[OSVALUE] - [ALO].[VALUE]
              FROM [dbo].[DebtorsLedger] AS [DTL]
                   INNER JOIN [dbo].[Allocations] AS [ALO]
                           ON [DTL].[BATCHNO] = [ALO].[BATCHNO]
                          AND [DTL].[PREF] = [ALO].[PREF]
                   INNER JOIN @ALLOCATIONS AS [TMP]
                           ON [TMP].[AllNo] = [ALO].[AllNo]
             WHERE [TMP].[id] = @I
               AND [DTL].[TYPE] IN ('R', 'J')

            SELECT TOP 1
                   @INV_DTL_RECORDID  = [DTL].[RECORDID],
                   @WRITEOFFREMAINDER = ISNULL([TMP].[WriteOffRemainder], 0)
              FROM [dbo].[DebtorsLedger] AS [DTL]
                   INNER JOIN [dbo].[Allocations] AS [ALO]
                           ON [DTL].[BATCHNO] = [ALO].[ABATCHNO]
                          AND [DTL].[PREF] = [ALO].[OPREF]
                   INNER JOIN @ALLOCATIONS AS [TMP]
                           ON [TMP].[AllNo] = [ALO].[AllNo]
             WHERE [TMP].[id] = @I

            -- Update the invoice's DTL record
            -- If the other record IS an invoice then also do the breakdown
            -- otherwise just update the DTL:OSVALUE
            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[DebtorsLedger] AS [DTL]
                        WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID
                          AND [DTL].[TYPE] = 'I')
            BEGIN
                DECLARE @ALO_VALUE    DECIMAL(19, 2)
                DECLARE @DTL_OSVALUE  DECIMAL(19, 2)
                DECLARE @DTL_OSFEES   DECIMAL(19, 2)
                DECLARE @DTL_OSOUTLAY DECIMAL(19, 2)
                DECLARE @DTL_OSVAT    DECIMAL(19, 2)

                -- Allocate against pre-billed outlay LAST
                DECLARE @INV_PREBILLEDOUTLAY DECIMAL(19, 2)
                DECLARE @INV_OSPREBILLED     DECIMAL(19, 2)
        
                DECLARE @ALO_FEES     DECIMAL(19, 2)
                DECLARE @ALO_OUTLAY   DECIMAL(19, 2)
                DECLARE @ALO_VAT      DECIMAL(19, 2)

                SELECT TOP 1
                       @ALO_VALUE             = ISNULL([ALO].[VALUE], 0),
                       @DTL_OSVALUE           = ISNULL([DTL].[OSVALUE], 0) + ISNULL([ALO].[VALUE], 0),
                       @DTL_OSFEES            = ISNULL([DTL].[OSFEES], 0),
                       @DTL_OSOUTLAY          = ISNULL([DTL].[OSOUTLAY], 0),
                       @DTL_OSVAT             = ISNULL([DTL].[OSVAT], 0),
                       @INV_PREBILLEDOUTLAY   = ISNULL([BAD].[PreBilledOutlay], 0),
                       @INV_OSPREBILLED       = 0,

                       @ALO_FEES     = 0,
                       @ALO_OUTLAY   = 0,
                       @ALO_VAT      = 0
                  FROM [dbo].[DebtorsLedger] AS [DTL]
                       OUTER APPLY (SELECT TOP 1 SUM([BAD].[VALUE]) AS [PreBilledOutlay]
                                      FROM [dbo].[BatchDetails] AS [BAD]
                                     WHERE [BAD].[BATCHNO] = [DTL].[BATCHNO]
                                       AND [BAD].[OUTLAY] = 'O'
                                       AND [BAD].[PreBilledOutlay] = 1) AS [BAD]
                       INNER JOIN [dbo].[Allocations] AS [ALO]
                               ON [DTL].[BATCHNO] = [ALO].[ABATCHNO]
                              AND [DTL].[PREF] = [ALO].[OPREF]
                       INNER JOIN @ALLOCATIONS AS [TMP]
                               ON [TMP].[AllNo] = [ALO].[AllNo]
                 WHERE [TMP].[id] = @I

                IF @DTL_OSVALUE = 0
                BEGIN
                    SELECT @ALO_FEES     = @DTL_OSFEES   * -1,
                           @ALO_OUTLAY   = @DTL_OSOUTLAY * -1,
                           @ALO_VAT      = @DTL_OSVAT    * -1,
                           @DTL_OSFEES   = 0,
                           @DTL_OSOUTLAY = 0,
                           @DTL_OSVAT    = 0
                END
                ELSE
                BEGIN
                    DECLARE @USERTOT DECIMAL(19, 2)
                    SET @USERTOT = @ALO_VALUE * -1

                    -- If the invoice contains pre-billed outlays then pay them off at the very end
                    -- We subtract how much outlay we can allocate now
                    -- and check it later on
                    IF @DTL_OSOUTLAY > 0 AND @INV_PREBILLEDOUTLAY > 0
                    BEGIN
                        SET @INV_OSPREBILLED = @DTL_OSOUTLAY
                        SET @DTL_OSOUTLAY = @DTL_OSOUTLAY - @INV_PREBILLEDOUTLAY
                    
                        IF @DTL_OSOUTLAY < 0
                        BEGIN
                            SET @DTL_OSOUTLAY = 0
                        END

                        SET @INV_OSPREBILLED = @INV_OSPREBILLED - @DTL_OSOUTLAY
                    END
                
                    IF @USERTOT > 0
                    BEGIN
                        -- How much outlay we can allocate now
                        DECLARE @ALLOCATE_OUTLAY DECIMAL(19, 2)
                        SET @ALLOCATE_OUTLAY = @DTL_OSOUTLAY

                        IF @ALLOCATE_OUTLAY > @USERTOT
                        BEGIN
                            SET @ALLOCATE_OUTLAY = @USERTOT
                        END

                        SET @ALO_OUTLAY = @ALLOCATE_OUTLAY * -1
                        SET @USERTOT = @USERTOT + @ALO_OUTLAY
                        SET @DTL_OSOUTLAY = @DTL_OSOUTLAY + @ALO_OUTLAY
                    END

                    -- Add the OS Pre-billed outlay
                    SET @DTL_OSOUTLAY = @DTL_OSOUTLAY + @INV_OSPREBILLED
                
                    IF @USERTOT > 0
                    BEGIN
                        DECLARE @DTL_OSFEES_ORIGINAL DECIMAL(19, 2)
                        DECLARE @DTL_OSVAT_ORIGINAL  DECIMAL(19, 2)

                        SET @DTL_OSFEES_ORIGINAL = @DTL_OSFEES
                        SET @DTL_OSVAT_ORIGINAL  = @DTL_OSVAT
                    
                        -- Possible division by 0
                        BEGIN TRY
                            DECLARE @FEESANDVAT DECIMAL(19, 2)
                            SET @FEESANDVAT = @DTL_OSFEES + @DTL_OSVAT
                            IF @FEESANDVAT > @USERTOT
                            BEGIN
                                SET @FEESANDVAT = @USERTOT
                            END

                            SET @ALO_FEES     = (@FEESANDVAT * (@DTL_OSFEES / (@DTL_OSFEES + @DTL_OSVAT))) * -1
                            SET @ALO_VAT      = (@FEESANDVAT * (@DTL_OSVAT  / (@DTL_OSFEES + @DTL_OSVAT))) * -1
                            SET @DTL_OSFEES   = @DTL_OSFEES + @ALO_FEES
                            SET @DTL_OSVAT    = @DTL_OSVAT  + @ALO_VAT
                            SET @USERTOT      = @USERTOT + @ALO_FEES + @ALO_VAT
                        END TRY
                        BEGIN CATCH
                            SET @ALO_FEES   = 0
                            SET @ALO_VAT    = 0
                            SET @DTL_OSFEES = @DTL_OSFEES_ORIGINAL
                            SET @DTL_OSVAT  = @DTL_OSVAT_ORIGINAL
                        END CATCH
                    END
                    
                    IF @USERTOT > 0 AND @DTL_OSOUTLAY > 0
                    BEGIN
                        -- Allocate the remaining money against the pre-billed outlay
                        -- In most cases this won't happen as we expect people to 
                        -- be only paying for regular outlay, fees and VAT
                        SET @ALO_OUTLAY = @ALO_OUTLAY - @USERTOT
                        SET @DTL_OSOUTLAY = @DTL_OSOUTLAY - @USERTOT
                    END
                END
                
                UPDATE [DTL]
                   SET [DTL].[OSVALUE]  = @DTL_OSVALUE,
                       [DTL].[OSFEES]   = @DTL_OSFEES,
                       [DTL].[OSOUTLAY] = @DTL_OSOUTLAY,
                       [DTL].[OSVAT]    = @DTL_OSVAT
                  FROM [dbo].[DebtorsLedger] AS [DTL]
                 WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID

                UPDATE [ALO]
                   SET [ALO].[FEES]   = @ALO_FEES,
                       [ALO].[OUTLAY] = @ALO_OUTLAY,
                       [ALO].[VAT]    = @ALO_VAT
                  FROM [dbo].[Allocations] AS [ALO]
                       INNER JOIN @ALLOCATIONS AS [TMP]
                               ON [ALO].[AllNo] = [TMP].[AllNo]
                 WHERE [TMP].[id] = @I
            END
            ELSE
            BEGIN
                UPDATE [DTL]
                   SET [DTL].[OSVALUE] = [DTL].[OSVALUE] + [ALO].[VALUE]
                  FROM [dbo].[DebtorsLedger] AS [DTL]
                       INNER JOIN [dbo].[Allocations] AS [ALO]
                               ON [DTL].[BATCHNO] = [ALO].[ABATCHNO]
                              AND [DTL].[PREF] = [ALO].[OPREF]
                       INNER JOIN @ALLOCATIONS AS [TMP]
                               ON [TMP].[id] = [ALO].[AllNo]
                 WHERE [TMP].[id] = @I
            END

            -- Check if we need to create a write-off journal
            -- We will create one journal for each write-off
            IF @WRITEOFFREMAINDER = 1 AND 
               EXISTS (SELECT TOP 1 1
                         FROM [dbo].[DebtorsLedger] AS [DTL]
                        WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID
                          AND [DTL].[OSVALUE] <> 0)
            BEGIN
                EXEC @WO_BATCHNO = [dbo].[ky_NETGetBatchNo]
                EXEC @WO_PREF = [dbo].[ky_NETGetPostRef]

                INSERT INTO [dbo].[BatchH] (
                       [BATCHNO],
                       [POSTFWD],
                       [TYPE],
                       [CODE],
                       [BRANCH],
                       [PREF],
                       [REF],
                       [DATE],
                       [FEE],
                       [MATTER],
                       [SUPP],
                       [NARR],
                       [VALUE],
                       [SUBTOT],
                       [POSTED],
                       [CLIENTAC],
                       [PERNO],
                       [YEAR],
                       [PAYEE],
                       [OUTLAYTOT],
                       [VATTOT],
                       [FEETOT],
                       [INVCR],
                       [THIRDPARTY],
                       [USERCODE],
                       [ENTRYDATE],
                       [CLIENTBANK],
                       [CURRENCY],
                       [CURRENCYVALUE],
                       [CUROUTLAYTOT],
                       [CURVATTOT],
                       [CURFEETOT],
                       [RECNO],
                       [SINGLELINE],
                       [TEMPLATE],
                       [CHEQUEREQNO],
                       [WRITEDOWN],
                       [WRITEBACKHOURS],
                       [WRITEBACKVALUE],
                       [CORRECTCOPY],
                       [CreditInvoiceNo],
                       [DraftBillNo],
                       [EFTSent],
                       [EFTDate],
                       [EFTFileNumber],
                       [EFTFileName],
                       [EFTYorN],
                       [ClientCode],
                       [PayClient],
                       [OnceOffPayment],
                       [CaseAssCode],
                       [EFTEmailYorN],
                       [HandlerCode],
                       [PaymentMethod],
                       [ClearedDate])
                SELECT @WO_BATCHNO      AS [BATCHNO],
                       [BAH].[POSTFWD]  AS [POSTFWD],
                       'J'              AS [TYPE],
                       ''               AS [CODE],
                       ''               AS [BRANCH],
                       @WO_PREF         AS [PREF],
                       ''               AS [REF],
                       [BAD].[DATE]     AS [DATE],
                       ''               AS [FEE],
                       ''               AS [MATTER],
                       ''               AS [SUPP],
                       'Automatic Debtors balance write-off' AS [NARR],
                       0                AS [VALUE],
                       0                AS [SUBTOT],
                       'N'              AS [POSTED],
                       ''               AS [CLIENTAC],
                       @PERNO           AS [PERNO],
                       @YEAR            AS [YEAR],
                       ''               AS [PAYEE],
                       0                AS [OUTLAYTOT],
                       0                AS [VATTOT],
                       0                AS [FEETOT],
                       ''               AS [INVCR],
                       ''               AS [THIRDPARTY],
                       ''               AS [USERCODE],
                       @TODAY           AS [ENTRYDATE],
                       ''               AS [CLIENTBANK],
                       ''               AS [CURRENCY],
                       0                AS [CURRENCYVALUE],
                       0                AS [CUROUTLAYTOT],
                       0                AS [CURVATTOT],
                       0                AS [CURFEETOT],
                       0                AS [RECNO],
                       ''               AS [SINGLELINE],
                       ''               AS [TEMPLATE],
                       0                AS [CHEQUEREQNO],
                       NULL             AS [WRITEDOWN],
                       0                AS [WRITEBACKHOURS],
                       0                AS [WRITEBACKVALUE],
                       ''               AS [CORRECTCOPY],
                       0                AS [CreditInvoiceNo],
                       0                AS [DraftBillno],
                       'N'              AS [EFTSent],
                       NULL             AS [EFTDate],
                       0                AS [EFTFileNumber],
                       ''               AS [EFTFileName],
                       'N'              AS [EFTYorN],
                       ''               AS [ClientCode],
                       'N'              AS [PayClient],
                       'N'              AS [OnceOffPayment],
                       ''               AS [CaseAssCode],
                       'N'              AS [EFTEmailYorN],
                       ''               AS [HandlerCode],
                       0                AS [PaymentMethod],
                       NULL             AS [ClearedDate]
                  FROM @ALLOCATIONS AS [TMP]
                       INNER JOIN [dbo].[BatchH] AS [BAH]
                               ON [BAH].[BATCHNO] = [TMP].[ReceiptBatchNo]
                       INNER JOIN [dbo].[BatchDetails] AS [BAD]
                               ON [BAD].[BATCHNO] = [BAH].[BATCHNO]
                              AND [BAD].[PREF] = [TMP].[ReceiptPostRef]
                 WHERE [TMP].[id] = @I

                -- Use a table variable to store the most important details
                -- then insert the contents into the actual table
                DECLARE @WO_INV_BATCHDETAILS TABLE (
                        [ROW]        INT            IDENTITY(1, 1) PRIMARY KEY,
                        [REF]        VARCHAR(10),
                        [CODE]       VARCHAR(10),
                        [NARR]       VARCHAR(100),
                        [MATTER]     VARCHAR(20)    DEFAULT(''),
                        [VALUE]      DECIMAL(19, 2),
                        [VATCODE]    VARCHAR(10),
                        [VATVAL]     DECIMAL(19, 2) DEFAULT(0),
                        [OUTLAY]     VARCHAR(1),
                        [OUTLAYCODE] VARCHAR(1)     DEFAULT(''),
                        [ALLOCBATCH] INT            DEFAULT(0),
                        [ALLOCPREF]  INT            DEFAULT(0),
                        [ALLOCREF]   VARCHAR(10)    DEFAULT(''),
                        [ALLOCVALUE] DECIMAL(19, 2) DEFAULT(0))

                -- Insert each matter's write-off record
                -- This writes off the debt from them matter ledger
                INSERT INTO @WO_INV_BATCHDETAILS (
                       [REF],
                       [CODE],
                       [NARR],
                       [MATTER],
                       [VALUE],
                       [VATCODE],
                       [OUTLAY],
                       [ALLOCBATCH],
                       [ALLOCPREF],
                       [ALLOCREF],
                       [ALLOCVALUE])
                SELECT 'W/o(auto)'           AS [REF],
                       @DEBTORS              AS [CODE],
                       'Automatic Write-off' AS [NARR],
                       [BAD].[MATTER]        AS [MATTER],
                       [DTL].[OSVALUE] * -1  AS [VALUE],
                       @VATEXCLUDE           AS [VATCODE],
                       'D'                   AS [OUTLAY],
                       [DTL].[BATCHNO]       AS [ALLOCBATCH],
                       [DTL].[PREF]          AS [ALLOCPREF],
                       [DTL].[REF]           AS [ALLOCREF],
                       [DTL].[OSVALUE]       AS [ALLOCVALUE]
                  FROM @ALLOCATIONS AS [TMP]
                       INNER JOIN [dbo].[DebtorsLedger] AS [DTL]
                               ON [DTL].[BATCHNO] = [TMP].[InvoiceBatchNo]
                              AND [DTL].[PREF] = [TMP].[InvoicePostRef]
                       INNER JOIN [dbo].[BatchDetails] AS [BAD]
                               ON [BAD].[BATCHNO] = [TMP].[ReceiptBatchNo]
                              AND [BAD].[PREF] = [TMP].[ReceiptPostRef]
                 WHERE [TMP].[id] = @I

                -- Write off the outlay
                IF EXISTS (SELECT TOP 1 1
                             FROM [dbo].[DebtorsLedger] AS [DTL]
                            WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID
                              AND [DTL].[OSOUTLAY] <> 0)
                BEGIN
                    INSERT INTO @WO_INV_BATCHDETAILS (
                           [REF],
                           [CODE],
                           [NARR],
                           [VALUE],
                           [VATCODE],
                           [OUTLAY])
                    SELECT 'W/o(auto)'                  AS [REF],
                           @OUTLAYWRITEOFF              AS [CODE],
                           'Automatic Outlay Write-off' AS [NARR],
                           [DTL].[OSOUTLAY]             AS [VALUE],
                           @VATEXCLUDE                  AS [VATCODE],
                           'N'                          AS [OUTLAY]
                      FROM [dbo].[DebtorsLedger] AS [DTL]
                     WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID
                END

                -- Write off the fees
                IF EXISTS (SELECT TOP 1 1
                             FROM [dbo].[DebtorsLedger] AS [DTL]
                            WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID
                              AND [DTL].[OSFEES] <> 0)
                BEGIN
                    INSERT INTO @WO_INV_BATCHDETAILS (
                           [REF],
                           [CODE],
                           [NARR],
                           [VALUE],
                           [VATCODE],
                           [VATVAL],
                           [OUTLAY],
                           [OUTLAYCODE])
                    SELECT 'W/o(auto)'                AS [REF],
                           @FEESWRITEOFF              AS [CODE],
                           'Automatic Fees Write-off' AS [NARR],
                           [DTL].[OSFEES]             AS [VALUE],
                           [DTL].[VATCODE]            AS [VATCODE],
                           [DTL].[OSVAT]              AS [VATVAL],
                           'N'                        AS [OUTLAY],
                           'I'                        AS [OUTLAYCODE]
                      FROM [dbo].[DebtorsLedger] AS [DTL]
                     WHERE [DTL].[RECORDID] = @INV_DTL_RECORDID
                END

                -- Insert the detail lines now
                INSERT INTO [dbo].[BatchDetails] (
                       [BATCHNO],
                       [TYPE],
                       [CODE],
                       [PREF],
                       [REF],
                       [DATE],
                       [FEE],
                       [BRANCH],
                       [NARR],
                       [MATTER],
                       [SUPP],
                       [VALUE],
                       [VATCODE],
                       [VATVAL],
                       [CLIENTYN],
                       [OUTLAY],
                       [PENDING],
                       [YEAR],
                       [PERNO],
                       [ENTRYCURRENCY],
                       [CURRENCYVALUE],
                       [CURRENCYVAT],
                       [OUTLAYCODE],
                       [THIRDPARTY],
                       [PAYEE],
                       [HEADPREF],
                       [HEADBATCH],
                       [ALLOCBATCH],
                       [ALLOCPREF],
                       [ALLOCREF],
                       [ALLOCVALUE],
                       [ALLOCWRITEOFF],
                       [PSUPP],
                       [UNDETAKING],
                       [CaseAssCode],
                       [OnceOffPayment],
                       [PayClient],
                       [ClientCode],
                       [EFTEmailYorN],
                       [RegisteredPost],
                       [PreBilledOutlay])
                SELECT @WO_BATCHNO               AS [BATCHNO],
                       'J'                       AS [TYPE],
                       [TMP].[CODE]              AS [CODE],
                       @WO_PREF    + [TMP].[ROW] AS [PREF],
                       [TMP].[REF]               AS [REF],
                       @TODAY                    AS [DATE],
                       ''                        AS [FEE],
                       ''                        AS [BRANCH],
                       [TMP].[NARR]              AS [NARR],
                       [TMP].[MATTER]            AS [MATTER],
                       ''                        AS [SUPP],
                       [TMP].[VALUE]             AS [VALUE],
                       [TMP].[VATCODE]           AS [VATCODE],
                       [TMP].[VATVAL]            AS [VATVAL],
                       ''                        AS [CLIENTYN],
                       [TMP].[OUTLAY]            AS [OUTLAY],
                       ''                        AS [PENDING],
                       @YEAR                     AS [YEAR],
                       @PERNO                    AS [PERNO],
                       @BASECURRENCY             AS [ENTRYCURRENCY],
                       0                         AS [CURRENCYVALUE],
                       0                         AS [CURRENCYVAT],
                       [TMP].[OUTLAYCODE]        AS [OUTLAYCODE],
                       ''                        AS [THIRDPARTY],
                       ''                        AS [PAYEE],
                       0                         AS [HEADPREF],
                       0                         AS [HEADBATCH],
                       [TMP].[ALLOCBATCH]        AS [ALLOCBATCH],
                       [TMP].[ALLOCPREF]         AS [ALLOCPREF],
                       [TMP].[ALLOCREF]          AS [ALLOCREF],
                       [TMP].[ALLOCVALUE]        AS [ALLOCVALUE],
                       ''                        AS [ALLOCWRITEOFF],
                       ''                        AS [PSUPP],
                       ''                        AS [UNDETAKING],
                       ''                        AS [CaseAssCode],
                       'N'                       AS [OnceOffPayment],
                       'Y'                       AS [PayClient],
                       ''                        AS [ClientCode],
                       'N'                       AS [EFTEmailYorN],
                       0                         AS [RegisteredPost],
                       0                         AS [PreBilledOutlay]
                  FROM @WO_INV_BATCHDETAILS AS [TMP]
            END
        END
        
        -- If the allocation is targetting the suppliers ledger
        IF ISNULL((SELECT TOP 1 [Type] FROM @ALLOCATIONS WHERE [id] = @I), '') = 'S'
        BEGIN
            DECLARE @BIL_SPL_RECORDID INT

            -- "! Now Process Allocations for this Payment"
            UPDATE [SPL]
               SET [SPL].[OSVALUE] = ISNULL([SPL].[OSVALUE], 0) - ISNULL([TMP].[AllocateValue], 0)
              FROM [dbo].[SupplierLedger] AS [SPL]
                   INNER JOIN @ALLOCATIONS AS [TMP]
                           ON [TMP].[ReceiptBatchNo] = [SPL].[BATCHNO]
                          AND [TMP].[ReceiptPostRef] = [SPL].[PREF]
             WHERE [TMP].[id] = @I
            
            UPDATE [SPL]
               SET [SPL].[OSVALUE] = ISNULL([SPL].[OSVALUE], 0) + ISNULL([TMP].[AllocateValue], 0)
              FROM [dbo].[SupplierLedger] AS [SPL]
                   INNER JOIN @ALLOCATIONS AS [TMP]
                           ON [TMP].[InvoiceBatchNo] = [SPL].[BATCHNO]
                          AND [TMP].[InvoicePostRef] = [SPL].[PREF]
             WHERE [TMP].[id] = @I
             
            SELECT TOP 1
                   @BIL_SPL_RECORDID  = [SPL].[RECORDID],
                   @WRITEOFFREMAINDER = ISNULL([TMP].[WriteOffRemainder], 0)
              FROM [dbo].[SupplierLedger] AS [SPL]
                   INNER JOIN @ALLOCATIONS AS [TMP]
                           ON [TMP].[InvoiceBatchNo] = [SPL].[BATCHNO]
                          AND [TMP].[InvoicePostRef] = [SPL].[PREF]
             WHERE [TMP].[id] = @I

            -- If there was pending outlay
            INSERT INTO [dbo].[PendingOutlay] (
                   [MATTER],
                   [DATE],
                   [SUPPLIER],
                   [REF],
                   [NARRATIVE],
                   [VALUE])
            SELECT LTRIM(RTRIM([BILL_BAD].[MATTER])),
                   [PAY_BAH].[DATE],
                   LTRIM(RTRIM([SPL].[SUPP])),
                   LTRIM(RTRIM([BILL_BAD].[REF])),
                   CASE WHEN [PAY_BAH].[TYPE] = 'J'
                             THEN 'Auto Supplier Journal Debit'
                        ELSE 'Supplier Bill Paid' END,
                   [BILL_BAD].[VALUE] * -1
              FROM @ALLOCATIONS AS [TMP]
                   INNER JOIN [dbo].[SupplierLedger] AS [SPL]
                           ON [TMP].[InvoiceBatchNo] = [SPL].[BATCHNO]
                          AND [TMP].[InvoicePostRef] = [SPL].[PREF]
                   INNER JOIN [dbo].[BatchDetails] AS [BILL_BAD]
                           ON [BILL_BAD].[BATCHNO] = [TMP].[InvoiceBatchNo]
                          AND [BILL_BAD].[PREF] = [TMP].[InvoicePostRef]
                   INNER JOIN [dbo].[BatchH] AS [PAY_BAH]
                           ON [PAY_BAH].[BATCHNO] = [TMP].[ReceiptBatchNo]
             WHERE [TMP].[id] = @I
               AND [SPL].[OSVALUE] = 0
               AND [SPL].[PENDINGOUTLAY] <> 0
               AND [BILL_BAD].[OUTLAY] = 'O' -- !If this was an Outlay Pending

            -- ! Generate Journals if Write-off requested
            IF @WRITEOFFREMAINDER = 1 AND
               EXISTS (SELECT TOP 1 1
                         FROM [dbo].[SupplierLedger] AS [SPL]
                        WHERE [SPL].[RECORDID] = @BIL_SPL_RECORDID
                          AND [SPL].[OSVALUE] <> 0)
            BEGIN                
                EXEC @WO_BATCHNO = [dbo].[ky_NETGetBatchNo]
                EXEC @WO_PREF = [dbo].[ky_NETGetPostRef]
                
                INSERT INTO [dbo].[BatchH] (
                       [BATCHNO],
                       [POSTFWD],
                       [TYPE],
                       [CODE],
                       [BRANCH],
                       [PREF],
                       [REF],
                       [DATE],
                       [FEE],
                       [MATTER],
                       [SUPP],
                       [NARR],
                       [VALUE],
                       [SUBTOT],
                       [POSTED],
                       [CLIENTAC],
                       [PERNO],
                       [YEAR],
                       [PAYEE],
                       [OUTLAYTOT],
                       [VATTOT],
                       [FEETOT],
                       [INVCR],
                       [THIRDPARTY],
                       [USERCODE],
                       [ENTRYDATE],
                       [CLIENTBANK],
                       [CURRENCY],
                       [CURRENCYVALUE],
                       [CUROUTLAYTOT],
                       [CURVATTOT],
                       [CURFEETOT],
                       [RECNO],
                       [SINGLELINE],
                       [TEMPLATE],
                       [CHEQUEREQNO],
                       [WRITEDOWN],
                       [WRITEBACKHOURS],
                       [WRITEBACKVALUE],
                       [CORRECTCOPY],
                       [CreditInvoiceNo],
                       [DraftBillNo],
                       [EFTSent],
                       [EFTDate],
                       [EFTFileNumber],
                       [EFTFileName],
                       [EFTYorN],
                       [ClientCode],
                       [PayClient],
                       [OnceOffPayment],
                       [CaseAssCode],
                       [EFTEmailYorN],
                       [HandlerCode],
                       [PaymentMethod],
                       [ClearedDate])
                SELECT @WO_BATCHNO      AS [BATCHNO],
                       [BAH].[POSTFWD]  AS [POSTFWD],
                       'J'              AS [TYPE],
                       ''               AS [CODE],
                       ''               AS [BRANCH],
                       @WO_PREF         AS [PREF],
                       ''               AS [REF],
                       [BAH].[DATE]     AS [DATE],
                       ''               AS [FEE],
                       ''               AS [MATTER],
                       ''               AS [SUPP],
                       'Automatic Creditors balance write-off' AS [NARR],
                       0                AS [VALUE],
                       0                AS [SUBTOT],
                       'N'              AS [POSTED],
                       ''               AS [CLIENTAC],
                       @PERNO           AS [PERNO],
                       @YEAR            AS [YEAR],
                       ''               AS [PAYEE],
                       0                AS [OUTLAYTOT],
                       0                AS [VATTOT],
                       0                AS [FEETOT],
                       ''               AS [INVCR],
                       ''               AS [THIRDPARTY],
                       ''               AS [USERCODE],
                       @TODAY           AS [ENTRYDATE],
                       ''               AS [CLIENTBANK],
                       ''               AS [CURRENCY],
                       0                AS [CURRENCYVALUE],
                       0                AS [CUROUTLAYTOT],
                       0                AS [CURVATTOT],
                       0                AS [CURFEETOT],
                       0                AS [RECNO],
                       ''               AS [SINGLELINE],
                       ''               AS [TEMPLATE],
                       0                AS [CHEQUEREQNO],
                       NULL             AS [WRITEDOWN],
                       0                AS [WRITEBACKHOURS],
                       0                AS [WRITEBACKVALUE],
                       ''               AS [CORRECTCOPY],
                       0                AS [CreditInvoiceNo],
                       0                AS [DraftBillno],
                       'N'              AS [EFTSent],
                       NULL             AS [EFTDate],
                       0                AS [EFTFileNumber],
                       ''               AS [EFTFileName],
                       'N'              AS [EFTYorN],
                       ''               AS [ClientCode],
                       'N'              AS [PayClient],
                       'N'              AS [OnceOffPayment],
                       ''               AS [CaseAssCode],
                       'N'              AS [EFTEmailYorN],
                       ''               AS [HandlerCode],
                       0                AS [PaymentMethod],
                       NULL             AS [ClearedDate]
                  FROM @ALLOCATIONS AS [TMP]
                       INNER JOIN [dbo].[BatchH] AS [BAH]
                               ON [BAH].[BATCHNO] = [TMP].[ReceiptBatchNo]
                       INNER JOIN [dbo].[BatchDetails] AS [BAD]
                               ON [BAD].[BATCHNO] = [BAH].[BATCHNO]
                              AND [BAD].[PREF] = [TMP].[ReceiptPostRef]
                 WHERE [TMP].[id] = @I

                INSERT INTO [dbo].[BatchDetails] (
                       [BATCHNO],
                       [TYPE],
                       [CODE],
                       [PREF],
                       [REF],
                       [DATE],
                       [FEE],
                       [BRANCH],
                       [NARR],
                       [MATTER],
                       [SUPP],
                       [VALUE],
                       [VATCODE],
                       [VATVAL],
                       [CLIENTYN],
                       [OUTLAY],
                       [PENDING],
                       [YEAR],
                       [PERNO],
                       [ENTRYCURRENCY],
                       [CURRENCYVALUE],
                       [CURRENCYVAT],
                       [OUTLAYCODE],
                       [THIRDPARTY],
                       [PAYEE],
                       [HEADPREF],
                       [HEADBATCH],
                       [ALLOCBATCH],
                       [ALLOCPREF],
                       [ALLOCREF],
                       [ALLOCVALUE],
                       [ALLOCWRITEOFF],
                       [PSUPP],
                       [UNDETAKING],
                       [CaseAssCode],
                       [OnceOffPayment],
                       [PayClient],
                       [ClientCode],
                       [EFTEmailYorN],
                       [RegisteredPost],
                       [PreBilledOutlay])
                SELECT @WO_BATCHNO,                     /* BATCHNO */
                       'J',                             /* TYPE */
                       @CREDITORS,                      /* CODE */
                       @WO_PREF + 1,                    /* PREF */
                       'W/o(auto)',                     /* REF */
                       [PAY_BAH].[DATE],                /* DATE */
                       '',                              /* FEE */
                       '',                              /* BRANCH */
                       'Automatic Write-off',           /* NARR */
                       '',                              /* MATTER */
                       LTRIM(RTRIM([PAY_BAD].[SUPP])),  /* SUPP */
                       [SPL].[OSVALUE] * -1,            /* VALUE */
                       @VATEXCLUDE,                     /* VATCODE */
                       0,                               /* VATVAL */
                       '',                              /* CLIENTYN */
                       'N',                             /* OUTLAY */
                       '',                              /* PENDING */
                       @YEAR,                           /* YEAR */
                       [PAY_BAH].[PERNO],               /* PERNO */
                       @BASECURRENCY,                   /* ENTRYCURRENCY */
                       CASE WHEN [PAY_BAH].[CURRENCY] = @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'I'
                                 THEN [SPL].[OSVALUE] * -1 / 0.787564
                            WHEN [PAY_BAH].[CURRENCY] = @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'E'
                                 THEN [SPL].[OSVALUE] * -1 * 0.787564
                            WHEN [PAY_BAH].[CURRENCY] <> @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'I'
                                 THEN [SPL].[OSVALUE] * -1 / 0.787564
                            WHEN [PAY_BAH].[CURRENCY] <> @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'E'
                                 THEN [SPL].[OSVALUE] * -1 * 0.787564
                            ELSE 0 END,                 /* CURRENCYVALUE */
                       0,                               /* CURRENCYVAT */
                       '',                              /* OUTLAYCODE */
                       '',                              /* THIRDPARTY */
                       '',                              /* PAYEE */
                       0,                               /* HEADPREF */
                       0,                               /* HEADBATCH */
                       [SPL].[BATCHNO],                 /* ALLOCBATCH */
                       [SPL].[PREF],                    /* ALLOCPREF */
                       LTRIM(RTRIM([SPL].[REF])),       /* ALLOCREF */
                       [SPL].[OSVALUE],                 /* ALLOCVALUE */
                       '',                              /* ALLOCWRITEOFF */
                       '',                              /* PSUPP */
                       0,                               /* UNDETAKING */
                       '',                              /* CaseAssCode */
                       'N',                             /* OnceOffPayment */
                       'N',                             /* PayClient */
                       '',                              /* ClientCode */
                       'N',                             /* EFTEmailYorN */
                       0,                               /* RegisteredPost */
                       0                                /* PreBilledOutlay */
                  FROM [dbo].[BatchH] AS [BAH]
                       INNER JOIN [dbo].[SupplierLedger] AS [SPL]
                               ON [SPL].[RECORDID] = @BIL_SPL_RECORDID
                       INNER JOIN @ALLOCATIONS AS [TMP]
                               ON [TMP].[id] = @I
                       INNER JOIN [dbo].[BatchDetails] AS [PAY_BAD]
                               ON [PAY_BAD].[BATCHNO] = [TMP].[ReceiptBatchNo]
                              AND [PAY_BAD].[PREF] = [TMP].[ReceiptPostRef]
                       INNER JOIN [dbo].[BatchH] AS [PAY_BAH]
                               ON [PAY_BAH].[BATCHNO] = [PAY_BAD].[BATCHNO]
                 WHERE [BAH].[BATCHNO] = @WO_BATCHNO
                
                INSERT INTO [dbo].[BatchDetails] (
                       [BATCHNO],
                       [TYPE],
                       [CODE],
                       [PREF],
                       [REF],
                       [DATE],
                       [FEE],
                       [BRANCH],
                       [NARR],
                       [MATTER],
                       [SUPP],
                       [VALUE],
                       [VATCODE],
                       [VATVAL],
                       [CLIENTYN],
                       [OUTLAY],
                       [PENDING],
                       [YEAR],
                       [PERNO],
                       [ENTRYCURRENCY],
                       [CURRENCYVALUE],
                       [CURRENCYVAT],
                       [OUTLAYCODE],
                       [THIRDPARTY],
                       [PAYEE],
                       [HEADPREF],
                       [HEADBATCH],
                       [ALLOCBATCH],
                       [ALLOCPREF],
                       [ALLOCREF],
                       [ALLOCVALUE],
                       [ALLOCWRITEOFF],
                       [PSUPP],
                       [UNDETAKING],
                       [CaseAssCode],
                       [OnceOffPayment],
                       [PayClient],
                       [ClientCode],
                       [EFTEmailYorN],
                       [RegisteredPost],
                       [PreBilledOutlay])
                SELECT @WO_BATCHNO,           /* BATCHNO */
                       'J',                   /* TYPE */
                       @BILLSWRITEOFF,        /* CODE */
                       @WO_PREF + 2,          /* PREF */
                       'W/o(auto)',           /* REF */
                       [PAY_BAH].[DATE],      /* DATE */
                       '',                    /* FEE */
                       '',                    /* BRANCH */
                       'Automatic Write-off', /* NARR */
                       '',                    /* MATTER */
                       '',                    /* SUPP */
                       [SPL].[OSVALUE],       /* VALUE */
                       @VATEXCLUDE,           /* VATCODE */
                       0,                     /* VATVAL */
                       '',                    /* CLIENTYN */
                       'N',                   /* OUTLAY */
                       '',                    /* PENDING */
                       @YEAR,                 /* YEAR */
                       [PAY_BAH].[PERNO],     /* PERNO */
                       @BASECURRENCY,         /* ENTRYCURRENCY */
                       CASE WHEN [PAY_BAH].[CURRENCY] = @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'I'
                                 THEN [SPL].[OSVALUE] / 0.787564
                            WHEN [PAY_BAH].[CURRENCY] = @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'E'
                                 THEN [SPL].[OSVALUE] * 0.787564
                            WHEN [PAY_BAH].[CURRENCY] <> @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'I'
                                 THEN [SPL].[OSVALUE] / 0.787564
                            WHEN [PAY_BAH].[CURRENCY] <> @BASECURRENCY
                             AND [PAY_BAH].[CURRENCY] = 'E'
                                 THEN [SPL].[OSVALUE] * 0.787564
                            ELSE 0 END,       /* CURRENCYVALUE */
                       0,                     /* CURRENCYVAT */
                       '',                    /* OUTLAYCODE */
                       '',                    /* THIRDPARTY */
                       '',                    /* PAYEE */
                       0,                     /* HEADPREF */
                       0,                     /* HEADBATCH */
                       0,                     /* ALLOCBATCH */
                       0,                     /* ALLOCPREF */
                       '',                    /* ALLOCREF */
                       0,                     /* ALLOCVALUE */
                       '',                    /* ALLOCWRITEOFF */
                       '',                    /* PSUPP */
                       0,                     /* UNDETAKING */
                       '',                    /* CaseAssCode */
                       'N',                   /* OnceOffPayment */
                       'N',                   /* PayClient */
                       '',                    /* ClientCode */
                       'N',                   /* EFTEmailYorN */
                       0,                     /* RegisteredPost */
                       0                      /* PreBilledOutlay */
                  FROM [dbo].[BatchH] AS [BAH]
                       INNER JOIN [dbo].[SupplierLedger] AS [SPL]
                               ON [SPL].[RECORDID] = @BIL_SPL_RECORDID
                       INNER JOIN @ALLOCATIONS AS [TMP]
                               ON [TMP].[id] = @I
                       INNER JOIN [dbo].[BatchH] AS [PAY_BAH]
                               ON [PAY_BAH].[BATCHNO] = [TMP].[ReceiptBatchNo]
                 WHERE [BAH].[BATCHNO] = @WO_BATCHNO
            END
        END
        
        SET @I = @I + 1
    END
END

GO

IF EXISTS (SELECT TOP 1 1
             FROM [sys].[objects] AS [so]
            WHERE [so].[name] = N'KAAS_BGPaid'
              AND [so].[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_BGPaid]
END
GO
 
CREATE PROCEDURE [dbo].[KAAS_BGPaid] (
       @Matter      VARCHAR(17),
       @BatchNo     INT,
       @Unpaid      INT,
       @ForceFees   INT,
       @ForceOutlay INT)
AS
BEGIN

UPDATE BGD
   SET BGD.[PaidNow] = Case WHEN @Unpaid = 1
                                 THEN 0
                            ELSE BGD.[BillNow] END
  from [dbo].[debtorsledger] DRL
       INNER JOIN [dbo].[billheader] BIH
                  inner join BGControl BGC
                             inner join BGDetail BGD
                                     on BGD.[BGControlID] = BGC.[ID]
                                    and BGD.[Type] = 'O'
                                    and (   isnull(@Matter, '') = ''
                                         OR BGD.[Matter] = isnull(@Matter, ''))
                          on BGC.BATCHNO = BIH.BATCHNO
               ON BIH.[BATCHNO] <> 0
              AND BIH.[BATCHNO] = DRL.[BATCHNO]
 WHERE (   @BatchNo is null
        OR DRL.[BATCHNO] = @BatchNo)
   AND (   OSOUTLAY = 0
        OR @ForceOutlay = 1)

UPDATE BGD
   SET BGD.[PaidNow] = Case WHEN @Unpaid = 1
                                 THEN 0
                            ELSE BGD.[BillNow] END
  from [dbo].[debtorsledger] DRL
       INNER JOIN [dbo].[billheader] BIH
                  inner join BGControl BGC
                             inner join BGDetail BGD
                                     on BGD.[BGControlID] = BGC.[ID]
                                    and BGD.[Type] = 'F'
                                    and (   isnull(@Matter, '') = ''
                                         OR BGD.[Matter] = isnull(@Matter, ''))
                          on BGC.BATCHNO = BIH.BATCHNO
               ON BIH.[BATCHNO] <> 0
              AND BIH.[BATCHNO] = DRL.[BATCHNO]
 WHERE (   @BatchNo is null
        OR DRL.[BATCHNO] = @BatchNo)
   AND (   OSFEES = 0
        OR @ForceFees = 1)

END
GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CheckBatchRecordPresent' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CheckBatchRecordPresent] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CheckBatchRecordPresent]  
	( 
		@BatchNo INT = 0
	)

AS

/*******************************************************************************************************
* Check if Batch record present or not                                                                 * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CheckBatchRecordPresent]        								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-12-29    Balamurugan C        Created                                                           *
 *******************************************************************************************************/

BEGIN
 SET NOCOUNT ON  

 IF NOT EXISTS
	(
		SELECT TOP 1 1
		  FROM [dbo].[BatchH] 
		 WHERE [BatchNo] = @BatchNo
	)
    BEGIN
		SELECT 'N' AS [BatchStatus]	 
	END 
 ELSE
	BEGIN
		SELECT 'Y' AS [BatchStatus]
	END

 SET NOCOUNT OFF


 END
 GO

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

GO

CREATE PROCEDURE 
       [dbo].[KAAS_CheckHandlerCodeExist]
      (@HandlerCode VARCHAR(10),
       @Result      TINYINT OUTPUT)
AS

BEGIN
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_CheckHandlerCodeExist]                                                                     *
 *                                                                                                           *
 * Description: This procedure is used to check handler code exists or not                                   *
 *                                                                                                           *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification history:                                                                                     *
 * 2021-06-25  Natarajan S            Created					                                                     *

 *************************************************************************************************************/

    IF EXISTS
      (SELECT TOP 1 1 
         FROM [dbo].[Handlers] HAN
        WHERE HAN.[CODE] = @HandlerCode)
      BEGIN
        SET @Result = 1
      END
    ELSE 
      IF EXISTS
        (SELECT TOP 1 1 
           FROM [dbo].[HandlerChargeGroups] HCG
          WHERE HCG.[Code] = @HandlerCode)
        BEGIN
          SET @Result = 2
        END
      ELSE
        BEGIN
          SET @Result = 0 
        END
    
END

GO

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

CREATE PROCEDURE [dbo].[KAAS_CheckIfBatchHExists]  
	( 
		@BatchNo varchar(50)
	)
AS
/*******************************************************************************************************
* Check if Batch header exists                                                                         * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CheckIfBatchHExists]        								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-08    Revathy D        Created                                                               *
* 2022-02-28    Balamurugan.C    Modified - Handled TCL Statements                                     *
 *******************************************************************************************************/
 BEGIN
 SET NOCOUNT ON  
  BEGIN TRY
     BEGIN TRAN
		 IF NOT EXISTS
			(
				SELECT TOP 1 * 
				  FROM [dbo].[BatchH] 
				 WHERE [BatchNo] = @BatchNo
			)
			BEGIN
				DELETE 
				  FROM [dbo].[BatchDetails] 
				 WHERE [BatchNo] =  @BatchNo  
			END 
       COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	 END CATCH
 SET NOCOUNT OFF


 END

 GO


 


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CheckSAMClientMoneyLaunderingApproved' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CheckSAMClientMoneyLaunderingApproved] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_CheckSAMClientMoneyLaunderingApproved]
	(
		@ClientCode			VARCHAR(10) = ''
	)
AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CheckSAMClientMoneyLaunderingApproved]  					       *
* Description: To check specified client marked as approved for money laundering					   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-08-31    Balamurugan C        Created                                                           *
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON

		SELECT [Code],
			   [Approved]
		  FROM [dbo].[Contacts]
		 WHERE [Code] = @ClientCode

	SET NOCOUNT OFF		
END
GO

IF OBJECT_ID(N'KAAS_CheckSAMClosedMatter',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_CheckSAMClosedMatter]
GO
CREATE PROCEDURE [dbo].[KAAS_CheckSAMClosedMatter]
	(
		@Code VARCHAR(50)
	)
AS

/*******************************************************************************************************
* To get details of closed matter																	   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CheckSAMClosedMatter]        					                   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-08-25    Vinodhkumar M      Created                                                             *
* 2021-09-03    Balamurugan.C      Modified -Added Outlay Budget                                       *
* 2021-09-17    Balamurugan.C      Modified -Added Client Name,Description                             *
 *******************************************************************************************************/

BEGIN
	 SELECT	[MAT].[Code]			AS [Code],
			[MAT].[ClientCode]		AS [ClientCode],
			[MAT].[Matter]			AS [MatterNo],
			[MAT].[FECode]			AS [FECode],
			[MAT].[Closed]			AS [Closed],
			[MAT].[ClientMin]		AS [ClientMin],
			[MAT].[OutlayBud]		AS [OutlayBud],
			[CON].[Name]			AS [Name],
			[MAT].[Description]		AS [Description]
	   FROM [dbo].[matters] [MAT]
  LEFT JOIN [dbo].[Contacts] [CON]
         ON [MAT].[ClientCode] = [CON].[Code]
	  WHERE [MAT].[Code] = @Code

END


GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CheckSAMJournalAllocatedOutlayLimit' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CheckSAMJournalAllocatedOutlayLimit] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CheckSAMJournalAllocatedOutlayLimit] 
			(
                  @Matter           VARCHAR(20) = '',
				  @JournalAmount	DECIMAL     = 0 
            )
AS
/*******************************************************************************************************
* Fetches the Invoice list                                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CheckSAMJournalAllocatedOutlayLimit] 'BAR001/0001'               *
*                                                                                                      *
* Modification History:                                                                                *
* 05 Oct 2021    Balamurugan C        Created														   *
* 06 Oct 2021    Balamurugan C        Modified - Added Journal amount in Sum on allocated batch value  *													   *                                          
 *******************************************************************************************************/
BEGIN

	DECLARE @AllocationCnt      INT = 0,
			@ValidAllocationCnt INT  = 0;

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

		SELECT [BatchNo],
			   [Matter]
		  INTO #AllocTempDetails 
		  FROM [dbo].[DebtorsLedger]
		 WHERE [Matter] = @Matter

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

		SELECT [BAD].*
		  INTO #TempBatchDetailsAlloc
		  FROM [dbo].[BatchDetails] [BAD]
		  JOIN #AllocTempDetails [ATD]
			ON [BAD].[ALLOCBATCH] = [ATD].[BATCHNO]
		  JOIN [dbo].[BatchH] [BAH]
			ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
		 WHERE [BAD].[Type] = 'J' AND
			   [BAH].POSTED <> 'Y' 


	SET @AllocationCnt = (SELECT COUNT(1) FROM #TempBatchDetailsAlloc)

	IF(@AllocationCnt > 0)
		BEGIN
			SET @ValidAllocationCnt =(
										SELECT COUNT(1)
										FROM [dbo].Matters [MAT]  WITH (NOLOCK)
							 LEFT OUTER JOIN [dbo].[Contacts] [CON] WITH (NOLOCK)
										  ON [MAT].[ClientCode] = [CON].[Code]
									   WHERE [MAT].[OutlayBal] < 0 AND
											 [MAT].[OutlayBal] + [MAT].[DebtBal] >= 0 AND
											 [MAT].[OutlayBal] < ( SELECT SUM([AllocValue]) + (ISNULL(@JournalAmount,0) * -1)
																	 FROM #TempBatchDetailsAlloc 
																  ) AND
											 [MAT].[Code]  = @Matter
									 )
			IF(@ValidAllocationCnt>0)
				BEGIN
					SELECT 'Allocation Within Limit' AS ResultValue
				END
			ELSE
				BEGIN
					SELECT 'Allocation Over Limit' AS ResultValue
				END

		END
	ELSE
		BEGIN
			SELECT 'No Allocation Found' as ResultValue
		END

END
GO


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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_CheckUnpostedPayments]
AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CheckUnpostedPayments]      									   *
* Description: To check whether any unposted payments and multi payments present		    		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2024-04-29    Balamurugan C        Created                                                           *
 *******************************************************************************************************/
BEGIN

	DECLARE @IsUnpostedBatchPresent VARCHAR(1) = 'N'

	IF EXISTS(SELECT TOP 1 1 
					  FROM [dbo].[BatchH]  
					 WHERE [Posted] = 'N'
					   AND ([Type] = 'P' OR [Type] = 'M'))
	BEGIN
		SET  @IsUnpostedBatchPresent = 'Y';
	END

	SELECT @IsUnpostedBatchPresent

END
GO

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

CREATE PROCEDURE [dbo].[KAAS_CommonSAMUpdatePosting](
       @PostedBatchNo INT         = 0,
       @PostedType    VARCHAR(1)  = '',
       @IsPostingFwd  VARCHAR(1)  = '',
       @HandlerName   VARCHAR(20) = '')
AS
  /*******************************************************************************************************
  * Update Posting Logic                                                                                 *
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_CommonSAMUpdatePosting]                                          *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-11-12    Balamurugan C        Created                                                           *
  * 2022-01-03    Balamurugan C        Modified - Changed Matter Varchar(10) to Varchar(20)              *
  * 2022-01-13    Balamurugan C        Modified - Split Receipt,Payment,Journal into Separate SP         *
  * 2022-02-24    John Ginnane         Changed parameters to purchase bills and refactored code          *
  * 2023-10-16	  Ghayathri			   Removed 'Type' parameters to Multiplayment SP					 *
  ********************************************************************************************************/
BEGIN
    BEGIN TRY
        BEGIN TRAN

        /* UPDATE POSTING PURCHASE BILLS */
        IF @PostedType = 'B'
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMPurchaseBill] @PostedBatchNo, @IsPostingFwd, @HandlerName
        END

        /* UPDATE POSTING BANK TRANSFER */
        IF(@PostedType = 'T')
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMBankTransfer] @PostedBatchNo,@IsPostingFwd,@HandlerName
        END

        /* UPDATE POSTING MULTI PAYMENT */
        IF(@PostedType = 'M')
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMMultiPayment] @PostedBatchNo,@IsPostingFwd,@HandlerName
        END

        /* UPDATE POSTING ISSUE INVOICE */
        IF @PostedType = 'I'
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMInvoice] @PostedBatchNo, @IsPostingFwd, @HandlerName
        END
        
        /* UPDATE POSTING RECEIPT BATCHES */
        IF @PostedType = 'R'
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMReceipts] @PostedBatchNo, @IsPostingFwd, @HandlerName
        END

        /* UPDATE POSTING PAYMENT BATCHES */
        IF @PostedType = 'P'
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMPayment] @PostedBatchNo, @IsPostingFwd, @HandlerName
        END

        /* UPDATE POSTING JOURNAL BATCHES */
        IF @PostedType = 'J'
        BEGIN
            EXEC [dbo].[KAAS_UpdatePostingSAMJournal] @PostedBatchNo, @IsPostingFwd, @HandlerName
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        -- Each UpdatePosting procedure has it's own try/catch which can rollback
        -- So we check if we're still in a transactions before trying to rollback
        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRAN
        END
    END CATCH
END
GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CompleteBankReconciliationProcess' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CompleteBankReconciliationProcess] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CompleteBankReconciliationProcess]
	( 
		@BankAc	           VARCHAR(10)   = '',
		@ReconDate	       DATE          = NULL
	)
AS
/*******************************************************************************************************
* Complete Bank Reconciliation Process																   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CompleteBankReconciliationProcess]   			                   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-27    Balamurugan C        Created                                                           *
* 2022-02-02    Balamurugan C        Modified - Update Nominal Ledger,Bank Balance using Ticked        *
* 2022-02-08    Balamurugan C        Modified - Change Logic for Outstanding logic                     *
* 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 * 
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRAN
	/*UPDATE DATE COMPLETE AND LAST RECON NUMBER*/
		
		DECLARE @LastReconNumber    INT = 0,
				@CurrentReconNumber INT = 0

		  SELECT @LastReconNumber = MAX(RecNo)
	   	    FROM [dbo].[BankRecHistory]
		   WHERE RTRIM([BankAc]) = @BankAc
	         AND [DateComplete] IS NOT NULL

		  SELECT @CurrentReconNumber = [RecNo]
	   	    FROM [dbo].[BankRecHistory]
		   WHERE RTRIM([BankAc]) = @BankAc
	         AND [DateComplete] IS NULL
			 
		  UPDATE [dbo].[BankRecHistory]
		     SET [DateComplete]  =  CAST(GETDATE() AS DATE),
			     [LastRec]       =  @LastReconNumber
		   WHERE [DateComplete] IS NULL
		     AND RTRIM([BankAc]) = @BankAc

	/* INSERT INTO COMPLETE REC TRANSACTION TABLE*/

		  INSERT 
		    INTO [dbo].[BankRecCompleteTrans]
			   (
				 [BankAc],
				 [Type],
				 [Date],
				 [Ref],
				 [Batch],
				 [Pref],
				 [Narr],
				 [Value],
				 [OsRecNo],
				 [RecNo],
				 [Ticked],
				 [NomTransId]
			   )
			   (
		  SELECT [BankAc],
				 [Type],
				 [Date],
				 [Ref],
				 [Batch],
				 [Pref],
				 [Narr],
				 [Value],
				 [OsRecNo],
				 [RecNo],
				 [Ticked],
				 [NomTransId]
			FROM [dbo].[BankRecTransactions]
		   WHERE [BankAc] = @BankAc
			 AND [RecNo]  =	@CurrentReconNumber 
			   )


	/* UPDATE NOMINAL LEDGER VALUES*/
		 UPDATE [NML]
		    SET [NML].[RecNo]  = ABS([BRC].[RecNo])
		   FROM [dbo].[NominalLedger] [NML]
		   JOIN [dbo].[BankRecCompleteTrans] [BRC]
		     ON [BRC].[NomTransId] = [NML].[RecordId]
			AND [BRC].[Ticked]     = 'R'
		  WHERE [NML].[Code]       = @BankAc

	/* UPDATE BATCH HEADER RECON TABLE*/
		 UPDATE [BAH]
		    SET [BAH].[RecNo]  = ABS([BRC].[RecNo])
		   FROM [dbo].[BatchH] [BAH]
		   JOIN [dbo].[BankRecCompleteTrans] [BRC]
		     ON [BRC].[Batch] = [BAH].[BatchNo]
			AND [BRC].[Ticked]     = 'R'
		
	/* DELETE OUTSTANDING TRANSACTION AND RECON TRANSCTION */
		
		 DELETE [BOT]
		   FROM [dbo].[BankRecOutstandingTrans] [BOT]
		   JOIN [dbo].[BankRecTransactions] [BRT]
		     ON [BRT].[BankAc] = [BOT].[BankAc]
			AND [BRT].[NomTransId] = [BOT].[RECORDID]
		  WHERE [BOT].[BankAc] = @BankAc
		    AND [BRT].[RecNo]  = @CurrentReconNumber
			AND [BRT].[Ticked] = 'R'    

		 DELETE 
		   FROM [dbo].[BankRecTransactions]
		  WHERE [BankAc] = @BankAc
		    AND [RecNo]  = @CurrentReconNumber 


		COMMIT TRAN
	END TRY

	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	END CATCH		

END

GO

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

CREATE PROCEDURE 
	[dbo].[KAAS_CopyBatchDetails]
	(
		@KeyId decimal
	)

AS

/*******************************************************************************************************
* Copy existing batch details                                                                          * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CopyBatchDetails]          								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-10    Revathy D        Created                                                               *
* 2022-02-25    Balamurugan.C    Modified - Handled TCL Statements                                     *
* 2024-04-23    Balamurugan.C    Modified - Handled logic for creating new head batch and pref for     *
                                            multi payment                                              *
 *******************************************************************************************************/

BEGIN
  SET NOCOUNT ON 
   	BEGIN TRY
	 BEGIN TRAN

		DECLARE @PREF int 
		SET @PREF = (SELECT 
			MAX(PREF)+1 PREF
		FROM 
		(
		  (
			SELECT 
				PREF, 
				BATCHNO 
			FROM DBO.BATCHH 
		  )
		 UNION ALL
		  (
			SELECT 
				PREF, 
				BATCHNO 
			FROM DBO.BATCHDETAILS
		  )
		) BAT)


			DECLARE @NEWHEADBATCH   INT
			DECLARE @NEWHEADPREF    INT
			DECLARE @IsMultiPayment VARCHAR(1) = 'N';

			IF EXISTS (SELECT 1 FROM [BatchDetails] WHERE [KEYID] = @KeyId AND [TYPE] = 'M')
			BEGIN
				 SET @IsMultiPayment = 'Y'
			  SELECT @NEWHEADBATCH = LASTBATCH + 1,
					 @NEWHEADPREF = LASTPREF + 1
			    FROM [dbo].[control]

			  UPDATE [dbo].[control] 
				 SET [LASTBATCH] = @NEWHEADBATCH,
					 [LASTPREF] = @NEWHEADPREF
			END
		

		INSERT INTO 
			[dbo].[BatchDetails] 
				(
					[BATCHNO], 
					[TYPE], 
					[CODE], 
					[PREF], 
					[REF], 
					[DATE], 
					[FEE], 
					[BRANCH], 
					[NARR], 
					[MATTER], 
					[SUPP], 
					[VALUE], 
					[VATCODE], 
					[VATVAL], 
					[CLIENTYN], 
					[OUTLAY], 
					[PENDING], 
					[YEAR], 
					[PERNO], 
					[ENTRYCURRENCY], 
					[CURRENCYVALUE], 
					[CURRENCYVAT], 
					[OUTLAYCODE], 
					[THIRDPARTY], 
					[PAYEE], 
					[HEADPREF], 
					[HEADBATCH], 
					[ALLOCBATCH], 
					[ALLOCPREF], 
					[ALLOCREF], 
					[ALLOCVALUE], 
					[ALLOCWRITEOFF], 
					[PSUPP], 
					[UNDETAKING], 
					[CaseAssCode], 
					[OnceOffPayment], 
					[PayClient], 
					[ClientCode], 
					[EFTEmailYorN], 
					[RegisteredPost]
				)
				SELECT 
					[BATCHNO], 
					[TYPE], 
					[CODE], 
					@PREF, 
					[REF], 
					[DATE], 
					[FEE], 
					[BRANCH], 
					[NARR], 
					[MATTER], 
					[SUPP], 
					[VALUE], 
					[VATCODE], 
					[VATVAL], 
					[CLIENTYN], 
					[OUTLAY], 
					[PENDING], 
					[YEAR], 
					[PERNO], 
					[ENTRYCURRENCY], 
					[CURRENCYVALUE], 
					[CURRENCYVAT], 
					[OUTLAYCODE], 
					[THIRDPARTY], 
					[PAYEE], 
					CASE WHEN @IsMultiPayment = 'Y' THEN @NEWHEADPREF ELSE [HEADPREF] END, 
					CASE WHEN @IsMultiPayment = 'Y' THEN @NEWHEADBATCH ELSE [HEADBATCH] END, 
					[ALLOCBATCH], 
					[ALLOCPREF], 
					[ALLOCREF], 
					[ALLOCVALUE], 
					[ALLOCWRITEOFF], 
					[PSUPP], 
					[UNDETAKING], 
					[CaseAssCode], 
					[OnceOffPayment], 
					[PayClient], 
					[ClientCode], 
					[EFTEmailYorN], 
					[ALLOCBATCH]
				FROM 
					[dbo].[BatchDetails] 
					WHERE [KEYID] = @KeyId

   		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	 END CATCH
  SET NOCOUNT OFF
 END



 GO



IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateBankReconciliationTransaction' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateBankReconciliationTransaction] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateBankReconciliationTransaction]
	( 
		@BankAc	           VARCHAR(10)   = '',
		@ReconDate	       DATE          = NULL,
		@Mode              VARCHAR(25)   = ''
	)
AS
/*******************************************************************************************************
* Process and Create new record in bank reconciliation process and fetch posted records from batches   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateBankReconciliationTransaction]   			               *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-24    Balamurugan C        Created                                                           *
* 2022-02-10    Balamurugan C        Modified - Used SAM window Existing Procedure                     *
* 2022-02-11    Balamurugan C        Modified - Created new SP for intiate and refresh process         *
*                                                as per SAM                                            *
* 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/
BEGIN
  BEGIN TRY
    BEGIN TRAN
			   DECLARE @NEXTRECON INT = 0
			   DECLARE @LASTRECON INT = 0

				SELECT @NEXTRECON = ISNULL([CON].[LastRecon] + 1, 0)
				  FROM [dbo].[control] AS [CON]

				SELECT @LASTRECON = ISNULL(MAX([BRH].[RECNO]), 0)
				  FROM [dbo].[BankRecHistory] AS [BRH]
				 WHERE [BRH].[BANKAC] = @BANKAC


		IF @MODE= 'CREATE'
		   BEGIN
		   		UPDATE [dbo].[control]
				   SET [LastRecon] = @NEXTRECON
				  EXEC [dbo].[KAAS_SAMInitiateBankRec] @NEXTRECON, @BankAc, @ReconDate, @LASTRECON
			END
		IF @MODE = 'REFRESH'
		   BEGIN
				  EXEC [dbo].[KAAS_SAMRefreshBankRec] @LASTRECON, @BankAc
		   END


					SELECT [RecNo],
						   RTRIM([BankAc])	 AS [BankAc],
						   [RecDate],
						   [DateComplete],
						   [LastRec],
						   RTRIM([Currency]) AS [Currency],
						   [OpeningBalance],
						   [Lodgements],
						   [Cheques],
						   [OsLodgements],
						   [OsCheques],
						   [BankBal],
						   [ClosingBal],
						   [Diff]
					  FROM [dbo].[BankRecHistory]
					 WHERE [BankAc] = @BankAc
					   AND [DateComplete] IS NULL 
				

					SELECT RTRIM([BRT].[BankAc]) AS [BankAc],
						   RTRIM([BRT].[Type])	 AS [Type],
						   [BRT].[Date],
						   RTRIM([BRT].[Ref])    AS [Ref],
						   [BRT].[Batch],
						   [BRT].[Pref],
						   RTRIM([BRT].[Narr])	 AS [Narr],
						   [BRT].[Value],
						   [BRT].[OsRecNo],
						   [BRT].[RecNo],
						   RTRIM([BRT].[Ticked]) AS [Ticked],
						   [RecordId],
						   [BRT].[NomTransId]
					  FROM [dbo].[BankRecTransactions] [BRT]
					  JOIN [dbo].[BankRecHistory] [BRH]
						ON [BRH].[RecNo]  = [BRT].[RecNo]
					 WHERE [BRT].[BankAc] = @BankAc
     COMMIT TRAN
 END TRY

 BEGIN CATCH
	DECLARE @ErrorMsg      NVARCHAR(4000), 
			@ErrorSeverity INT,
			@ErrorState    INT; 

	SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
		   @ErrorSeverity = ERROR_SEVERITY(), 
		   @ErrorState    = ERROR_STATE()

 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
		  IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
 END CATCH
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_CreateBatch] (
       @BATCHNO         INT,
       @POSTFWD         CHAR(1)        = '',
       @TYPE            CHAR(1),
       @CODE            CHAR(10),
       @BRANCH          VARCHAR(3)     = '',
       @PREF            INT,
       @REF             CHAR(10),
       @DATE            DATETIME,
       @FEE             VARCHAR(10)    = '',
       @MATTER          VARCHAR(20)    = '',
       @SUPP            CHAR(10)       = '',
       @NARR            CHAR(150),
       @VALUE           DECIMAL(17, 2),
       @SUBTOT          DECIMAL(17, 2) = 0.00,
       @POSTED          CHAR(1),
       @CLIENTAC        CHAR(1),
       @PERNO           SMALLINT,
       @YEAR            SMALLINT,
       @PAYEE           CHAR(60)       = '',
       @OUTLAYTOT       DECIMAL(17, 2) = 0.00,
       @VATTOT          DECIMAL(17, 2) = 0.00,
       @FEETOT          DECIMAL(17, 2) = 0.00,
       @INVCR           CHAR(1),
       @THIRDPARTY      CHAR(1)        = '',
       @USERCODE        CHAR(8)        = '',
       @ENTRYDATE       DATETIME,
       @CLIENTBANK      CHAR(10)       = '',
       @CURRENCY        CHAR(1)        = 'E',
       @CURRENCYVALUE   DECIMAL(17, 2) = 0.00,
       @CUROUTLAYTOT    DECIMAL(17, 2) = 0.00,
       @CURVATTOT       DECIMAL(17, 2) = 0.00,
       @CURFEETOT       DECIMAL(17, 2) = 0.00,
       @RECNO           INT            = 0,
       @SINGLELINE      CHAR(1)        = '',
       @TEMPLATE        CHAR(10)       = '',
       @CHEQUEREQNO     INT            = 0,
       @WRITEDOWN       DATETIME       = NULL,
       @WRITEBACKHOURS  DECIMAL(7, 2)  = 0.00,
       @WRITEBACKVALUE  DECIMAL(13, 2) = 0.00,
       @CORRECTCOPY     CHAR(1)        = '',
       @CREDITINVOICENO INT            = 0,
       @DRAFTBILLNO     INT            = 0,
       @EFTSENT         CHAR(1)        = 'N',
       @EFTDATE         DECIMAL        = NULL,
       @EFTFILENUMBER   INT            = NULL,
       @EFTFILENAME     VARCHAR(500)   = NULL,
       @EFTYORN         CHAR(1)        = 'N',
       @CLIENTCODE      VARCHAR(10)    = NULL,
       @PAYCLIENT       CHAR(1)        = 'N',
       @ONCEOFFPAYMENT  CHAR(1)        = 'N',
       @CASEASSCODE     VARCHAR(6)     = NULL,
       @EFTEMAILYORN    CHAR(1)        = 'N',
       @FNCODE          VARCHAR(10)    = NULL,
       @PAYMETHOD       INT            = 0,
       @CLEARDATE       DATETIME       = NULL)
AS
/*******************************************************************************************************
* Save the Batch Header                                                                                *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateBatch]                                                     *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-09    Revathy D        Created                                                               *
* 2021-04-12    Revathy D        Updated                                                               *
* 2021-09-09    Balamurugan      Updated-Removed Entry Date Column from update                         *
* 2021-09-09    Vinodhkumar M    Updated-Paymethod, cleared date			                           *
* 2021-11-26    Balamurugan C    Added Calcuation for Curren Value			                           *
* 2022-01-11    Vinodhkumar M    Updated-Formatted the WriteDown Parameter  			               *
* 2022-01-20    Balamurugan C    Modified - Include CAST AS DATE for all datetime fields               *
* 2022-01-28    Balamurugan C    Modified - Include CAST AS DATE for before function                   *
                                            all datetime fields                                        *
* 2022-02-04    Balamurugan C    Modified - Added Default Values for few fields                        *
* 2022-02-04    John Ginnane     Create XML version and moved code into there                          *
* 2022-02-16    Balamurugan.C    Added new line end of the procedure 
* 2022-09-27    Ghayathri.S.V    Removed Currency value as input paramater to  KAAS_CreateBatchXML SP  *
* 2022-10-11    Ghayathri.S.V    Modified - Conditional currency as input parameter to the Batch XML.  *
********************************************************************************************************/
BEGIN
    SET NOCOUNT ON
    
    DECLARE @XML NVARCHAR(MAX)
    SET @XML = (SELECT @BATCHNO         AS [BATCHNO],
                       @POSTFWD         AS [POSTFWD],
                       @TYPE            AS [TYPE],
                       @CODE            AS [CODE],
                       @BRANCH          AS [BRANCH],
                       @PREF            AS [PREF],
                       @REF             AS [REF],
                       @DATE            AS [DATE],
                       @FEE             AS [FEE],
                       @MATTER          AS [MATTER],
                       @SUPP            AS [SUPP],
                       @NARR            AS [NARR],
                       @VALUE           AS [VALUE],
                       @SUBTOT          AS [SUBTOT],
                       @POSTED          AS [POSTED],
                       @CLIENTAC        AS [CLIENTAC],
                       @PERNO           AS [PERNO],
                       @YEAR            AS [YEAR],
                       @PAYEE           AS [PAYEE],
                       @OUTLAYTOT       AS [OUTLAYTOT],
                       @VATTOT          AS [VATTOT],
                       @FEETOT          AS [FEETOT],
                       @INVCR           AS [INVCR],
                       @THIRDPARTY      AS [THIRDPARTY],
                       @USERCODE        AS [USERCODE],
                       @ENTRYDATE       AS [ENTRYDATE],
                       @CLIENTBANK      AS [CLIENTBANK],
                       CASE WHEN @TYPE IN ('T','B')
					        THEN ''
                       ELSE @CURRENCY 
					   END              AS [CURRENCY],
                       @CUROUTLAYTOT    AS [CUROUTLAYTOT],
                       @CURFEETOT       AS [CURFEETOT],
                       @RECNO           AS [RECNO],
                       @SINGLELINE      AS [SINGLELINE],
                       @TEMPLATE        AS [TEMPLATE],
                       @CHEQUEREQNO     AS [CHEQUEREQNO],
                       @WRITEDOWN       AS [WRITEDOWN],
                       @WRITEBACKHOURS  AS [WRITEBACKHOURS],
                       @WRITEBACKVALUE  AS [WRITEBACKVALUE],
                       @CORRECTCOPY     AS [CORRECTCOPY],
                       @CREDITINVOICENO AS [CreditInvoiceNo],
                       @DRAFTBILLNO     AS [DraftBillNo],
                       @EFTSENT         AS [EFTSent],
                       @EFTDATE         AS [EFTDate],
                       @EFTFILENUMBER   AS [EFTFileNumber],
                       @EFTFILENAME     AS [EFTFileName],
                       @EFTYORN         AS [EFTYorN],
                       @CLIENTCODE      AS [ClientCode],
                       @PAYCLIENT       AS [PayClient],
                       @ONCEOFFPAYMENT  AS [OnceOffPayment],
                       @CASEASSCODE     AS [CaseAssCode],
                       @EFTEMAILYORN    AS [EFTEmailYorN],
                       @PAYMETHOD       AS [PaymentMethod],
                       @CLEARDATE       AS [ClearedDate]
                   FOR XML RAW('BatchH'))

    SET @XML = N'<Data User="' + ISNULL(LTRIM(RTRIM(@FNCODE)), '') + N'">' + @XML + N'</Data>'

    EXEC [dbo].[KAAS_CreateBatchXML] @XML

    SET NOCOUNT OFF
END
GO

IF EXISTS (SELECT TOP 1 1
             FROM [sys].[objects] AS [so]
            WHERE [so].[name] = N'KAAS_CreateBatchDetails'
              AND [so].[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_CreateBatchDetails]
END
GO

CREATE PROCEDURE [dbo].[KAAS_CreateBatchDetails] (
       @KEYID            INT,
       @BATCHNO          INT,
       @PREF             INT,
       @REF              CHAR(10),
       @DATE             DATETIME,
       @NARR             CHAR(100),
       @MATTER           VARCHAR(20),
       @VALUE            DECIMAL(17,2),
       @VATCODE          CHAR(1),
       @VATVAL           DECIMAL(17,2)  = 0.00,
       @YEAR             SMALLINT,
       @PERNO            SMALLINT,
       @CODE             CHAR(10)       = '',
       @ALLOCREF         CHAR(10)       = '',
       @ALLOCVALUE       DECIMAL(17,2)  = 0.00,
       @ALLOCBATCH       INT,
       @ALLOCPREF        INT,
       @OUTLAY           CHAR(1),
       @ALLOCWRITEOFF    CHAR(1)       = '',
       @FNCODE           VARCHAR(10)   = NULL,
       @TYPE             CHAR(1)       = '',
       @SUPP             VARCHAR(10)   = '',
       @OUTLAYCODE       VARCHAR(4)    = '',
       @FEE              VARCHAR(10)   = '',
       @BRANCH           VARCHAR(3)    = '',
       @PAYEE            VARCHAR(60)   = '',
       @ONCEOFFPAYMENT   CHAR(1)       = 'N',
       @PAYCLIENT        CHAR(1)       = 'N',
       @THIRDPARTY       CHAR(1)       = 'N',
       @CLIENTCODE       VARCHAR(10)   = '',
       @EFTEMAILYORN     CHAR(1)       = 'N',
       @CASEASSCODE      VARCHAR(6)    = '',
       @CURRENCYVALUE    DECIMAL(17,2) = 0,
       @HEADBATCH        INT           = 0,
       @HEADPREF         INT           = 0,
       @PSUPP            CHAR(10)      = '',
       @UNDETAKING       SMALLINT      = 0,
       @CLIENTYN         CHAR(1)       = '',
       @PENDING          CHAR(1)       = '',
	   @RegisteredPost   INT           = 0,
       @PreBilledOutlay  INT           = 0,
	   @ENTRYCURRENCY    CHAR(1)	   = 'E'
	   )
AS
  /*******************************************************************************************************
  * Save the Batch Details                                                                               *
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_CreateBatchDetails]                                              *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-04-10    Revathy D        Created                                                               *
  * 2021-04-23    Balamurugan C    Modified -Added Payee,Third Party Column                              *
  * 2021-04-25    Balamurugan C    Modified -Case Associate Column                                       *
  * 2021-09-21    Revathy D        Modified - Default Code is modified for type 'P'                      *
  * 2021-10-18    Vinodhkumar M    Modified - Added Currency Value Parameter                             *
  * 2021-11-26    Balamurugan C    Added Calcuation for Curren Value and Current VAT		             *
  * 2021-12-07    vinodhkumar M    Added headbatch, headpref columns			    		             *
  * 2022-01-20    Balamurugan C    Modified - Include CAST AS DATE for all datetime fields               *
  * 2022-01-28    Balamurugan C    Modified - Include CAST AS DATE for before function                   *
                                              all datetime fields                                        *
  * 2022-02-04    John Ginnane     Replaced existing code with new XML call                              *
  * 2022-02-16    Balamurugan.C    Added new line end of the procedure 
  * 2022-04-11    Ghayathri.S.V    Added Registered Post and PreBilledOutLay  
  * 2022-09-27    Ghayathri.S.V    Removed Currency value as input paramater to 
                                   KAAS_CreateBatchDetailsXML SP                                         *
  * 2022-10-11    Ghayathri.S.V    Modified - Entry Currencylogic based on clarion logic for type 
                                              bank transfer                                              *                                
  ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON

    DECLARE @XML NVARCHAR(MAX)
    SET @XML = (SELECT @BATCHNO        AS [BATCHNO],
                       @TYPE           AS [TYPE],
                       @CODE           AS [CODE],
                       @PREF           AS [PREF],
                       @REF            AS [REF],
                       @DATE           AS [DATE],
                       @FEE            AS [FEE],
                       @BRANCH         AS [BRANCH],
                       @NARR           AS [NARR],
                       @MATTER         AS [MATTER],
                       @SUPP           AS [SUPP],
                       @VALUE          AS [VALUE],
                       @VATCODE        AS [VATCODE],
                       @VATVAL         AS [VATVAL],
                       @CLIENTYN       AS [CLIENTYN],
                       @OUTLAY         AS [OUTLAY],
                       @PENDING        AS [PENDING],
                       @YEAR           AS [YEAR],
                       @PERNO          AS [PERNO],
                       @OUTLAYCODE     AS [OUTLAYCODE],
                       @THIRDPARTY     AS [THIRDPARTY],
                       @PAYEE          AS [PAYEE],
                       @HEADPREF       AS [HEADPREF],
                       @HEADBATCH      AS [HEADBATCH],
                       @ALLOCBATCH     AS [ALLOCBATCH],
                       @ALLOCPREF      AS [ALLOCPREF],
                       @ALLOCREF       AS [ALLOCREF],
                       @ALLOCVALUE     AS [ALLOCVALUE],
                       @ALLOCWRITEOFF  AS [ALLOCWRITEOFF],
                       @PSUPP          AS [PSUPP],
                       @UNDETAKING     AS [UNDETAKING],
                       @KEYID          AS [KEYID],
                       @CASEASSCODE    AS [CaseAssCode],
                       @ONCEOFFPAYMENT AS [OnceOffPayment],
                       @PAYCLIENT      AS [PayClient],
                       @CLIENTCODE     AS [ClientCode],
                       @EFTEMAILYORN   AS [EFTEmailYorN],
					   @RegisteredPost AS [RegisteredPost],
					   @PreBilledOutlay AS [PreBilledOutlay],
					   CASE 
					   WHEN @TYPE = 'T'
					   THEN ''
                       ELSE @ENTRYCURRENCY 
					   END              AS [ENTRYCURRENCY]
		
                   FOR XML RAW('BatchDetails'))

    SET @XML = N'<Data User="' + ISNULL(LTRIM(RTRIM(@FNCODE)), '') + N'">' + @XML + N'</Data>'

    EXEC [dbo].[KAAS_CreateBatchDetailsXML] @XML
    SET NOCOUNT OFF
END
GO

IF EXISTS (SELECT TOP 1 1
             FROM sys.[objects] SO
            WHERE SO.[name] = N'KAAS_CreateBatchDetailsXML'
              AND SO.[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_CreateBatchDetailsXML]
END
GO
CREATE PROCEDURE [dbo].[KAAS_CreateBatchDetailsXML]
      (@XML NVARCHAR(MAX))
AS
  /*******************************************************************************************************
  * Save the Batch Details                                                                               *
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_CreateBatchDetailsXML]                                           *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2022-01-27    John Ginnane     13662 - Created                                                       *
  * 2022-02-16    Balamurugan.C    Added new line end of the procedure                                   *
  * 2022-02-17    Balamurugan.C    Modified - Chnaged CurrencyValue and Vat syntax                       *
  * 2022-02-18    Balamurugan.C    Modified - Currency Value need to fetch from form for journal         *
  * 2022-02-22    Balamurugan.C    Modified - Currency Value is 0 for transfer type                      *
  * 2022-02-23    Balamurugan.C    Modified - Handled T-SQL Statements                                   *
  * 2022-05-09    Vignesh M        Modified - UTC Conversion Removed   
  * 2022-09-27    Ghayathri.S.V    Modified - CURRENCYVAT input parameter from @VALUE to @VATVAL         *
  * 2022-10-03    Ghayathri.S.V    Modified - For journal type updated the currecny value based on EI 
                                              conversion                                                 *
  * 2022-10-11    Ghayathri.S.V    Modified - For bank transfer type updated the currecny value based 
                                              on clarion logic                                          *                                            
  *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON
    BEGIN TRY
        BEGIN TRAN   
            DECLARE @iSL             INT
            DECLARE @BASECURRENCY    CHAR(1)
            DECLARE @IECONVERT       DECIMAL(17,6)
			DECLARE @EICONVERT       DECIMAL(17,6)
            DECLARE @VATEXCLUDE      VARCHAR(1)
            DECLARE @CURRENTYEAR     INT
            DECLARE @CURRENTPERIOD   INT
    
            SELECT @BASECURRENCY   = [CON].[BASECURRENCY],
                   @IECONVERT      = [CON].[IECONVERT],
                   @VATEXCLUDE     = [CON].[VATEXCLUDE],
                   @CURRENTYEAR    = [CON].[YEAR],
                   @CURRENTPERIOD  = [CON].[CURPER],
				   @EICONVERT      = [CON].[EICONVERT]
              FROM [dbo].[control] AS [CON]

            BEGIN TRY
            EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
            END TRY
            BEGIN CATCH
            EXEC sp_xml_preparedocument @iSL OUTPUT, N'<Data />'
            END CATCH

            DECLARE @USER            VARCHAR(100)
            DECLARE @BATCHNO         INT
            DECLARE @TYPE            CHAR(1)
            DECLARE @CODE            CHAR(10)
            DECLARE @PREF            INT
            DECLARE @REF             CHAR(10)
            DECLARE @DATE            DATETIME
            DECLARE @FEE             VARCHAR(10)
            DECLARE @BRANCH          VARCHAR(3)
            DECLARE @NARR            CHAR(100)
            DECLARE @MATTER          VARCHAR(20)
            DECLARE @SUPP            CHAR(10)
            DECLARE @VALUE           DECIMAL(17, 2)
            DECLARE @VATCODE         CHAR(1)
            DECLARE @VATVAL          DECIMAL(17, 2)
            DECLARE @CLIENTYN        CHAR(1)
            DECLARE @OUTLAY          CHAR(1)
            DECLARE @PENDING         CHAR(1)
            DECLARE @YEAR            SMALLINT
            DECLARE @PERNO           SMALLINT
            DECLARE @ENTRYCURRENCY   CHAR(1)
            DECLARE @CURRENCYVALUE   DECIMAL(17, 2)
            DECLARE @CURRENCYVAT     DECIMAL(17, 2)
            DECLARE @OUTLAYCODE      CHAR(4)
            DECLARE @THIRDPARTY      CHAR(1)
            DECLARE @PAYEE           CHAR(60)
            DECLARE @HEADPREF        INT
            DECLARE @HEADBATCH       INT
            DECLARE @ALLOCBATCH      INT
            DECLARE @ALLOCPREF       INT
            DECLARE @ALLOCREF        CHAR(10)
            DECLARE @ALLOCVALUE      DECIMAL(17, 2)
            DECLARE @ALLOCWRITEOFF   CHAR(1)
            DECLARE @PSUPP           CHAR(10)
            DECLARE @UNDETAKING      SMALLINT
            DECLARE @KEYID           DECIMAL(9, 0)
            DECLARE @CaseAssCode     VARCHAR(6)
            DECLARE @OnceOffPayment  CHAR(1)
            DECLARE @PayClient       CHAR(1)
            DECLARE @ClientCode      VARCHAR(10)
            DECLARE @EFTEmailYorN    CHAR(1)
            DECLARE @RegisteredPost  INT
            DECLARE @PreBilledOutlay BIT

            SELECT @USER             = ISNULL([XML].[User],            ''),
                   @BATCHNO          = ISNULL([XML].[BATCHNO],         0),
                   @TYPE             = ISNULL([XML].[TYPE],            ''),
                   @CODE             = ISNULL([XML].[CODE],            ''),
                   @PREF             = ISNULL([XML].[PREF],            0),
                   @REF              = ISNULL([XML].[REF],             ''),
                   @DATE             = [XML].[DATE],
                   @FEE              = ISNULL([XML].[FEE],             ''),
                   @BRANCH           = ISNULL([XML].[BRANCH],          ''),
                   @NARR             = ISNULL([XML].[NARR],            ''),
                   @MATTER           = ISNULL([XML].[MATTER],          ''),
                   @SUPP             = ISNULL([XML].[SUPP],            ''),
                   @VALUE            = ISNULL([XML].[VALUE],           0),
                   @VATCODE          = ISNULL([XML].[VATCODE],         ''),
                   @VATVAL           = ISNULL([XML].[VATVAL],          0),
                   @CLIENTYN         = ISNULL([XML].[CLIENTYN],        ''),
                   @OUTLAY           = ISNULL([XML].[OUTLAY],          ''),
                   @PENDING          = ISNULL([XML].[PENDING],         ''),
                   @YEAR             = ISNULL([XML].[YEAR],            @CURRENTYEAR),
                   @PERNO            = ISNULL([XML].[PERNO],           @CURRENTPERIOD),
                   @ENTRYCURRENCY    = [XML].[ENTRYCURRENCY],
                   @CURRENCYVALUE    = [XML].[CURRENCYVALUE],
                   @CURRENCYVAT      = [XML].[CURRENCYVAT],
                   @OUTLAYCODE       = ISNULL([XML].[OUTLAYCODE],      ''),
                   @THIRDPARTY       = ISNULL([XML].[THIRDPARTY],      'N'),
                   @PAYEE            = ISNULL([XML].[PAYEE],           ''),
                   @HEADPREF         = ISNULL([XML].[HEADPREF],        0),
                   @HEADBATCH        = ISNULL([XML].[HEADBATCH],       0),
                   @ALLOCBATCH       = ISNULL([XML].[ALLOCBATCH],      0),
                   @ALLOCPREF        = ISNULL([XML].[ALLOCPREF],       0),
                   @ALLOCREF         = ISNULL([XML].[ALLOCREF],        ''),
                   @ALLOCVALUE       = ISNULL([XML].[ALLOCVALUE],      0),
                   @ALLOCWRITEOFF    = ISNULL([XML].[ALLOCWRITEOFF],   ''),
                   @PSUPP            = ISNULL([XML].[PSUPP],           ''),
                   @UNDETAKING       = ISNULL([XML].[UNDETAKING],      0),
                   @KEYID            = ISNULL([XML].[KEYID],           0),
                   @CaseAssCode      = ISNULL([XML].[CaseAssCode],     ''),
                   @OnceOffPayment   = ISNULL([XML].[OnceOffPayment],  'N'),
                   @PayClient        = ISNULL([XML].[PayClient],       'N'),
                   @ClientCode       = ISNULL([XML].[ClientCode],      ''),
                   @EFTEmailYorN     = ISNULL([XML].[EFTEmailYorN],    'N'),
                   @RegisteredPost   = ISNULL([XML].[RegisteredPost],  0),
                   @PreBilledOutlay  = ISNULL([XML].[PreBilledOutlay], 0)
              FROM OPENXML(@iSL, N'Data/BatchDetails')
              WITH ([User]            VARCHAR(10)    '../@User',
                    [BATCHNO]         INT            '@BATCHNO',
                    [TYPE]            CHAR(1)        '@TYPE',
                    [CODE]            CHAR(10)       '@CODE',
                    [PREF]            INT            '@PREF',
                    [REF]             CHAR(10)       '@REF',
                    [DATE]            DATETIME       '@DATE',
                    [FEE]             VARCHAR(10)    '@FEE',
                    [BRANCH]          VARCHAR(3)     '@BRANCH',
                    [NARR]            CHAR(100)      '@NARR',
                    [MATTER]          VARCHAR(20)    '@MATTER',
                    [SUPP]            CHAR(10)       '@SUPP',
                    [VALUE]           DECIMAL(17, 2) '@VALUE',
                    [VATCODE]         CHAR(1)        '@VATCODE',
                    [VATVAL]          DECIMAL(17, 2) '@VATVAL',
                    [CLIENTYN]        CHAR(1)        '@CLIENTYN',
                    [OUTLAY]          CHAR(1)        '@OUTLAY',
                    [PENDING]         CHAR(1)        '@PENDING',
                    [YEAR]            SMALLINT       '@YEAR',
                    [PERNO]           SMALLINT       '@PERNO',
                    [ENTRYCURRENCY]   CHAR(1)        '@ENTRYCURRENCY',
                    [CURRENCYVALUE]   DECIMAL(17, 2) '@CURRENCYVALUE',
                    [CURRENCYVAT]     DECIMAL(17, 2) '@CURRENCYVAT',
                    [OUTLAYCODE]      CHAR(4)        '@OUTLAYCODE',
                    [THIRDPARTY]      CHAR(1)        '@THIRDPARTY',
                    [PAYEE]           CHAR(60)       '@PAYEE',
                    [HEADPREF]        INT            '@HEADPREF',
                    [HEADBATCH]       INT            '@HEADBATCH',
                    [ALLOCBATCH]      INT            '@ALLOCBATCH',
                    [ALLOCPREF]       INT            '@ALLOCPREF',
                    [ALLOCREF]        CHAR(10)       '@ALLOCREF',
                    [ALLOCVALUE]      DECIMAL(17, 2) '@ALLOCVALUE',
                    [ALLOCWRITEOFF]   CHAR(1)        '@ALLOCWRITEOFF',
                    [PSUPP]           CHAR(10)       '@PSUPP',
                    [UNDETAKING]      SMALLINT       '@UNDETAKING',
                    [KEYID]           DECIMAL(9, 0)  '@KEYID',
                    [CaseAssCode]     VARCHAR(6)     '@CaseAssCode',
                    [OnceOffPayment]  CHAR(1)        '@OnceOffPayment',
                    [PayClient]       CHAR(1)        '@PayClient',
                    [ClientCode]      VARCHAR(10)    '@ClientCode',
                    [EFTEmailYorN]    CHAR(1)        '@EFTEmailYorN',
                    [RegisteredPost]  INT            '@RegisteredPost',
                    [PreBilledOutlay] BIT            '@PreBilledOutlay') AS [XML]
    
            BEGIN TRY
            EXEC sp_xml_removedocument @iSL
            END TRY
            BEGIN CATCH
            END CATCH

            IF @TYPE <> 'P' OR (@TYPE = 'P' AND @CODE = '')
            BEGIN
                SET @CODE = (SELECT CASE @OUTLAY
                                         WHEN 'C' THEN ISNULL([CON].[CLIENT], '')
                                         WHEN 'O' THEN ISNULL([CON].[OUTLAY], '')
                                         WHEN 'D' THEN ISNULL([CON].[DEBTORS], '')
                                    ELSE @CODE END
                               FROM [dbo].[control] AS [CON])    
            END
            
            /*
                Prepare dates by handling timezones
                Remove time component for backwards compatibility
                with Clarion apps
            */

            SET @DATE = DATEADD(DAY, DATEDIFF(DAY, 0,@DATE), 0)
                
            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchDetails] AS [BAD]
                        WHERE [BAD].[KEYID] = @KEYID)
            BEGIN
                    UPDATE [BAD]
                       SET [BAD].[BATCHNO]          = @BATCHNO,
                           [BAD].[TYPE]             = @TYPE,
                           [BAD].[CODE]             = @CODE,
                           [BAD].[PREF]             = @PREF,
                           [BAD].[REF]              = @REF,
                           [BAD].[DATE]             = @DATE,
                           [BAD].[FEE]              = @FEE,
                           [BAD].[BRANCH]           = @BRANCH,
                           [BAD].[NARR]             = @NARR,
                           [BAD].[MATTER]           = @MATTER,
                           [BAD].[SUPP]             = @SUPP,
                           [BAD].[VALUE]            = @VALUE,
                           [BAD].[VATCODE]          = @VATCODE,
                           [BAD].[VATVAL]           = @VATVAL,
                           [BAD].[CLIENTYN]         = @CLIENTYN,
                           [BAD].[OUTLAY]           = @OUTLAY,
                           [BAD].[PENDING]          = @PENDING,
                           [BAD].[YEAR]             = @YEAR,
                           [BAD].[PERNO]            = @PERNO,
                           [BAD].[ENTRYCURRENCY]    = @ENTRYCURRENCY,
                           [BAD].[CURRENCYVALUE]    = ISNULL(@CURRENCYVALUE, CONVERT(DECIMAL(19, 2), 
															CASE 
															WHEN @TYPE =  'J' 
															THEN (@VALUE/@EICONVERT)
														    WHEN @TYPE =  'T' 
														    THEN 
																(CASE WHEN @BASECURRENCY = @ENTRYCURRENCY 
																	  THEN (@VALUE * @IECONVERT)
														              ELSE 0 END)
															ELSE (@VALUE * @IECONVERT) END)),
                           [BAD].[CURRENCYVAT]      = ISNULL(@CURRENCYVAT, CONVERT(DECIMAL(19, 2), @VATVAL * @IECONVERT)),
                           [BAD].[OUTLAYCODE]       = @OUTLAYCODE,
                           [BAD].[THIRDPARTY]       = @THIRDPARTY,
                           [BAD].[PAYEE]            = @PAYEE,
                           [BAD].[HEADPREF]         = @HEADPREF,
                           [BAD].[HEADBATCH]        = @HEADBATCH,
                           [BAD].[ALLOCBATCH]       = @ALLOCBATCH,
                           [BAD].[ALLOCPREF]        = @ALLOCPREF,
                           [BAD].[ALLOCREF]         = @ALLOCREF,
                           [BAD].[ALLOCVALUE]       = @ALLOCVALUE,
                           [BAD].[ALLOCWRITEOFF]    = @ALLOCWRITEOFF,
                           [BAD].[PSUPP]            = @PSUPP,
                           [BAD].[UNDETAKING]       = @UNDETAKING,
                           [BAD].[CaseAssCode]      = @CaseAssCode,
                           [BAD].[OnceOffPayment]   = @OnceOffPayment,
                           [BAD].[PayClient]        = @PayClient,
                           [BAD].[ClientCode]       = @ClientCode,
                           [BAD].[EFTEmailYorN]     = @EFTEmailYorN,
                           [BAD].[RegisteredPost]   = @RegisteredPost,
                           [BAD].[PreBilledOutlay]  = @PreBilledOutlay
                      FROM [dbo].[BatchDetails] AS [BAD]
                     WHERE [BAD].[KEYID] = @KEYID
                END
                ELSE
                BEGIN
                    INSERT INTO [dbo].[BatchDetails] (
                           [BATCHNO],
                           [TYPE],
                           [CODE],
                           [PREF],
                           [REF],
                           [DATE],
                           [FEE],
                           [BRANCH],
                           [NARR],
                           [MATTER],
                           [SUPP],
                           [VALUE],
                           [VATCODE],
                           [VATVAL],
                           [CLIENTYN],
                           [OUTLAY],
                           [PENDING],
                           [YEAR],
                           [PERNO],
                           [ENTRYCURRENCY],
                           [CURRENCYVALUE],
                           [CURRENCYVAT],
                           [OUTLAYCODE],
                           [THIRDPARTY],
                           [PAYEE],
                           [HEADPREF],
                           [HEADBATCH],
                           [ALLOCBATCH],
                           [ALLOCPREF],
                           [ALLOCREF],
                           [ALLOCVALUE],
                           [ALLOCWRITEOFF],
                           [PSUPP],
                           [UNDETAKING],
                           [CaseAssCode],
                           [OnceOffPayment],
                           [PayClient],
                           [ClientCode],
                           [EFTEmailYorN],
                           [RegisteredPost],
                           [PreBilledOutlay])
                    VALUES (@BATCHNO,
                            @TYPE,
                            @CODE,
                            @PREF,
                            @REF,
                            @DATE,
                            @FEE,
                            @BRANCH,
                            @NARR,
                            @MATTER,
                            @SUPP,
                            @VALUE,
                            @VATCODE,
                            @VATVAL,
                            @CLIENTYN,
                            @OUTLAY,
                            @PENDING,
                            @YEAR,
                            @PERNO,
                            @ENTRYCURRENCY,
                            ISNULL(@CURRENCYVALUE, CONVERT(DECIMAL(19, 2), 
							CASE 
							WHEN @TYPE =  'J' 
							THEN (@VALUE/@EICONVERT)
							WHEN @TYPE =  'T' 
							THEN (CASE WHEN @BASECURRENCY = @ENTRYCURRENCY 
							           THEN (@VALUE * @IECONVERT)
							           ELSE 0 END)
							ELSE (@VALUE * @IECONVERT) END)),
                            ISNULL(@CURRENCYVAT, CONVERT(DECIMAL(19, 2), @VATVAL * @IECONVERT)),
                            @OUTLAYCODE,
                            @THIRDPARTY,
                            @PAYEE,
                            @HEADPREF,
                            @HEADBATCH,
                            @ALLOCBATCH,
                            @ALLOCPREF,
                            @ALLOCREF,
                            @ALLOCVALUE,
                            @ALLOCWRITEOFF,
                            @PSUPP,
                            @UNDETAKING,
                            @CaseAssCode,
                            @OnceOffPayment,
                            @PayClient,
                            @ClientCode,
                            @EFTEmailYorN,
                            @RegisteredPost,
                            @PreBilledOutlay)
                END
            COMMIT TRAN
        END TRY

        BEGIN CATCH
            DECLARE @ErrorMsg      NVARCHAR(4000)
            DECLARE @ErrorSeverity INT
            DECLARE @ErrorState    INT

            SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
                   @ErrorSeverity = ERROR_SEVERITY(),
                   @ErrorState    = ERROR_STATE()

            RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState)

            IF @@TRANCOUNT > 0
            BEGIN
                ROLLBACK TRANSACTION
            END
        END CATCH
    SET NOCOUNT OFF
END
GO

IF EXISTS (SELECT TOP 1 1
             FROM sys.[objects] SO
            WHERE SO.[name] = N'KAAS_CreateBatchXML'
              AND SO.[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_CreateBatchXML]
END
GO
CREATE PROCEDURE [dbo].[KAAS_CreateBatchXML]
      (@XML NVARCHAR(MAX))
AS
/*******************************************************************************************************
* Save the Batch Header                                                                                *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateBatchXML]                                                  *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-02-04    John Ginnane     Created                                                               *
* 2022-02-16    Balamurugan.C    Added new line end of the procedure                                   *
* 2022-02-17    Balamurugan C    Modified - Changed Syntax for currency rates                          *
* 2022-02-18    Balamurugan.C    Modified - Currency Value need to fetch from form for journal         *
* 2022-02-22    Balamurugan.C    Modified - Currency Value is 0 for transfer type                      *
* 2022-02-23    Balamurugan.C    Modified - Handled T-SQL Statements                                   *
* 2022-05-04    Vignesh.M        Modified - Entry Date Removed in Update Statement                     *
* 2022-05-09    Vignesh M        Modified - UTC Conversion Removed                                     *
* 2022-10-11    Ghayathri.S.V    Modified - Currency Value logic for Bank Tranfer and
                                            Purchase Bill Type                                         *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON
    BEGIN TRY
        BEGIN TRAN    
            DECLARE @iSL             INT
            DECLARE @BASECURRENCY    CHAR(1)
            DECLARE @IECONVERT       DECIMAL(17,6)
            DECLARE @VATEXCLUDE      VARCHAR(1)
            DECLARE @CURRENTYEAR     INT
            DECLARE @CURRENTPERIOD   INT

            SELECT @BASECURRENCY   = [CON].[BASECURRENCY],
                   @IECONVERT      = [CON].[IECONVERT],
                   @VATEXCLUDE     = [CON].[VATEXCLUDE],
                   @CURRENTYEAR    = [CON].[YEAR],
                   @CURRENTPERIOD  = [CON].[CURPER]
              FROM [dbo].[control] AS [CON]

            BEGIN TRY
            EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
            END TRY
            BEGIN CATCH
            EXEC sp_xml_preparedocument @iSL OUTPUT, N'<Data />'
            END CATCH
    
            DECLARE @USER            VARCHAR(100)
            DECLARE @BATCHNO         INT
            DECLARE @POSTFWD         CHAR(1)
            DECLARE @TYPE            CHAR(1)
            DECLARE @CODE            CHAR(10)
            DECLARE @BRANCH          VARCHAR(3)
            DECLARE @PREF            INT
            DECLARE @REF             CHAR(10)
            DECLARE @DATE            DATETIME
            DECLARE @FEE             VARCHAR(10)
            DECLARE @MATTER          VARCHAR(20)
            DECLARE @SUPP            CHAR(10)
            DECLARE @NARR            CHAR(150)
            DECLARE @VALUE           DECIMAL(17, 2)
            DECLARE @SUBTOT          DECIMAL(17, 2)
            DECLARE @POSTED          CHAR(1)
            DECLARE @CLIENTAC        CHAR(1)
            DECLARE @PERNO           SMALLINT
            DECLARE @YEAR            SMALLINT
            DECLARE @PAYEE           CHAR(60)
            DECLARE @OUTLAYTOT       DECIMAL(17, 2)
            DECLARE @VATTOT          DECIMAL(17, 2)
            DECLARE @FEETOT          DECIMAL(17, 2)
            DECLARE @INVCR           CHAR(1)
            DECLARE @THIRDPARTY      CHAR(1)
            DECLARE @USERCODE        CHAR(8)
            DECLARE @ENTRYDATE       DATETIME
            DECLARE @CLIENTBANK      CHAR(10)
            DECLARE @CURRENCY        CHAR(1)
            DECLARE @CURRENCYVALUE   DECIMAL(17, 2)
            DECLARE @CUROUTLAYTOT    DECIMAL(17, 2)
            DECLARE @CURVATTOT       DECIMAL(17, 2)
            DECLARE @CURFEETOT       DECIMAL(17, 2)
            DECLARE @RECNO           INT
            DECLARE @SINGLELINE      CHAR(1)
            DECLARE @TEMPLATE        CHAR(10)
            DECLARE @CHEQUEREQNO     INT
            DECLARE @WRITEDOWN       DATETIME
            DECLARE @WRITEBACKHOURS  DECIMAL(7, 2)
            DECLARE @WRITEBACKVALUE  DECIMAL(13, 2)
            DECLARE @CORRECTCOPY     CHAR(1)
            DECLARE @CreditInvoiceNo INT
            DECLARE @DraftBillNo     INT
            DECLARE @EFTSent         CHAR(1)
            DECLARE @EFTDate         DATETIME
            DECLARE @EFTFileNumber   INT
            DECLARE @EFTFileName     VARCHAR(500)
            DECLARE @EFTYorN         CHAR(1)
            DECLARE @ClientCode      VARCHAR(10)
            DECLARE @PayClient       CHAR(1)
            DECLARE @OnceOffPayment  CHAR(1)
            DECLARE @CaseAssCode     VARCHAR(6)
            DECLARE @EFTEmailYorN    CHAR(1)
            DECLARE @HandlerCode     VARCHAR(10)
            DECLARE @PaymentMethod   INT
            DECLARE @ClearedDate     DATETIME

            SELECT @USER             = ISNULL([XML].[User],            ''),
                   @BATCHNO          = ISNULL([XML].[BATCHNO],         0),
                   @POSTFWD          = ISNULL([XML].[POSTFWD],         ''),
                   @TYPE             = ISNULL([XML].[TYPE],            ''),
                   @CODE             = ISNULL([XML].[CODE],            ''),
                   @BRANCH           = ISNULL([XML].[BRANCH],          ''),
                   @PREF             = ISNULL([XML].[PREF],            0),
                   @REF              = ISNULL([XML].[REF],             ''),
                   @DATE             = ISNULL([XML].[DATE],            NULL),
                   @FEE              = ISNULL([XML].[FEE],             ''),
                   @MATTER           = ISNULL([XML].[MATTER],          ''),
                   @SUPP             = ISNULL([XML].[SUPP],            ''),
                   @NARR             = ISNULL([XML].[NARR],            ''),
                   @VALUE            = ISNULL([XML].[VALUE],           0),
                   @SUBTOT           = ISNULL([XML].[SUBTOT],          0),
                   @POSTED           = ISNULL([XML].[POSTED],          'N'),
                   @CLIENTAC         = ISNULL([XML].[CLIENTAC],        'N'),
                   @PERNO            = ISNULL([XML].[PERNO],           @CURRENTPERIOD),
                   @YEAR             = ISNULL([XML].[YEAR],            @CURRENTYEAR),
                   @PAYEE            = ISNULL([XML].[PAYEE],           ''),
                   @OUTLAYTOT        = ISNULL([XML].[OUTLAYTOT],       0),
                   @VATTOT           = ISNULL([XML].[VATTOT],          0),
                   @FEETOT           = ISNULL([XML].[FEETOT],          0),
                   @INVCR            = ISNULL([XML].[INVCR],           ''),
                   @THIRDPARTY       = ISNULL([XML].[THIRDPARTY],      ''),
                   @USERCODE         = ISNULL([XML].[USERCODE],        ''),
                   @ENTRYDATE        = ISNULL([XML].[ENTRYDATE],       DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)),
                   @CLIENTBANK       = ISNULL([XML].[CLIENTBANK],      ''),
                   @CURRENCY         = ISNULL([XML].[CURRENCY],        @BASECURRENCY),
                   @CURRENCYVALUE    = [XML].[CURRENCYVALUE],
                   @CUROUTLAYTOT     = [XML].[CUROUTLAYTOT],
                   @CURVATTOT        = [XML].[CURVATTOT],
                   @CURFEETOT        = [XML].[CURFEETOT],
                   @RECNO            = ISNULL([XML].[RECNO],           0),
                   @SINGLELINE       = ISNULL([XML].[SINGLELINE],      ''),
                   @TEMPLATE         = ISNULL([XML].[TEMPLATE],        ''),
                   @CHEQUEREQNO      = ISNULL([XML].[CHEQUEREQNO],     0),
                   @WRITEDOWN        = ISNULL([XML].[WRITEDOWN],       NULL),
                   @WRITEBACKHOURS   = ISNULL([XML].[WRITEBACKHOURS],  0),
                   @WRITEBACKVALUE   = ISNULL([XML].[WRITEBACKVALUE],  0),
                   @CORRECTCOPY      = ISNULL([XML].[CORRECTCOPY],     ''),
                   @CreditInvoiceNo  = ISNULL([XML].[CreditInvoiceNo], 0),
                   @DraftBillNo      = ISNULL([XML].[DraftBillNo],     0),
                   @EFTSent          = ISNULL([XML].[EFTSent],         'N'),
                   @EFTDate          = ISNULL([XML].[EFTDate],         NULL),
                   @EFTFileNumber    = ISNULL([XML].[EFTFileNumber],   NULL),
                   @EFTFileName      = ISNULL([XML].[EFTFileName],     ''),
                   @EFTYorN          = ISNULL([XML].[EFTYorN],         'N'),
                   @ClientCode       = ISNULL([XML].[ClientCode],      ''),
                   @PayClient        = ISNULL([XML].[PayClient],       'N'),
                   @OnceOffPayment   = ISNULL([XML].[OnceOffPayment],  'N'),
                   @CaseAssCode      = ISNULL([XML].[CaseAssCode],     ''),
                   @EFTEmailYorN     = ISNULL([XML].[EFTEmailYorN],    'N'),
                   @HandlerCode      = ISNULL([XML].[HandlerCode],     NULL),
                   @PaymentMethod    = ISNULL([XML].[PaymentMethod],   NULL),
                   @ClearedDate      = ISNULL([XML].[ClearedDate],     NULL)
              FROM OPENXML(@iSL, N'Data/BatchH')
              WITH ([User]            VARCHAR(10)    '../@User',
                    [BATCHNO]         INT            '@BATCHNO',
                    [POSTFWD]         CHAR(1)        '@POSTFWD',
                    [TYPE]            CHAR(1)        '@TYPE',
                    [CODE]            CHAR(10)       '@CODE',
                    [BRANCH]          VARCHAR(3)     '@BRANCH',
                    [PREF]            INT            '@PREF',
                    [REF]             CHAR(10)       '@REF',
                    [DATE]            DATETIME       '@DATE',
                    [FEE]             VARCHAR(10)    '@FEE',
                    [MATTER]          VARCHAR(20)    '@MATTER',
                    [SUPP]            CHAR(10)       '@SUPP',
                    [NARR]            CHAR(150)      '@NARR',
                    [VALUE]           DECIMAL(17, 2) '@VALUE',
                    [SUBTOT]          DECIMAL(17, 2) '@SUBTOT',
                    [POSTED]          CHAR(1)        '@POSTED',
                    [CLIENTAC]        CHAR(1)        '@CLIENTAC',
                    [PERNO]           SMALLINT       '@PERNO',
                    [YEAR]            SMALLINT       '@YEAR',
                    [PAYEE]           CHAR(60)       '@PAYEE',
                    [OUTLAYTOT]       DECIMAL(17, 2) '@OUTLAYTOT',
                    [VATTOT]          DECIMAL(17, 2) '@VATTOT',
                    [FEETOT]          DECIMAL(17, 2) '@FEETOT',
                    [INVCR]           CHAR(1)        '@INVCR',
                    [THIRDPARTY]      CHAR(1)        '@THIRDPARTY',
                    [USERCODE]        CHAR(8)        '@USERCODE',
                    [ENTRYDATE]       DATETIME       '@ENTRYDATE',
                    [CLIENTBANK]      CHAR(10)       '@CLIENTBANK',
                    [CURRENCY]        CHAR(1)        '@CURRENCY',
                    [CURRENCYVALUE]   DECIMAL(17, 2) '@CURRENCYVALUE',
                    [CUROUTLAYTOT]    DECIMAL(17, 2) '@CUROUTLAYTOT',
                    [CURVATTOT]       DECIMAL(17, 2) '@CURVATTOT',
                    [CURFEETOT]       DECIMAL(17, 2) '@CURFEETOT',
                    [RECNO]           INT            '@RECNO',
                    [SINGLELINE]      CHAR(1)        '@SINGLELINE',
                    [TEMPLATE]        CHAR(10)       '@TEMPLATE',
                    [CHEQUEREQNO]     INT            '@CHEQUEREQNO',
                    [WRITEDOWN]       DATETIME       '@WRITEDOWN',
                    [WRITEBACKHOURS]  DECIMAL(7, 2)  '@WRITEBACKHOURS',
                    [WRITEBACKVALUE]  DECIMAL(13, 2) '@WRITEBACKVALUE',
                    [CORRECTCOPY]     CHAR(1)        '@CORRECTCOPY',
                    [CreditInvoiceNo] INT            '@CreditInvoiceNo',
                    [DraftBillNo]     INT            '@DraftBillNo',
                    [EFTSent]         CHAR(1)        '@EFTSent',
                    [EFTDate]         DATETIME       '@EFTDate',
                    [EFTFileNumber]   INT            '@EFTFileNumber',
                    [EFTFileName]     VARCHAR(500)   '@EFTFileName',
                    [EFTYorN]         CHAR(1)        '@EFTYorN',
                    [ClientCode]      VARCHAR(10)    '@ClientCode',
                    [PayClient]       CHAR(1)        '@PayClient',
                    [OnceOffPayment]  CHAR(1)        '@OnceOffPayment',
                    [CaseAssCode]     VARCHAR(6)     '@CaseAssCode',
                    [EFTEmailYorN]    CHAR(1)        '@EFTEmailYorN',
                    [HandlerCode]     VARCHAR(10)    '@HandlerCode',
                    [PaymentMethod]   INT            '@PaymentMethod',
                    [ClearedDate]     DATETIME       '@ClearedDate') AS [XML]

            BEGIN TRY
            EXEC sp_xml_removedocument @iSL
            END TRY
            BEGIN CATCH
            END CATCH

            /*
                Prepare dates by handling timezones
                Remove time component for backwards compatibility
                with Clarion apps
            */

            SET @DATE        = DATEADD(DAY, DATEDIFF(DAY, 0, @DATE       ), 0)
            SET @ENTRYDATE   = DATEADD(DAY, DATEDIFF(DAY, 0, @ENTRYDATE  ), 0)
            SET @WRITEDOWN   = DATEADD(DAY, DATEDIFF(DAY, 0, @WRITEDOWN  ), 0)
            SET @EFTDate     = DATEADD(DAY, DATEDIFF(DAY, 0, @EFTDate    ), 0)
            SET @ClearedDate = DATEADD(DAY, DATEDIFF(DAY, 0, @ClearedDate), 0)

            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchH] AS [BAH]
                        WHERE [BAH].[BATCHNO] = @BATCHNO)
            BEGIN
                UPDATE [BAH]
                   SET [BAH].[POSTFWD]          = @POSTFWD,
                       [BAH].[TYPE]             = @TYPE,
                       [BAH].[CODE]             = @CODE,
                       [BAH].[BRANCH]           = @BRANCH,
                       [BAH].[PREF]             = @PREF,
                       [BAH].[REF]              = @REF,
                       [BAH].[DATE]             = @DATE,
                       [BAH].[FEE]              = @FEE,
                       [BAH].[MATTER]           = @MATTER,
                       [BAH].[SUPP]             = @SUPP,
                       [BAH].[NARR]             = @NARR,
                       [BAH].[VALUE]            = @VALUE,
                       [BAH].[SUBTOT]           = @SUBTOT,
                       [BAH].[POSTED]           = @POSTED,
                       [BAH].[CLIENTAC]         = @CLIENTAC,
                       [BAH].[PERNO]            = @PERNO,
                       [BAH].[YEAR]             = @YEAR,
                       [BAH].[PAYEE]            = @PAYEE,
                       [BAH].[OUTLAYTOT]        = @OUTLAYTOT,
                       [BAH].[VATTOT]           = @VATTOT,
                       [BAH].[FEETOT]           = @FEETOT,
                       [BAH].[INVCR]            = @INVCR,
                       [BAH].[THIRDPARTY]       = @THIRDPARTY,
                       [BAH].[USERCODE]         = @USERCODE,
                       [BAH].[CLIENTBANK]       = @CLIENTBANK,
                       [BAH].[CURRENCY]         = @CURRENCY,
                       [BAH].[CURRENCYVALUE]    = ISNULL(@CURRENCYVALUE, CONVERT(DECIMAL(19, 2), 
														CASE 
															WHEN @TYPE =  'T' 
															THEN (CASE WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'I'
																	   THEN @VALUE / 0.787564
																	   WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'E'
																	   THEN @VALUE * 0.787564
																       ELSE 0 END)
														    WHEN @TYPE =  'B' 
															THEN (CASE WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'I'
																	   THEN @SUBTOT / 0.787564
																	   WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'E'
																	   THEN @SUBTOT * 0.787564
																       ELSE 0 END)
															ELSE (@VALUE * @IECONVERT) END)),
                       [BAH].[CUROUTLAYTOT]     = ISNULL(@CUROUTLAYTOT,  CONVERT(DECIMAL(19, 2), @OUTLAYTOT * @IECONVERT)),
                       [BAH].[CURVATTOT]        = ISNULL(@CURVATTOT,     CONVERT(DECIMAL(19, 2), @VATTOT    * @IECONVERT)),
                       [BAH].[CURFEETOT]        = ISNULL(@CURFEETOT,     CONVERT(DECIMAL(19, 2), @FEETOT    * @IECONVERT)),
                       [BAH].[RECNO]            = @RECNO,
                       [BAH].[SINGLELINE]       = @SINGLELINE,
                       [BAH].[TEMPLATE]         = @TEMPLATE,
                       [BAH].[CHEQUEREQNO]      = @CHEQUEREQNO,
                       [BAH].[WRITEDOWN]        = @WRITEDOWN,
                       [BAH].[WRITEBACKHOURS]   = @WRITEBACKHOURS,
                       [BAH].[WRITEBACKVALUE]   = @WRITEBACKVALUE,
                       [BAH].[CORRECTCOPY]      = @CORRECTCOPY,
                       [BAH].[CreditInvoiceNo]  = @CreditInvoiceNo,
                       [BAH].[DraftBillNo]      = @DraftBillNo,
                       [BAH].[EFTSent]          = @EFTSent,
                       [BAH].[EFTDate]          = @EFTDate,
                       [BAH].[EFTFileNumber]    = @EFTFileNumber,
                       [BAH].[EFTFileName]      = @EFTFileName,
                       [BAH].[EFTYorN]          = @EFTYorN,
                       [BAH].[ClientCode]       = @ClientCode,
                       [BAH].[PayClient]        = @PayClient,
                       [BAH].[OnceOffPayment]   = @OnceOffPayment,
                       [BAH].[CaseAssCode]      = @CaseAssCode,
                       [BAH].[EFTEmailYorN]     = @EFTEmailYorN,
                       [BAH].[HandlerCode]      = @HandlerCode,
                       [BAH].[PaymentMethod]    = @PaymentMethod,
                       [BAH].[ClearedDate]      = @ClearedDate
                  FROM [dbo].[BatchH] AS [BAH]
                 WHERE [BAH].[BATCHNO] = @BATCHNO
            END
            ELSE
            BEGIN
                INSERT INTO [dbo].[BatchH] (
                       [BATCHNO],
                       [POSTFWD],
                       [TYPE],
                       [CODE],
                       [BRANCH],
                       [PREF],
                       [REF],
                       [DATE],
                       [FEE],
                       [MATTER],
                       [SUPP],
                       [NARR],
                       [VALUE],
                       [SUBTOT],
                       [POSTED],
                       [CLIENTAC],
                       [PERNO],
                       [YEAR],
                       [PAYEE],
                       [OUTLAYTOT],
                       [VATTOT],
                       [FEETOT],
                       [INVCR],
                       [THIRDPARTY],
                       [USERCODE],
                       [ENTRYDATE],
                       [CLIENTBANK],
                       [CURRENCY],
                       [CURRENCYVALUE],
                       [CUROUTLAYTOT],
                       [CURVATTOT],
                       [CURFEETOT],
                       [RECNO],
                       [SINGLELINE],
                       [TEMPLATE],
                       [CHEQUEREQNO],
                       [WRITEDOWN],
                       [WRITEBACKHOURS],
                       [WRITEBACKVALUE],
                       [CORRECTCOPY],
                       [CreditInvoiceNo],
                       [DraftBillNo],
                       [EFTSent],
                       [EFTDate],
                       [EFTFileNumber],
                       [EFTFileName],
                       [EFTYorN],
                       [ClientCode],
                       [PayClient],
                       [OnceOffPayment],
                       [CaseAssCode],
                       [EFTEmailYorN],
                       [HandlerCode],
                       [PaymentMethod],
                       [ClearedDate])
                SELECT @BATCHNO,
                       @POSTFWD,
                       @TYPE,
                       @CODE,
                       @BRANCH,
                       @PREF,
                       @REF,
                       @DATE,
                       @FEE,
                       @MATTER,
                       @SUPP,
                       @NARR,
                       @VALUE,
                       @SUBTOT,
                       @POSTED,
                       @CLIENTAC,
                       @PERNO,
                       @YEAR,
                       @PAYEE,
                       @OUTLAYTOT,
                       @VATTOT,
                       @FEETOT,
                       @INVCR,
                       @THIRDPARTY,
                       @USERCODE,
                       @ENTRYDATE,
                       @CLIENTBANK,
                       @CURRENCY,
                       ISNULL(@CURRENCYVALUE, CONVERT(DECIMAL(19, 2), 
						CASE 
						WHEN @TYPE =  'T' 
						THEN (CASE WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'I'
								   THEN @VALUE / 0.787564
								   WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'E'
								   THEN @VALUE * 0.787564
								   ELSE 0 END)
						WHEN @TYPE =  'B' 
						THEN (CASE WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'I'
								   THEN @SUBTOT / 0.787564
								   WHEN @CURRENCY = @BASECURRENCY AND @CURRENCY = 'E'
								   THEN @SUBTOT * 0.787564
									ELSE 0 END)
						ELSE (@VALUE * @IECONVERT) END)),
                       ISNULL(@CUROUTLAYTOT,  CONVERT(DECIMAL(19, 2), @OUTLAYTOT * @IECONVERT)),
                       ISNULL(@CURVATTOT,     CONVERT(DECIMAL(19, 2), @VATTOT   * @IECONVERT)),
                       ISNULL(@CURFEETOT,     CONVERT(DECIMAL(19, 2), @FEETOT    * @IECONVERT)),
                       @RECNO,
                       @SINGLELINE,
                       @TEMPLATE,
                       @CHEQUEREQNO,
                       @WRITEDOWN,
                       @WRITEBACKHOURS,
                       @WRITEBACKVALUE,
                       @CORRECTCOPY,
                       @CreditInvoiceNo,
                       @DraftBillNo,
                       @EFTSent,
                       @EFTDate,
                       @EFTFileNumber,
                       @EFTFileName,
                       @EFTYorN,
                       @ClientCode,
                       @PayClient,
                       @OnceOffPayment,
                       @CaseAssCode,
                       @EFTEmailYorN,
                       @HandlerCode,
                       @PaymentMethod,
                       @ClearedDate
            END

        COMMIT TRAN
    END TRY

    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION;
        END 
    END CATCH

    SET NOCOUNT OFF
END
GO

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

CREATE PROCEDURE
       [dbo].[KAAS_CreateCostTransferBatch]
      (@XML            NVARCHAR(MAX),
       @REF            VARCHAR(10),
       @Handler        VARCHAR(10),
	   @DataCount	   VARCHAR(MAX))
AS
/*************************************************************************************************************
 *                                                                                                           *
 * KAAS_CreateCostTransferBatch																				 *
 * Create Cost Transfer Batch     
 * Copied from ky_NETSPCCreateCostTransferBatch																 *
 * @XML:                                                                                                     *
 * <MATTERS>                                                                                                 *
 *   <MATTER CODE='xxxxxx/nnnn' BRANCH="A" VALUE="2910.30" BATCHNO="3315" PREF="1234" WRITEOFF="N" />        *
 *   <MATTER CODE='yyyyyy/mmmm' BRANCH="B" VALUE="5576.38" BATCHNO="3220" PREF="1235" WRITEOFF="Y" />        *
 *   <!-- etc ... -->                                                                                        *
 * </MATTERS>                                                                                                *
 * @Handler:       currently logged in handler                                                               *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * Original:                                -                                                        *   *
 *   * First compatible version:                5.8.1.19                                                 *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History:                                                                                     *
 * 2024-03-01   Ghayathri S.V     Created																     *
 * 2024-03-20   Ghayathri S.V     Modified to fetch multiple batch numbers									 *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

DECLARE @MATTERS TABLE
       ([Code]             VARCHAR(20)                   NOT NULL,
        [id]               INT         IDENTITY(1, 1)    NOT NULL    PRIMARY KEY,
        [BRANCH]           CHAR(3)                       NOT NULL,
        [BATCHNO]          INT                           NOT NULL,
        [PREF]             INT                           NOT NULL,
        [VALUE]            DECIMAL(17, 2)                NOT NULL,
        [WRITEOFF]         CHAR(1)                       NOT NULL,
        UNIQUE NONCLUSTERED
              ([BRANCH], [id]))

DECLARE @BRANCHTOTALS TABLE
       ([BRANCH]           CHAR(3)                       NOT NULL   PRIMARY KEY,
        [VALUE]            DECIMAL(17, 2)                NOT NULL,
        [CURRENCYVALUE]    DECIMAL(17, 2)                NOT NULL)

DECLARE @LOGON    VARCHAR(8)

--Try and get the [LOGON] from the [dbo].[Handlers] table. If nothing is found, use the [CODE] instead but only if it's
--8 characters or less. If that fails, revert back to the ADM [LOGON]
--START
SET @Handler = ISNULL(@Handler, 'ADM')
IF NOT EXISTS
  (SELECT TOP 1 1
     FROM [dbo].[Handlers] [HAN]
    WHERE [HAN].[CODE] = @Handler)
  BEGIN
    SET @Handler = 'ADM'
  END

SELECT @LOGON = CASE WHEN RTRIM(ISNULL([HAN].[LOGON], '')) <> ''
                          THEN RTRIM([HAN].[LOGON])
                     WHEN LEN(@Handler) > 8
                          THEN ISNULL((SELECT [HAM].[LOGON] FROM [dbo].[Handlers] [HAM] WHERE [HAM].[CODE] = 'ADM'), '')
                     WHEN @Handler = ''
                          THEN ISNULL((SELECT [HAM].[LOGON] FROM [dbo].[Handlers] [HAM] WHERE [HAM].[CODE] = 'ADM'), '')
                     ELSE RTRIM(CONVERT(VARCHAR(8), @Handler)) END
  FROM [dbo].[Handlers] [HAN]
 WHERE [HAN].[CODE] = @Handler
--END

DECLARE @iSL INT

EXEC sp_xml_preparedocument @iSL OUTPUT, @XML

INSERT
  INTO @MATTERS
      ([Code],
       [BRANCH],
       [BATCHNO],
       [PREF],
       [VALUE],
       [WRITEOFF])
SELECT [CODE],
       [BRANCH],
       ISNULL([BATCHNO], 0),
       ISNULL([PREF], 0),
       [VALUE],
       [WRITEOFF]
  FROM OPENXML(@iSL, N'MATTERS/MATTER')
  WITH ([CODE]      VARCHAR(20)     '@CODE',
        [BRANCH]    CHAR(3)         '@BRANCH',
        [BATCHNO]   INT             '@BATCHNO',
        [PREF]      INT             '@PREF',
        [VALUE]     DECIMAL(17, 2)  '@VALUE',
        [WRITEOFF]  CHAR(1)         '@WRITEOFF')

EXEC sp_xml_removedocument @iSL

IF NOT EXISTS
  (SELECT TOP 1 1
     FROM @MATTERS)
  BEGIN
    --Nothing to do here
    SET NOCOUNT OFF
    RETURN
  END

DECLARE @BATCHNO    INT
DECLARE @PREF       INT

DECLARE @TYPE       CHAR(1)
DECLARE @YEAR       INT
DECLARE @CURPER     INT
DECLARE @OUTLAY     VARCHAR(10)
DECLARE @VATE       CHAR(1)
DECLARE @OFFICEAC   CHAR(10)
DECLARE @CLIENTAC   CHAR(10)
DECLARE @DEBTRSAC   CHAR(10)
DECLARE @IECONVERT  FLOAT

SET @TYPE = 'R'

SELECT @YEAR      = [CTL].[YEAR],
       @CURPER    = [CTL].[CURPER],
       @OUTLAY    = [CTL].[OUTLAY],
       @VATE      = [CTL].[VATEXCLUDE],
       @OFFICEAC  = [CTL].[DEFAULTOFFICEAC],
       @CLIENTAC  = [CTL].[DEFAULTCLIENTAC],
       @DEBTRSAC  = [CTL].[DEBTORS],
       @IECONVERT = CONVERT(FLOAT, [CTL].[IECONVERT])
  FROM [dbo].[control] [CTL]

-- Use new function to get next value
SELECT @BATCHNO = [LAST].[BATCHNO],
       @PREF    = [LAST].[PREF]
  FROM [dbo].[ky_NETTFGetLastBatchNoAndPostRef]() AS [LAST]

-- Sum the Currency Converted Values to get the total value in BATCHH,
-- rather than converting the total afterwards. In the test data there was
-- a 1p difference between the two if you sum first and then convert,
-- and doing it this way gave the same result.
  INSERT
    INTO @BRANCHTOTALS
        ([BRANCH],
         [VALUE],
         [CURRENCYVALUE])
  SELECT [MTR].[BRANCH],
         SUM([MTR].[VALUE])                            AS [VALUE],
         SUM(CONVERT(DECIMAL(17, 2),
                     ROUND(  CONVERT(FLOAT,
                                     [MTR].[VALUE])
                           * CONVERT(FLOAT,
                                     @IECONVERT),
                           2)))                        AS [CURRENCYVALUE]
    FROM @MATTERS [MTR]
GROUP BY [MTR].[BRANCH]

DECLARE @CurrentBranch CHAR(3)

SELECT TOP 1 
       @CurrentBranch = [BT].[BRANCH]
  FROM @BRANCHTOTALS [BT]

WHILE @CurrentBranch IS NOT NULL
  BEGIN
    /* Get the next Batch Number and PREF */
    SET @BATCHNO = @BATCHNO + 1
    SET @PREF    = @PREF + 1
  
    /* We need to create a separate BatchH row for each Branch so the first thing
       we'll do is get the first available branch in the summary, and create that BatchH */
    INSERT
      INTO [dbo].[BatchH]
          ([BATCHNO],
           [POSTFWD],
           [TYPE],
           [CODE],
           [BRANCH],
           [PREF],
           [REF],
           [DATE],
           [FEE],
           [MATTER],
           [SUPP],
           [NARR],
           [VALUE],
           [SUBTOT],
           [POSTED],
           [CLIENTAC],
           [PERNO],
           [YEAR],
           [PAYEE],
           [OUTLAYTOT],
           [VATTOT],
           [FEETOT],
           [INVCR],
           [THIRDPARTY],
           [USERCODE],
           [ENTRYDATE],
           [CLIENTBANK],
           [CURRENCY],
           [CURRENCYVALUE],
           [CUROUTLAYTOT],
           [CURVATTOT],
           [CURFEETOT],
           [RECNO],
           [SINGLELINE],
           [TEMPLATE],
           [CHEQUEREQNO],
           [WRITEBACKHOURS],
           [WRITEBACKVALUE],
           [CORRECTCOPY],
           [CreditInvoiceNo],
           [DraftBillNo],
           [EFTSent],
           [EFTFileNumber],
           [EFTFileName],
           [EFTYorN],
           [ClientCode],
           [PayClient],
           [OnceOffPayment],
           [CaseAssCode],
           [EFTEmailYorN],
           [HandlerCode])
    SELECT @BATCHNO                                                   AS [BATCHNO],
           CONVERT(CHAR(1), '')                                       AS [POSTFWD],
           @TYPE                                                      AS [TYPE],
           @OFFICEAC                                                  AS [CODE],
           @CurrentBranch                                             AS [BRANCH],
           @PREF                                                      AS [PREF],
           CONVERT(CHAR(10), @REF)                                    AS [REF],
           CONVERT(DATETIME,
                   CONVERT(VARCHAR,
                            GETDATE(),
                            112),
                   112)                                               AS [DATE],
           ''                                                         AS [FEE],
           ''                                                         AS [MATTER],
           CONVERT(CHAR(10), '')                                      AS [SUPP],
           CONVERT(CHAR(150), 'Transfers for Costs (Auto)')           AS [NARR],
           [BT].[VALUE]                                               AS [VALUE],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [SUBTOT],
           CONVERT(CHAR(1), 'N')                                      AS [POSTED],
           CONVERT(CHAR(1), '')                                       AS [CLIENTAC],
           @CURPER                                                    AS [PERNO],
           @YEAR                                                      AS [YEAR],
           CONVERT(CHAR(60), '')                                      AS [PAYEE],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [OUTLAYTOT],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [VATTOT],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [FEETOT],
           CONVERT(CHAR(1), '')                                       AS [INVCR],
           CONVERT(CHAR(1), 'Y')                                      AS [THIRDPARTY],
           @LOGON                                                     AS [USERCODE],
           CONVERT(DATETIME,
                   CONVERT(VARCHAR,
                            GETDATE(),
                            112),
                   112)                                               AS [ENTRYDATE],
           @CLIENTAC                                                  AS [CLIENTBANK],
           CONVERT(CHAR(1), 'E')                                      AS [CURRENCY],
           [BT].[CURRENCYVALUE]                                       AS [CURRENCYVALUE],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [CUROUTLAYTOT],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [CURVATTOT],
           CONVERT(DECIMAL(17, 2), 0)                                 AS [CURFEETOT],
           0                                                          AS [RECNO],
           CONVERT(CHAR(1), '')                                       AS [SINGLELINE],
           CONVERT(CHAR(10), '')                                      AS [TEMPLATE],
           0                                                          AS [CHEQUEREQNO],
           CONVERT(DECIMAL(7, 2), 0)                                  AS [WRITEBACKHOURS],
           CONVERT(DECIMAL(13, 2), 0)                                 AS [WRITEBACKVALUE],
           CONVERT(CHAR(1), '')                                       AS [CORRECTCOPY],
           0                                                          AS [CreditInvoiceNo],
           0                                                          AS [DraftBillNo],
           CONVERT(CHAR(1), 'N')                                      AS [EFTSent],
           0                                                          AS [EFTFileNumber],
           ''                                                         AS [EFTFileName],
           CONVERT(CHAR(1), 'N')                                      AS [EFTYorN],
           ''                                                         AS [ClientCode],
           CONVERT(CHAR(1), 'N')                                      AS [PayClient],
           CONVERT(CHAR(1), 'N')                                      AS [OnceOffPayment],
           ''                                                         AS [CaseAssCode],
           CONVERT(CHAR(1), 'N')                                      AS [EFTEmailYorN],
           @Handler                                                   AS [HandlerCode]
      FROM @BRANCHTOTALS [BT]
     WHERE [BT].[BRANCH] = @CurrentBranch

    DECLARE @CurrentBDID          INT
    DECLARE @CurrentBDMatter      VARCHAR(20)
    DECLARE @CurrentBDValue       DECIMAL(17, 2)
    DECLARE @CurrentBDAllocBatch  INT
    DECLARE @CurrentBDAllocREF    CHAR(10)
    DECLARE @CurrentBDAllocPREF   INT
    DECLARE @CurrentBDAllocValue  DECIMAL(17, 2)
    DECLARE @CurrentBDWriteOff    CHAR(1)

    /* Get the first Batch Detail data for this Branch */
    SELECT TOP 1
           @CurrentBDID         = [MTS].[id],
           @CurrentBDMatter     = [MTS].[Code],
           @CurrentBDValue      = [MTS].[VALUE],
           @CurrentBDAllocBatch = [MTS].[BATCHNO],
           @CurrentBDAllocREF   = [DTL].[REF],
           @CurrentBDAllocPREF  = [DTL].[PREF],
           @CurrentBDAllocValue = [DTL].[OSVALUE],
           @CurrentBDWriteOff   = [MTS].[WRITEOFF]
      FROM @MATTERS [MTS]
           INNER JOIN [dbo].[DebtorsLedger] AS [DTL]
                   ON [DTL].[BATCHNO] = [MTS].[BATCHNO]
                  AND [DTL].[PREF] = [MTS].[PREF]
     WHERE [MTS].[BRANCH] = @CurrentBranch

    WHILE @CurrentBDMatter IS NOT NULL
      BEGIN
        /* Get the next PREF */
        SET @PREF   = @PREF + 1

        /* Insert the Batch Detail */
        INSERT
          INTO [dbo].[BatchDetails]
              ([BATCHNO],
               [TYPE],
               [CODE],
               [PREF],
               [REF],
               [DATE],
               [FEE],
               [BRANCH],
               [NARR],
               [MATTER],
               [SUPP],
               [VALUE],
               [VATCODE],
               [VATVAL],
               [CLIENTYN],
               [OUTLAY],
               [PENDING],
               [YEAR],
               [PERNO],
               [ENTRYCURRENCY],
               [CURRENCYVALUE],
               [CURRENCYVAT],
               [OUTLAYCODE],
               [THIRDPARTY],
               [PAYEE],
               [HEADPREF],
               [HEADBATCH],
               [ALLOCBATCH],
               [ALLOCPREF],
               [ALLOCREF],
               [ALLOCVALUE],
               [ALLOCWRITEOFF],
               [PSUPP],
               [UNDETAKING],
               [CASEASSCODE],
               [OnceOffPayment],
               [PayClient],
               [ClientCode],
               [EFTEmailYorN],
               [RegisteredPost],
               [PreBilledOutlay])
        SELECT @BATCHNO                                                   AS [BATCHNO],
               @TYPE                                                      AS [TYPE],
               @DEBTRSAC                                                  AS [CODE],
               @PREF                                                      AS [PREF],
               CONVERT(CHAR(10), @REF)                                    AS [REF],
               CONVERT(DATETIME,
                       CONVERT(VARCHAR,
                               GETDATE(),
                               112),
                       112)                                               AS [DATE],
               ''                                                         AS [FEE],
               @CurrentBranch                                             AS [BRANCH],
               'Transfer for Costs (Auto)'                                AS [NARR],
               @CurrentBDMatter                                           AS [MATTER],
               CONVERT(CHAR(10), '')                                      AS [SUPP],
               @CurrentBDValue                                            AS [VALUE],
               CONVERT(CHAR(1), '')                                       AS [VATCODE],
               CONVERT(DECIMAL(17, 2), 0)                                 AS [VATVAL],
               CONVERT(CHAR(1), '')                                       AS [CLIENTYN],
               CONVERT(CHAR(1), 'D')                                      AS [OUTLAY],
               CONVERT(CHAR(1), '')                                       AS [PENDING],
               @YEAR                                                      AS [YEAR],
               @CURPER                                                    AS [PERNO],
               CONVERT(CHAR(1), 'E')                                      AS [ENTRYCURRENCY],
               CONVERT(DECIMAL(17, 2),
                       ROUND(  CONVERT(FLOAT,
                                       @CurrentBDValue)
                             * CONVERT(FLOAT,
                                       @IECONVERT),
                             2))                                          AS [CURRENCYVALUE],
               CONVERT(DECIMAL(17, 2), 0)                                 AS [CURRENCYVAT],
               CONVERT(CHAR(4), '')                                       AS [OUTLAYCODE],
               CONVERT(CHAR(1), '')                                       AS [THIRDPARTY],
               CONVERT(CHAR(60), '')                                      AS [PAYEE],
               0                                                          AS [HEADPREF],
               0                                                          AS [HEADBATCH],
               @CurrentBDAllocBatch                                       AS [ALLOCBATCH],
               @CurrentBDAllocPREF                                        AS [ALLOCPREF],
               @CurrentBDAllocREF                                         AS [ALLOCREF],
               @CurrentBDAllocValue                                       AS [ALLOCVALUE],
               CASE WHEN @CurrentBDWriteOff = 'Y'
                         THEN CONVERT(CHAR(1), 'Y')
                    ELSE CONVERT(CHAR(1), '') END                         AS [ALLOCWRITEOFF],
               CONVERT(CHAR(10), '')                                      AS [PSUPP],
               CONVERT(SMALLINT, 0)                                       AS [UNDETAKING],
               ''                                                         AS [CASEASSCODE],
               CONVERT(CHAR(1), 'N')                                      AS [OnceOffPayment],
               CONVERT(CHAR(1), 'N')                                      AS [PayClient],
               ''                                                         AS [ClientCode],
               CONVERT(CHAR(1), 'N')                                      AS [EFTEmailYorN],
               0                                                          AS [RegisteredPost],
               CONVERT(BIT, 0)                                            AS [PreBilledOutlay]

        /* Remove the matter we've just inserted so that .... */
        DELETE @MATTERS WHERE [id] = @CurrentBDID

        SET @CurrentBDMatter = NULL
        /* .... when we read the first Batch Detail for this Branch again it'll actually be the next available one. Or none.  */
        SELECT TOP 1
               @CurrentBDID         = [MTS].[id],
               @CurrentBDMatter     = [MTS].[Code],
               @CurrentBDValue      = [MTS].[VALUE],
               @CurrentBDAllocBatch = [MTS].[BATCHNO],
               @CurrentBDAllocREF   = [DTL].[REF],
               @CurrentBDAllocPREF  = [DTL].[PREF],
               @CurrentBDAllocValue = [DTL].[OSVALUE],
               @CurrentBDWriteOff   = [MTS].[WRITEOFF]
          FROM @MATTERS [MTS]
               INNER JOIN [dbo].[DebtorsLedger] AS [DTL]
                       ON [DTL].[BATCHNO] = [MTS].[BATCHNO]
                      AND [DTL].[PREF] = [MTS].[PREF]
         WHERE [MTS].[BRANCH] = @CurrentBranch
      END

    /* Remove the Branch for which we've just inserted the BatchH and BatchDetails so that .... */
    DELETE [BT]
      FROM @BRANCHTOTALS [BT]
     WHERE [BT].[BRANCH] = @CurrentBranch

    SET @CurrentBranch = NULL

    /* .... when we read the first branch again it'll actually be the next one. Or none. */
    SELECT TOP 1
           @CurrentBranch = [BT].[BRANCH]
      FROM @BRANCHTOTALS [BT]
  END

UPDATE [dbo].[control]
   SET [LASTBATCH] = @BATCHNO,
       [LASTPREF]  = @PREF

PRINT @BATCHNO

DECLARE @Today DATETIME
SET @Today = CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),112),112)

SELECT TOP (CAST (@DataCount AS INT)) [BATCHNO] AS [BatchNo] FROM [dbo].[BatchH] 
WHERE [BATCHNO] <= @BATCHNO AND [REF] = @REF 
AND [DATE] = @Today
ORDER BY BATCHNO DESC

SET NOCOUNT OFF

END

GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateEditSAMCreditorList' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateEditSAMCreditorList] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateEditSAMCreditorList]
	(
		@Date	    DATE	      = NULL,
		@PayValue   DECIMAL(18,2) = 0,
		@RecordID	INT			  = 0,
		@Mode	    VARCHAR(10)   = ''
	)
AS
/*******************************************************************************************************
* Create Creditors List for Supplier Ledger                                                            * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateEditSAMCreditorList]        					           *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-12    Balamurugan C        Created                                                           *
* 2022-02-28    Balamurugan.C        Modified - Handled TCL Statements                                 *
*******************************************************************************************************/
BEGIN
   BEGIN TRY
     BEGIN TRAN
	IF(@Mode='Create')
		BEGIN
			DELETE 
			  FROM [dbo].[CreditorsList]

			INSERT 
			 INTO [dbo].[CreditorsList]
			   (  [SupplyCode],
				  [BatchNo],
				  [Pref],
				  [Ref],
				  [Date],
				  [OrigValue],
				  [OsValue],
				  [PayValue]
				)
		   SELECT [TSL].[Supp],
				  [TSL].[BatchNo],
				  [TSL].[Pref],
				  [TSL].[Ref],
				  [TSL].[Date],
				  [TSL].[Original],
				  [TSL].[OsValue],
				  0.00 AS [PayValue] 
			 FROM (
		   SELECT [Supp]
				 ,[BatchNo]
				 ,[Pref]
				 ,[Ref]
				 ,[Date]
				 ,[Original]
				 ,[OsValue] + ISnull((SELECT SUM([BTD].[AllocValue])
		    FROM [dbo].[BatchH] [BTH]
                 INNER JOIN [dbo].[BatchDetails] [BTD]  
				         ON [BTH].[BatchNo] = [BTD].[BatchNo]
	       WHERE [BTH].[Posted] = 'N' AND [SPL].[BatchNo] = [BTD].[AllocBatch] ),0) AS  [OsValue]		
		    FROM [dbo].[SupplierLedger] AS [SPL]
		   WHERE [SPL].[OsValue] < 0
			 AND [SPL].[BatchNo] <> 0
				 )[TSL]
		   WHERE [OsValue] < 0
			 AND CAST([Date] AS DATE) <= CAST(@Date AS DATE)
		ORDER BY [Supp] ASC
		END
	ELSE
		BEGIN
	      UPDATE [dbo].[CreditorsList]
		     SET [PayValue] = @PayValue
		   WHERE [RecordID] = @RecordID
		END
         COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END 
	 END CATCH
END
GO

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

CREATE PROCEDURE
       [dbo].[KAAS_CreateEFT]
      (
		@NextFileNumber			INT,
		@Bank					VARCHAR(50),
		@PaymentDate			DATETIME,
		@Narrative				VARCHAR(100),
		@TotalAmount			VARCHAR(100),
		@HandlerName			VARCHAR(100),
		@BatchNumber			VARCHAR(100),
		@Type					CHAR(1)
	  )
AS
/*************************************************************************************************************                                                *
 * Modification History                                                                                      *
 * 2024-03-05   Ghayathri S.V     Created																     *
 * 2024-03-25   Ghayathri S.V     Modified - Updated the logic to update batch details based on batch Type 	 *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

			DECLARE	@AccountName	VARCHAR(50),
					@SortCode		VARCHAR(10),
					@AccountNumber	VARCHAR(10),
					@Iban			VARCHAR(34),
					@Bic			VARCHAR(20),
					@OrgNumber		VARCHAR(34)

			SELECT	@AccountName	= NOM.ACCOUNTNAME,
					@SortCode		= NOM.SORTCODE,
					@AccountNumber	= NOM.ACCOUNTNO,
					@Iban			= NOM.IBAN,
					@Bic			= NOM.BIC,
					@OrgNumber		= NOM.OrgIDNumber
			FROM	dbo.[Nominal] NOM
			WHERE	NOM.CODE = @Bank

			DECLARE  @Today DATETIME
			SET		 @Today =  CONVERT(DATETIME,CONVERT(VARCHAR,GETDATE(),102),102)

			DECLARE  @EFTNo  INT
			SET		 @EFTNo = @NextFileNumber

			DECLARE  @EFTTotal  VARCHAR(100)
			SET		 @EFTTotal = @TotalAmount

			DECLARE  @CurrBatchNo VARCHAR(10)
			DECLARE	 @CurrPref	 VARCHAR(20) 
			DECLARE  @NewBatchNo VARCHAR(10)
			DECLARE	 @NewPref	 VARCHAR(20)
			DECLARE  @CurrYear	INT
			DECLARE  @CurrPer	INT

--1) UPDATE THE EFT DETAILS TABLE WITH THE LATEST FILE NUMBER
			BEGIN
				UPDATE		dbo.[EFTDetails]
				SET			FileNumber = @NextFileNumber 
				WHERE		RecordID = 1
			END

--2) INSERT THE REQUIRED DATA INTO THE EFT LOG TABLE
			BEGIN
				INSERT INTO		dbo.[EFTLog]
								(
									[Bank],
									[CreatedDate],
									[PaymentDate],
									[FileName],
									[Amount],
									[SeqNumber],
									[Logon]
								)
				VALUES			( 
									@Bank,
									@Today,
									@PaymentDate,
									'Downloads',
									@TotalAmount,
									@NextFileNumber,
									@HandlerName
								)
				END

--3) FETCH AND UPDATE THE LASTBATCH AND LASTPREF FROM CONTROL TABLE
			BEGIN
				SELECT @CurrBatchNo = LASTBATCH, @CurrPref = LASTPREF FROM dbo.[control]

				SET		@NewBatchNo = @CurrBatchNo + 1
				SET		@NewPref = @CurrPref + 1

				UPDATE  dbo.[control] 
				SET     LASTBATCH = @NewBatchNo, 
						LASTPREF = @NewPref
		    END

--4) UPDATE THE BATCH HEADER WITH NEW REF,EFT DETAILS AND BATCH DETAILS OF HEADBATCH WITH NEW BATCH NUMBER
			BEGIN
				IF  EXISTS (SELECT TOP 1 1 FROM  dbo.[BatchH] 
							WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ',')))
				BEGIN
					UPDATE  dbo.[BatchH]
					SET		EFTFileNumber = @EFTNo,
							EFTDate = @Today,
							EFTSent = 'Y',
							REF  = 'EFT' + CAST(@EFTNo AS VARCHAR)
					WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ','))
				END
			END

			BEGIN
				UPDATE			dbo.[BatchDetails]
				SET				HeadBatch = @NewBatchNo
				FROM			BatchDetails
				INNER JOIN		dbo.[BatchH] ON dbo.BatchDetails.BATCHNO = dbo.BatchH.BATCHNO
				WHERE			dbo.BatchH.EFTSent = 'Y' 
				AND				dbo.BatchH.EFTDate = @Today 
				AND				dbo.BatchH.EFTFileNumber = @EFTNo
			END
							
--5) CREATE A NEW NOMINAL LEDGER RECORD WITH THE NEW BATCH NUMBER AND TOTAL EFT AMOUNT
			BEGIN
				INSERT INTO		dbo.[NominalLedger]
							(
								[CODE],
								[BRANCH],
								[BATCHNO],
								[PREF],
								[DATE],
								[REF],
								[NARR],
								[MATTER],
								[SUPP],
								[FEE],
								[VALUE],
								[CURRENCYVALUE],
								[PER],
								[YEAR],
								[ENTRYDATE],
								[RECNO],
								[ClearedDate]
							)
			VALUES			(
							    @Bank,
								'',
								@NewBatchNo,
								@NewPref,
								@Today,
								'EFT: '+ CAST(@EFTNo AS VARCHAR),
								'EFT File No: ' +CAST(@EFTNo AS VARCHAR),
								'',
								'',
								'',
								ABS(@EFTTotal) * -1,
								ABS(@EFTTotal) * -1 / 1.27,
								@CurrPer,
								@CurrYear,
								@Today,
								0,
								''
							)
			END

--6) DELETE THE OLD NOMINAL LEDGER EFT RECORD
			BEGIN
				DELETE 
				FROM			dbo.[NominalLedger] 
				WHERE			dbo.[NominalLedger].CODE = @Bank
				AND				dbo.[NominalLedger].BATCHNO 
				IN				(	SELECT  dbo.[BatchH].BATCHNO from dbo.[batchH]
									WHERE	dbo.BatchH.EFTSent = 'Y'
									AND		dbo.BatchH.EFTDate = @Today 
									AND		dbo.BatchH.EFTFileNumber = @EFTNo
								)
		   END

--7) IF THERE IS ALREADY A BANK RECON RECORD THEN DELETE THE OLDER RECORD AND INSERT A NEW RECORD WITH NEW EFT VALUES

		-- FIRST CHECK IF THERE IS A BANK RECN RECORD
			
			DECLARE		@RecordTransactionId INT
			DECLARE		@RecNo INT
			DECLARE		@OSRecNo INT
			DECLARE		@NomTranId INT

			SELECT		@RecordTransactionId = MAX(RECORDID) 
			FROM		dbo.[BankRecTransactions] BRT
			INNER JOIN	dbo.BatchH BAH 
			ON			BAH.BATCHNO = BRT.BATCH
			WHERE		BAH.EFTSent = 'Y'
			AND			BAH.EFTDate = @Today 
			AND			BAH.EFTFileNumber = @EFTNo

			IF(@RecordTransactionId > 0)
				BEGIN

					SELECT		@RecNo = RecNo, @OSRecNo = OSRecNo
					FROM		dbo.BankRecTransactions 
					WHERE		dbo.BankRecTransactions.RecordId = @RecordTransactionId

					SELECT		 @NomTranId = RecordID 
					FROM		 NominalLedger 
					WHERE		 BatchNo = @NewBatchNo 
					AND			 PRef = @NewPref 
					AND			 Code = @Bank


					DELETE 
					FROM		dbo.BankRecTransactions 
                    WHERE		dbo.BankRecTransactions.BankAc = @Bank
                    AND			dbo.BankRecTransactions.BATCH 
					IN			( SELECT	dbo.[BatchH].BATCHNO from dbo.[batchH]
								  WHERE		dbo.BatchH.EFTSent = 'Y'
								  AND		dbo.BatchH.EFTDate = @Today 
								  AND		dbo.BatchH.EFTFileNumber = @EFTNo
								)
					
					INSERT 
					INTO		dbo.[BankRecTransactions]
								(
									[BANKAC],
									[TYPE],
									[DATE],
									[REF],
									[BATCH],
									[PREF],
									[NARR],
									[VALUE],
									[OSRECNO],
									[RECNO],
									[TICKED],
									[NomTransId]
								)
					VALUES		(
									@Bank,
									'P',
									@Today,
									'EFT: ' + CAST(@EFTNo AS VARCHAR),
									@NewBatchNo,
									@NewPref,
									'EFT File No: ' + CAST(@EFTNo AS VARCHAR),
									ABS(@EFTTotal),
									@OSRecNo,
									@RecNo,
									'',
									@NomTranId
								)
				END

----8) DELETE THE RECORDS FROM EFFTTABLE
			BEGIN
				DELETE 
				FROM	dbo.[EFTTable]
			END

----9) INSERT THE NEW RECORD INTO THE EFTTABLE
			BEGIN
				CREATE 
				TABLE		#TempTable
							(
								BatchNo			INT,
								Code			VARCHAR(10),
								BatchType		CHAR(1),
								ClientBank		VARCHAR(100),
								BatchValue		DECIMAL,
								Supp			VARCHAR(10),
								PayClient		CHAR(1),
								ClientCode		VARCHAR(10),
								OnceOffPayment	CHAR(1),
								CaseAssCode		VARCHAR(10)
							)

				INSERT
				INTO		#TempTable
							(
								BatchNo,
								Code,
								BatchType,
								ClientBank,
								BatchValue,
								Supp,
								PayClient,
								ClientCode,
								OnceOffPayment,
								CaseAssCode
							)
				SELECT			BATCHNO,
								Code,
								[TYPE],
								CLIENTBANK,
								[VALUE],
								SUPP,
								PayClient,
								ClientCode,
								OnceOffPayment,
								CaseAssCode
				FROM			dbo.[BatchH] 	
				WHERE			BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ','))

	--BASED ON TYPE,CODE AND OTHER CONDITIONS INSERT THE DATA FROM THE TABLE INTO THE EFTTABLE
				DECLARE @Bcode				VARCHAR(10),
						@BType				CHAR(1),
						@BClientBank		VARCHAR(100),
						@BValue				DECIMAL,
						@BSupp				VARCHAR(10),
						@BPayClient			CHAR(1),
						@BClientCode		VARCHAR(10),
						@BOnceOffPayment	CHAR(1),
						@BCaseAssCode		VARCHAR(10)

	-- DECLARE THE CURSOR TO ITERATE THROUGH THE TEMP TABLE TO INSERT RECORDS TO EFTTABLE
				DECLARE cursor_temp CURSOR FOR
				SELECT	Code,
						BatchType,
						ClientBank,
						BatchValue,
						Supp,
						PayClient,
						ClientCode,
						OnceOffPayment,
						CaseAssCode
				FROM	#TempTable

				OPEN cursor_temp
				FETCH NEXT FROM cursor_temp 
				INTO @Bcode,@BType,@BClientBank,@BValue,@BSupp,@BPayClient,@BClientCode,@BOnceOffPayment,@BCaseAssCode

				WHILE @@FETCH_STATUS = 0
				BEGIN
					IF @BType ='R' OR @BType = 'T'
						BEGIN
							IF @BClientBank <> ''
								BEGIN
									INSERT
									INTO		dbo.[EFTTable]
												(
													[BankCode],
													[BankName],
													[BankSortCode],
													[BankAccountNum],
													[BankIBAN],
													[BankBIC],
													[BANKOIN],
													[PaymentDate],
													[Narrative],
													[SequenceNo],
													[FileName],
													[PayeeType],
													[PayeeCode],
													[PayeeName],
													[PayeeSortCode],
													[PayeeAccountNum],
													[PayeeIBAN],
													[PayeeBIC],
													[PayeeAmount],
													[NoofTransactions],
													[SumofTransactions]
												)
									SELECT		@BClientBank,
												@AccountName,
												@SortCode,
												@AccountNumber,
												@Iban,
												@Bic,
												@OrgNumber,
												@PaymentDate,
												@Narrative,
												@NextFileNumber,
												'Download',
												'T',
												@Bcode,
												NOM.ACCOUNTNAME,
												NOM.SORTCODE,
												NOM.ACCOUNTNO,
												NOM.IBAN,
												NOM.BIC,
												@BValue,
												0,
												0
									FROM		dbo.[Nominal] NOM
									WHERE		NOM.CODE = @Bcode
								END
						END
					
					ELSE
						BEGIN
							IF @BSupp <> ''
								BEGIN
									INSERT
									INTO		dbo.[EFTTable]
												(
													[BankCode],
													[BankName],
													[BankSortCode],
													[BankAccountNum],
													[BankIBAN],
													[BankBIC],
													[BANKOIN],
													[PaymentDate],
													[Narrative],
													[SequenceNo],
													[FileName],
													[PayeeType],
													[PayeeCode],
													[PayeeName],
													[PayeeSortCode],
													[PayeeAccountNum],
													[PayeeIBAN],
													[PayeeBIC],
													[PayeeAmount],
													[NoofTransactions],
													[SumofTransactions]
												)
									SELECT		@Bcode,
												@AccountName,
												@SortCode,
												@AccountNumber,
												@Iban,
												@Bic,
												@OrgNumber,
												@PaymentDate,
												@Narrative,
												@NextFileNumber,
												'Download',
												'S',
												@BSupp,
												SUPP.[NAME],
												SUPP.BankSortCode,
												SUPP.BankAccNo,
												SUPP.IBAN,
												SUPP.BIC,
												@BValue,
												0,
												0
									FROM		dbo.[Suppliers] SUPP	
									WHERE		SUPP.CODE = @BSupp
								END

							ELSE IF @BPayClient = 'Y' AND @BClientCode <> ''
								BEGIN
									INSERT
									INTO		dbo.[EFTTable]
												(
													[BankCode],
													[BankName],
													[BankSortCode],
													[BankAccountNum],
													[BankIBAN],
													[BankBIC],
													[BANKOIN],
													[PaymentDate],
													[Narrative],
													[SequenceNo],
													[FileName],
													[PayeeType],
													[PayeeCode],
													[PayeeName],
													[PayeeSortCode],
													[PayeeAccountNum],
													[PayeeIBAN],
													[PayeeBIC],
													[PayeeAmount],
													[NoofTransactions],
													[SumofTransactions]
												)
									SELECT		@Bcode,
												@AccountName,
												@SortCode,
												@AccountNumber,
												@Iban,
												@Bic,
												@OrgNumber,
												@PaymentDate,
												@Narrative,
												@NextFileNumber,
												'Download',
												'C',
												@BClientCode,
												CNT.[Name],
												CNT.BankSortCode,
												CNT.BankAccNo,
												CNT.IBAN,
												CNT.BIC,
												@BValue,
												0,
												0
									FROM		dbo.[Contacts] CNT	
									WHERE		CNT.CODE = @BClientCode
								END

							ELSE IF @BOnceOffPayment = 'Y' AND @BCaseAssCode <> ''
								BEGIN
									INSERT
									INTO		dbo.[EFTTable]
												(
													[BankCode],
													[BankName],
													[BankSortCode],
													[BankAccountNum],
													[BankIBAN],
													[BankBIC],
													[BANKOIN],
													[PaymentDate],
													[Narrative],
													[SequenceNo],
													[FileName],
													[PayeeType],
													[PayeeCode],
													[PayeeName],
													[PayeeSortCode],
													[PayeeAccountNum],
													[PayeeIBAN],
													[PayeeBIC],
													[PayeeAmount],
													[NoofTransactions],
													[SumofTransactions]
												)
									SELECT		@Bcode,
												@AccountName,
												@SortCode,
												@AccountNumber,
												@Iban,
												@Bic,
												@OrgNumber,
												@PaymentDate,
												@Narrative,
												@NextFileNumber,
												'Download',
												'A',
												@BCaseAssCode,
												CAN.[Name],
												CAN.BankSortCode,
												CAN.BankAccNo,
												CAN.IBAN,
												CAN.BIC,
												@BValue,
												0,
												0
									FROM		dbo.[CaseAssociatesNames] CAN	
									WHERE		CAN.CODE = @BCaseAssCode
								END
						END
					
					FETCH NEXT FROM cursor_temp 
					INTO @Bcode,@BType,@BClientBank,@BValue,@BSupp,@BPayClient,@BClientCode,@BOnceOffPayment,@BCaseAssCode
				END

				CLOSE cursor_temp;
				DEALLOCATE cursor_temp;

			END

	-- UPDATE THE EFTTTABLE NoofTransactions AND SumofTransactions COLUMNS
			BEGIN
				DECLARE @NoOfTransaction INT

				SELECT	@NoOfTransaction = COUNT(*) 
				FROM	dbo.[EFTTable]
				WHERE	SequenceNo = @EFTNo

				IF  EXISTS (SELECT TOP 1 1 FROM  dbo.[EFTTable] WHERE SequenceNo = @EFTNo)
					BEGIN
						UPDATE	dbo.[EFTTable]
						SET		NoofTransactions = @NoOfTransaction, 
								SumofTransactions = @TotalAmount 
						WHERE	SequenceNo = @EFTNo
					END

			END

--10) UPDATE THE REF IN ALL LEDGER TABLES AND THE CONTROL TABLE AS WELL
	
			IF  EXISTS (SELECT TOP 1 1 FROM  dbo.[MatterLedger] 
						WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ',')))
				BEGIN
					UPDATE  dbo.[MatterLedger]
					SET		REF  = 'EFT' + CAST(@EFTNo AS VARCHAR)
					WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ','))
				END

			IF  EXISTS (SELECT TOP 1 1 FROM  dbo.[NominalLedger] 
						WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ',')))
				BEGIN
					UPDATE  dbo.[NominalLedger]
					SET		REF  = 'EFT' + CAST(@EFTNo AS VARCHAR)
					WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ','))
				END

			IF  EXISTS (SELECT TOP 1 1 FROM  dbo.[SupplierLedger] 
						WHERE BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ',')))
				BEGIN
					UPDATE  dbo.[SupplierLedger]
					SET		REF  = 'EFT' + CAST(@EFTNo AS VARCHAR)
					WHERE	BATCHNO IN ( SELECT CAST(value AS INT) FROM STRING_SPLIT(@BatchNumber, ','))
				END		
	
SET NOCOUNT OFF

END
GO




IF OBJECT_ID(N'KAAS_CreateNominalAccountDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_CreateNominalAccountDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_CreateNominalAccountDetails]
		(
				@Code			VARCHAR(10)  = '',
				@Retired		VARCHAR(1)	 = '',	       
				@Description	VARCHAR(30)	 = '',
				@Type			VARCHAR(6)	 = '',
				@Pbtype			CHAR(1)		 = '', 
				@Currency		CHAR(1)		 = '',
				@Repseq			VARCHAR(4)	 = '',
				@Clientbankacct CHAR(1)		 = '',
				@Deposit		CHAR(1)		 = '',
				@DepositType	VARCHAR(4)	 = '',	
				@Allowchqreq	CHAR(1)		 = '',
				@Chqprinter		VARCHAR(40)	 = '',
				@Lastchqno		INT			 = 0,
				@Bank			VARCHAR(40)	 = '',
				@BankBranch		VARCHAR(40)	 = '',
				@Address		VARCHAR(120) ='',
				@BankType		CHAR(1)		 = '',
				@BankPhone		VARCHAR(50)	 = '',
				@AccountNo		VARCHAR(10)  = '',
				@SortCode		VARCHAR(10)  = '',
				@AccountName	VARCHAR(50)  = '',
				@Signatories	VARCHAR(255) = '',
				@DateOpened		DATETIME     = null,
				@DateClosed		DATETIME     = null,
				@Iban			VARCHAR(34)  ='',
				@Bic			VARCHAR(20)  ='',
				@OrgIdNum		VARCHAR(34)  ='',
				@Branch		    VARCHAR(40)	 = '',
				@Mode			VARCHAR(10)  =''
		) 
AS
/*******************************************************************************************************
* Save the Nominal Account Details                                                                     * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateNominalAccountDetails]   			            		   *
*                                                                                                      *
* Modification History:                                                                                *
* Balamurugan			24-May-2021					Created                                            *
* Prabhu.V   			15-Feb-2021					Script Not handled properly for Insert and Edit    *
*   									        	and here delete script not required                *
* Balamurugan.C         01-Mar-2022                 Modified - Handled TCL Statements                  *    
* Vignesh.M             01-Jun-2022                 Modified - Branch column implemented               *    
 *******************************************************************************************************/
BEGIN
  BEGIN TRY
    BEGIN TRAN
    /*CHECK THE DATA ALREADY PRESENT OR NOT*/
    IF( @Mode = 'EDIT' )
      BEGIN
          IF EXISTS 
			(
				SELECT TOP 1 1
                  FROM [dbo].[Nominal]
                 WHERE [Code] = @CODE
			)
            BEGIN
                /*IF DATA ALREADY PRESENT UPDATE PROCESS*/
                UPDATE [dbo].[Nominal]
                   SET [Desc]			= @Description,
                       [Type]			= @Type,
                       [Pb]				= @Pbtype,
                       [Retired]		= @Retired,
                       [Currency]		= @Currency,
                       [Seq]			= @Repseq,
                       [ClientAc]		= @Clientbankacct,
                       [DepositYN]		= @Deposit,
                       [DepositType]	= @DepositType,
                       [ChequeReq]		= @Allowchqreq,
                       [ChequePrinter]	= @Chqprinter,
					   [LastNo]			= @Lastchqno,
                       [Bank]			= @Bank,
                       [BankBranch]		= @BankBranch,
					   [Branch]		    = @Branch,
                       [BankAddress]	= @Address,
                       [BankType]		= @BankType,
                       [BankPhone]		= @BankPhone,
                       [AccountNo]		= @AccountNo,
                       [SortCode]		= @SortCode,
                       [AccountName]	= @AccountName,
                       [WithdrawNames]	= @Signatories,
                       [AcOpened]		= @DateOpened,
                       [AcClosed]		= @DateClosed,
                       [Iban]			= @Iban,
                       [Bic]			= @Bic,
                       [OrgIDNumber]	= @OrgIdNum
                 WHERE [Code]			= @Code
            END
          
      END
	  ELSE
            BEGIN
                /*INSERT PROCESS IF DATA NOT PRESENT*/
				IF NOT EXISTS 
					(
						SELECT TOP 1 1
						  FROM [dbo].[Nominal]
						 WHERE [Code] = @CODE
					)
					BEGIN
						INSERT 
						  INTO  [dbo].[nominal]
									(
										[Code],
										[Desc],
										[Type],
										[Pb],
										[Retired],
										[Currency],
										[Seq],
										[Clientac],
										[Deposityn],
										[DepositType],
										[ChequeReq],
										[ChequePrinter],
										[LastNo],
										[Bank],
										[BankBranch],
										[Branch],
										[BankAddress],
										[BankType],
										[BankPhone],
										[AccountNo],
										[SortCode],
										[AccountName],
										[WithdrawNames],
										[AcOpened],
										[AcClosed],
										[Iban],
										[Bic],
										[OrgIDNumber]	
									)
						VALUES      ( 
										@Code,                 /*[Code]*/
										@Description,		   /*[Desc]*/
										@Type,	               /*[Type]*/
										@Pbtype,			   /*[Pb]*/
										@Retired,			   /*[Retired]*/
										@Currency,			   /*[Currency]*/
										@Repseq,			   /*[Seq]*/
										@Clientbankacct,	   /*[Clientac]*/
										@Deposit,			   /*[Deposityn]*/
										@DepositType,		   /*[DepositType]*/
										@Allowchqreq,		   /*[ChequeReq]*/
										@Chqprinter,		   /*[ChequePrinter]*/
										@Lastchqno,			   /*[LastNo]*/
										@Bank,				   /*[Bank]*/
										@BankBranch,		   /*[BankBranch]*/
										@Branch,		       /*[Branch]*/
										@Address,			   /*[BankAddress]*/
										@BankType,			   /*[BankType]*/
										@BankPhone,			   /*[BankPhone]*/
										@AccountNo,			   /*[AccountNo]*/
										@SortCode,			   /*[SortCode]*/
										@AccountName,		   /*[AccountName]*/
										@Signatories,		   /*[WithdrawNames]*/
										@DateOpened,		   /*[AcOpened]*/
										@DateClosed,		   /*[AcClosed]*/
										@Iban,				   /*[Iban]*/
										@Bic,				   /*[Bic]*/
										@OrgIdNum			   /*[OrgIDNumber]*/
									)
					END
									
            END
   	       COMMIT TRAN

	 END TRY
	 BEGIN CATCH
			     DECLARE @ErrorMsg      NVARCHAR(4000), 
				         @ErrorSeverity INT,
				         @ErrorState    INT; 

				  SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					     @ErrorSeverity = ERROR_SEVERITY(), 
					     @ErrorState    = ERROR_STATE()

			  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END  
	 END CATCH
END
GO


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

GO

CREATE PROCEDURE [dbo].[KAAS_CreateNominalBudget] 
	(
		 @CODE   		   VARCHAR(10),
		 @BRANCH 		   VARCHAR(10),
		 @YEAR 			   INT,
		 @PERIOD 		   INT,
		 @BUDGET 		   DECIMAL(19,2),
		 @RECORDID         INT
	)
AS
  /*******************************************************************************************************
  * Save the Nominal Budget                                                                              * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_CreateNominalBudget]   			            				     *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-09-27    Revathy D        Created                                                               *
  * 2022-03-01   Balamurugan C     Modified - Handled TCL Statements   and formatting                    *
  *******************************************************************************************************/
  BEGIN

  SET NOCOUNT ON 
   	BEGIN TRY
        BEGIN TRAN
			IF EXISTS
				(
					SELECT TOP 1 * 
						  FROM [dbo].[NOMINALBUDGETS]
						 WHERE [RECORDID] = @RECORDID
				)
			BEGIN
			   UPDATE [NBT] 
				  SET 
					  [NBT].[Code] 		= @CODE,
					  [NBT].[Branch] 	= @BRANCH,
					  [NBT].[Year] 	    = @YEAR,
					  [NBT].[Period] 	= @PERIOD,
					  [NBT].[Budget] 	= @BUDGET
				 FROM [dbo].[NominalBudgets] [NBT]
				WHERE [NBT].[RecordID]  = @RECORDID
			END
			ELSE
			 BEGIN
			   INSERT 
			     INTO [dbo].[NominalBudgets] 
				 (
					  [Code],
					  [Branch],
					  [Year],
					  [Period],
					  [Budget]
					) 
			  VALUES
					(   
					  @CODE,      /*[Code]*/
					  @BRANCH,	  /*[Branch]*/
					  @YEAR,	  /*[Year]*/
					  @PERIOD,	  /*[Period]*/
					  @BUDGET	  /*[Budget]*/
					)
			 END
 		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
			DECLARE @ErrorMsg      NVARCHAR(4000), 
				    @ErrorSeverity INT,
				    @ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

	      RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH
 SET NOCOUNT OFF

END

GO




IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateSAMControlAccountLog' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateSAMControlAccountLog] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateSAMControlAccountLog]
				 (
					   @HandlerCode		VARCHAR(10)	= ''
				 )
AS
  /*******************************************************************************************************
  * Control Account differences will stored in start of the day with handler code                        *
  * Each day one record need to be there                                                                 * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_CreateSAMControlAccountLog]   			            		     *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-12-23    Balamurugan C        Created                                                           *
  * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
  *******************************************************************************************************/
BEGIN
  BEGIN TRY
		BEGIN TRAN
				IF NOT EXISTS
					(
						SELECT TOP 1 1 
							  FROM [dbo].[ControlAccountLog]
							 WHERE CAST([EntryDate] AS DATE) = CAST(dbo.KEYHM_FNConvertDateToUTC(GETDATE(), @HandlerCode) AS DATE)
					)
				BEGIN
					DECLARE @LastBatch  INT   = 0,
							@CurrentDate DATE = NULL;

						SET @CurrentDate =  DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KEYHM_FNConvertDateToUTC](GETDATE(), @HandlerCode)), 0)


					DECLARE @FinalTable TABLE
					(
						[ClientAcMatterBalance]		DECIMAL(17,2) NULL,
						[OutlayAcMatterBalance]		DECIMAL(17,2) NULL,
						[BillingAcMatterBalance]	DECIMAL(17,2) NULL,
						[SupplierAcMatterBalance]	DECIMAL(17,2) NULL,
						[ClientControlAccounts]     DECIMAL(17,2) NULL,
						[OutlayControlAccounts]		DECIMAL(17,2) NULL,
						[BillingControlAccounts]    DECIMAL(17,2) NULL,
						[SupplierControlAccounts]   DECIMAL(17,2) NULL
					)
					INSERT INTO @FinalTable
					(
								[ClientAcMatterBalance],		
								[OutlayAcMatterBalance],		
								[BillingAcMatterBalance],	
								[SupplierAcMatterBalance],	
								[ClientControlAccounts],     
								[OutlayControlAccounts],		
								[BillingControlAccounts],    
								[SupplierControlAccounts]   	
					)
					SELECT SUM(ClientBal)						                AS [ClientAcMatterBalance],
						   SUM(OutlayBal)						                AS [OutlayAcMatterBalance],
						   SUM(DebtBal)							                AS [BillingAcMatterBalance],
					   (SELECT SUM(SupplierLedger.ORIGINAL) 
							AS Creditors 
						  FROM [dbo].[SupplierLedger] WITH(NOLOCK) )			AS [SupplierAcMatterBalance],
				(
					SELECT SUM(ISNULL(VALUE,0)) AS ClientControlAc 
					 FROM [dbo].[NominalLedger] WITH(NOLOCK)
					WHERE [CODE]=(SELECT [CNT].[CLIENT] 
									FROM [dbo].[Control] [CNT] WITH(NOLOCK)) 
									 AND YEAR=(SELECT [CNT].[YEAR] 
									FROM [dbo].[Control] [CNT] WITH(NOLOCK)))	AS [ClientControlAccounts],
					 (
					 SELECT ISNULL(SUM(ISNULL(VALUE,0)),0) AS OutlayControlAc  
					  FROM [dbo].[NominalLedger] WITH(NOLOCK)
					  WHERE[CODE]=(SELECT [CNT].[OUTLAY] 
									 FROM [dbo].[Control] [CNT] WITH(NOLOCK)) 
									  AND YEAR=(SELECT [CNT].[YEAR] 
												FROM [dbo].[Control] [CNT] WITH(NOLOCK))) AS [OutlayControlAccounts],
					(
					SELECT ISNULL(SUM(ISNULL(VALUE,0)),0) AS DebtorsControlAc 
					FROM [dbo].[NominalLedger] WITH(NOLOCK)
					WHERE CODE=(SELECT [CNT].[DEBTORS] FROM [dbo].[Control] [CNT] WITH(NOLOCK)) 
								AND YEAR=(SELECT [CNT].[YEAR] 
										  FROM [dbo].[Control] [CNT] WITH(NOLOCK))) AS [BillingControlAccounts],
					(SELECT ISNULL(SUM(ISNULL(VALUE,0)),0) AS CreditorsControlAc 
					   FROM [dbo].[NominalLedger] WITH(NOLOCK)
					  WHERE [CODE]=(SELECT [CNT].[CREDITOR] 
									  FROM [dbo].[Control] [CNT] WITH(NOLOCK)) 
									   AND YEAR=(SELECT [CNT].[YEAR] 
												   FROM [dbo].[Control] [CNT] WITH(NOLOCK))) AS [SupplierControlAccounts]
					FROM [dbo].[Matters] WITH(NOLOCK)

					SELECT @LastBatch = [LastBatch] FROM [dbo].[Control] WITH(NOLOCK)

					INSERT INTO [dbo].[ControlAccountLog]
							(
								[User],
								[EntryDate],
								[ModifiedDate],
								[LastBatchNo],
								[ClientAcMatterBalance],
								[OutlayAcMatterBalance],
								[BillingAcMatterBalance],
								[SupplierAcMatterBalance],
								[ClientControlAccounts],
								[OutlayControlAccounts],
								[BillingControlAccounts],
								[SupplierControlAccounts]
							)
						 SELECT @HandlerCode,
								@CurrentDate,
								@CurrentDate,
								@LastBatch,
								[ClientAcMatterBalance],
								[OutlayAcMatterBalance],
								[BillingAcMatterBalance],
								[SupplierAcMatterBalance],
								[ClientControlAccounts],
								[OutlayControlAccounts],
								[BillingControlAccounts],
								[SupplierControlAccounts]
						   FROM @FinalTable

				END
			COMMIT TRAN
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END
	END CATCH
END
GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateSAMCreditorMultiPayment' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateSAMCreditorMultiPayment] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateSAMCreditorMultiPayment]
		(
			@SupplierCode      VARCHAR(15)    = '',
			@SupplierName      VARCHAR(50)    = '',
			@BankCode		   VARCHAR(15)    = '',
			@UnpaidValue	   DECIMAL(18,2)  = 0,
			@PayValue		   DECIMAL(18,2)  = 0,
			@AllocBatch  	   INT            = 0,
			@AllocPref         INT            = 0,
			@AllocRef		   VARCHAR(20)    = '',
			@RecordID          INT            = 0,
			@SumOfPayValue     DECIMAL(18,2)  = 0,
			@TotalRecordCount  INT            = 0,
			@Mode              VARCHAR(20)    = '',
			@UpdateBatch       INT			  = 0
		)
AS
/*******************************************************************************************************
* Create Multi Payment Batch and Details                                                               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateSAMCreditorMultiPayment]        					       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-12    Balamurugan C        Created                                                           *
* 2021-10-18	Balamurugan C        Modified - Removed Supplier Ledger Update Part                    *
* 2021-12-24	Balamurugan C        Modified - Changed @UpdateBatch from default string to int        *
* 2022-02-28    Balamurugan.C        Modified - Handled TCL Statements                                 *
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRAN
			IF(@Mode='Record')
				BEGIN
				 DECLARE @LastBatch        INT         = 0,
						 @LastPref         INT         = 0,
						 @Year	           INT         = 0,
						 @CurPer           INT         = 0,
						 @LastPrefDetails  INT         = 0,
						 @DefaultCreditor  VARCHAR(15) = ''

				 (
				  SELECT @LastBatch       = (LastBatch + 1),
						 @LastPref        = (LastPref + 1),
						 @Year            = [Year],
						 @CurPer          = CurPer,
						 @DefaultCreditor = [Creditor]
				  FROM	 [dbo].[Control]
				 )
	/* INSERT TO BATCH HEADER TABLE */
			 IF NOT EXISTS	
				 (
			        SELECT TOP 1 1
				      FROM [dbo].[BatchH] 
				     WHERE [BatchNo] = @LastBatch
				  )	
			 INSERT INTO   [dbo].[BatchH]
					   (   [Batchno],
						   [Postfwd],
						   [Type],
						   [Code],
						   [Branch],
						   [Pref],
						   [Ref],
						   [Date],
						   [Fee],
						   [Matter],
						   [Supp],
						   [Narr],
						   [Value],
						   [Subtot],
						   [Posted],
						   [ClientAc],
						   [PerNo],
						   [Year],
						   [Payee],
						   [OutlayTot],
						   [VatTot],
						   [FeeTot],
						   [Invcr],
						   [ThirdParty],
						   [UserCode],
						   [EntryDate],
						   [ClientBank],
						   [Currency],
						   [CurrencyValue],
						   [CuroutlayTot],
						   [CurVatTot],
						   [CurFeeTot],
						   [RecNo],
						   [Singleline],
						   [Template],
						   [ChequeReqNo],
						   [WriteDown],
						   [WriteBackHours],
						   [WriteBackValue],
						   [CorrectCopy],
						   [CreditInvoiceNo],
						   [DraftBillNo],
						   [EFTSent],
						   [EFTDate],
						   [EFTFileNumber],
						   [EFTFileName],
						   [EFTYorN],
						   [ClientCode],
						   [PayClient],
						   [OnceOffPayment],
						   [CaseAssCode],
						   [EFTEmailYorN],
						   [HandlerCode],
						   [PaymentMethod],
						   [ClearedDate]  
					   )
				  VALUES 
					   (   
						   @LastBatch,                       /*[Batchno],*/
						   '',								 /*[Postfwd],*/
						   'M',							     /*[Type],*/
						   @BankCode,						 /*[Code],*/
						   '',								 /*[Branch],*/
						   @LastPref,						 /*[Pref],*/
						   'EFT',							 /*[Ref],*/
						   CAST(GETUTCDATE() AS DATE),		 /*[Date],*/
						   '',								 /*[Fee],*/
						   '',								 /*[Matter],*/
						   '',								 /*[Supp],*/
						   '',								 /*[Narr],*/
						   @SumOfPayValue,					 /*[Value],*/
						   0.00,							 /*[Subtot],*/
						   'N',								 /*[Posted],*/
						   '',								 /*[ClientAc],*/
						   @CurPer,							 /*[PerNo],*/
						   @Year,							 /*[Year],*/
						   '',								 /*[Payee],*/
						   0.00,							 /*[OutlayTot],*/
						   0.00,							 /*[VatTot],*/
						   0.00,                             /*[FeeTot],*/        
						   '',								 /*[Invcr],*/
						   '',								 /*[ThirdParty],*/
						   'keyhouse',						 /*[UserCode],*/
						   CAST(GETUTCDATE() AS DATE),		 /*[EntryDate],*/
						   '',								 /*[ClientBank],*/
						   'E',								 /*[Currency],*/
						   @SumOfPayValue,					 /*[CurrencyValue],*/
						   0.00,							 /*[CuroutlayTot],*/
						   0.00,							 /*[CurVatTot],*/
						   0.00,							 /*[CurFeeTot],*/
						   0,								 /*[RecNo],*/
						   '',								 /*[Singleline],*/
						   '',								 /*[Template],*/
						   0,								 /*[ChequeReqNo],*/
						   NULL,							 /*[WriteDown],*/
						   0.00,							 /*[WriteBackHours],*/
						   0.00,							 /*[WriteBackValue],*/
						   '',								 /*[CorrectCopy],*/
						   0,								 /*[CreditInvoiceNo],*/
						   0,								 /*[DraftBillNo],*/
						   'N',								 /*[EFTSent],*/
						   NULL,							 /*[EFTDate],*/
						   0,								 /*[EFTFileNumber],*/
						   '',								 /*[EFTFileName],*/
						   'Y',								 /*[EFTYorN],*/
						   '',								 /*[ClientCode],*/
						   'N',								 /*[PayClient],*/
						   'N',								 /*[OnceOffPayment],*/
						   '',								 /*[CaseAssCode],*/
						   'N',								 /*[EFTEmailYorN],*/
						   '',								 /*[HandlerCode],*/
						   0,								 /*[PaymentMethod],*/
						   NULL 							 /*[ClearedDate]*/  
					    ) 

				    UPDATE [dbo].[Control] 
					   SET [LASTPREF] = (@LastPref) 
				     WHERE [NEXT_DOC_NO] = 0

				    SELECT @LastPrefDetails = (LASTPREF+1) 
					  FROM [dbo].[Control]
	/* INSERT TO BATCH DETAILS TABLE */
			 INSERT INTO   [dbo].[Batchdetails]
					   (   
						   [BatchNo],
						   [Type],
						   [Code],
						   [Pref],
						   [Ref],
						   [Date],
						   [Fee],
						   [Branch],
						   [Narr], 
						   [Matter],
						   [Supp],
						   [Value],
						   [Vatcode],
						   [Vatval],
						   [Clientyn],
						   [Outlay],
						   [Pending],
						   [Year],
						   [Perno],
						   [Entrycurrency],
						   [Currencyvalue],
						   [Currencyvat],
						   [Outlaycode],
						   [Thirdparty],
						   [Payee],
						   [Headpref],
						   [Headbatch],
						   [Allocbatch],
						   [Allocpref],
						   [Allocref],
						   [Allocvalue],
						   [Allocwriteoff],
						   [Psupp],
						   [Undetaking],
						   [Caseasscode],
						   [Onceoffpayment],
						   [Payclient],
						   [ClientCode],
						   [EFTEmailYorN],
						   [RegisteredPost],
						   [PreBilledOutlay]
					   )
				  VALUES
					   (
						   @LastBatch,					                                                /*[BatchNo],*/
						   'M',					                      									/*[Type],*/
						   @DefaultCreditor,				                              				/*[Code],*/
						   @LastPrefDetails,					                  						/*[Pref],*/
						   'EFT',				                      									/*[Ref],*/
						   CAST(GETUTCDATE() AS DATE),                   								/*[Date],*/
						   '',							                  								/*[Fee],*/
						   '',						                  									/*[Branch],*/
						   'Auto Pd '+@SupplierName+' bill(s) for '+ CONVERT(varchar(20),@UnpaidValue), /*[Narr],*/ 
						   '',								      										/*[Matter],*/
						   @SupplierCode,					                          					/*[Supp],*/
						   @PayValue,			                      									/*[Value],*/
						   '',					                          								/*[Vatcode],*/
						   0.00,	                                  									/*[Vatval],*/
						   '',			                                  								/*[Clientyn],*/
						   'N',		                                      								/*[Outlay],*/
						   '',			                                  								/*[Pending],*/
						   @Year,		                                  								/*[Year],*/
						   @CurPer,			                          									/*[Perno],*/
						   'E',		                                  									/*[Entrycurrency],*/
						   @PayValue,	                              									/*[Currencyvalue],*/
						   0.00,		                                  								/*[Currencyvat],*/
						   '',			                                  								/*[Outlaycode],*/
						   '',			                                  								/*[Thirdparty],*/
						   @SupplierName,			                                  					/*[Payee],*/
						   @LastBatch + 1,			                                  					/*[Headpref],*/
						   @LastPref + 1,			                                  					/*[Headbatch],*/
						   @AllocBatch,		                          									/*[Allocbatch],*/
						   @AllocPref,		                              								/*[Allocpref],*/
						   @AllocRef,		                              								/*[Allocref],*/
						   @PayValue,	                              									/*[Allocvalue],*/
						   'N',		                                  									/*[Allocwriteoff],*/
						   '',			                                  								/*[Psupp],*/
						   0,			                                  								/*[Undetaking],*/
						   '',			                                  								/*[Caseasscode],*/
						   'N',		                                  									/*[Onceoffpayment],*/
						   'N',		                                  									/*[Payclient],*/
						   '',			                                  								/*[ClientCode],*/
						   'N',		                                  									/*[EFTEmailYorN],*/
						   0,			                                  								/*[RegisteredPost],*/
						   0			                                  								/*[PreBilledOutlay]*/
					   )

				    UPDATE [dbo].[Control] 
					   SET [LASTPREF]  = @LastPrefDetails
	   			     WHERE [NEXT_DOC_NO] = 0

			IF(@TotalRecordCount=1)
				BEGIN
				  UPDATE [dbo].[CreditorsList]
					 SET [OsValue] = CONVERT(NUMERIC(18,2),[OsValue]) + CONVERT(NUMERIC(18,2),ABS(@PayValue))
				   WHERE [RecordID] = @RecordID	    
				END

				  SELECT @LastBatch 'ResultBatch'

			END
		IF(@Mode='Batch')
			BEGIN
				  UPDATE [dbo].[Control] 
					 SET [LASTBATCH] = @UpdateBatch
	   			   WHERE [NEXT_DOC_NO] = 0
			END
		COMMIT TRAN
	END TRY

	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END 
	 END CATCH

END

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateSAMReconHistoryRecord' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateSAMReconHistoryRecord] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateSAMReconHistoryRecord]
	( 
		@BankAc	           VARCHAR(10)   = '',
		@RecDate           DATE          = NULL,
		@OsLodgements      DECIMAL(17,2) = 0,
		@OsCheques		   DECIMAL(17,2) = 0,
		@BankBal           DECIMAL(17,2) = 0,
		@ClosingBal        DECIMAL(17,2) = 0,
		@Diff              DECIMAL(17,2) = 0,
		@HandlerCode       VARCHAR(10)   = '',
		@Mode              VARCHAR(10)   = ''
	)
AS
/*******************************************************************************************************
* Bank Reconciliation -Insert Update Recon History Records                                             *
* Proceed Functionality -Update Nominal Ledger RecNo Columns based on BankAccount                      *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateSAMReconHistoryRecord]   			                       *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-19    Balamurugan C        Created                                                           *
* 2022-01-20    Balamurugan C        Modified - Added where condition for nominal ledger               *
* 2022-02-08	Balamurugan C        Modified - Added date condition for proceed functionality         *
* 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/
BEGIN
 BEGIN TRY
  BEGIN TRAN
	IF(@Mode = 'SAVE')
		BEGIN
			IF NOT EXISTS
			(
				SELECT TOP 1 1 
				  FROM [dbo].[BankRecHistory] 
				 WHERE [BankAc] = @BankAc
				   AND [RecNo]  = 0
			)
			BEGIN
				INSERT
				  INTO [dbo].[BankRecHistory]
					(
					   [RecNo],		    
					   [BankAc],	        
					   [RecDate],        
					   [DateComplete],   
					   [LastRec],        
					   [Currency],       
					   [OpeningBalance], 
					   [Lodgements],     
					   [Cheques],        
					   [OsLodgements],    
					   [OsCheques],		
					   [BankBal],        
					   [ClosingBal],     
					   [Diff]           
					)
				VALUES
					(
					   0,		     
					   @BankAc,	         
					   dbo.KEYHM_FNConvertDateToUTC(@RecDate, @HandlerCode),         
					   CAST(dbo.KEYHM_FNConvertDateToUTC(GETDATE(), @HandlerCode) AS DATE),
					   0,         
					   '',        
					   0.00,  
					   0.00,      
					   0.00,         
					   @OsLodgements,    
					   @OsCheques,		 
					   @BankBal,         
					   @ClosingBal,      
					   @Diff            
					)
			END
			ELSE
			BEGIN
				UPDATE [dbo].[BankRecHistory]
				   SET [RecDate]      = dbo.KEYHM_FNConvertDateToUTC(@RecDate, @HandlerCode),
				       [ClosingBal]   = @ClosingBal,
					   [OsLodgements] = @OsLodgements,
					   [OsCheques]    = @OsCheques,
				       [BankBal]      = @BankBal
				 WHERE [BankAc]       = @BankAc
				   AND [RECNO]        = 0 
				       
			END
		END
	IF(@Mode = 'PROCEED')
		BEGIN
			UPDATE [dbo].[NominalLedger]
			   SET [RECNO]         = 1
			 WHERE RTRIM([Code])   = @BankAc
			   AND [Date]         <= @RecDate
		END
  COMMIT TRAN
 END TRY

 BEGIN CATCH
	DECLARE @ErrorMsg      NVARCHAR(4000), 
			@ErrorSeverity INT,
			@ErrorState    INT; 

	SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
		   @ErrorSeverity = ERROR_SEVERITY(), 
		   @ErrorState    = ERROR_STATE()

 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
		  IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
 END CATCH
END
GO 

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateSAMReconOutstandingTransRecord' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateSAMReconOutstandingTransRecord] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateSAMReconOutstandingTransRecord]
	( 
		@Type		       VARCHAR(1)    = '',
		@Date              DATETIME      = NULL,
		@Ref			   VARCHAR(8)    = '',
		@Narr			   VARCHAR(60)   = '',
		@Value             DECIMAL(17,2) = 0,
		@BankCode          VARCHAR(10)   = '',
		@RecordId          INT           = 0,
		@HandlerCode       VARCHAR(10)   = '',
		@Mode              VARCHAR(15)   = ''
	)
AS
/*******************************************************************************************************
* Bank Reconciliation -Insert Update Recon Outstanding Trans REcords                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateSAMReconOutstandingTransRecord]   			               *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-18    Balamurugan C        Created                                                           *
* 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/
BEGIN
  BEGIN TRY
	 BEGIN TRAN
IF(@Mode = 'INSERTUPDATE')
	BEGIN
		IF EXISTS
		(
			SELECT TOP 1 1 
			  FROM [dbo].[BankRecOutstandingTrans] 
			 WHERE [RecordId] = @RecordId
		)
			BEGIN
				UPDATE [dbo].[BankRecOutstandingTrans]
				   SET [Type]  = @Type,
					   [Date]  = dbo.KEYHM_FNConvertDateToUTC(CAST(@Date AS DATE), @HandlerCode),
					   [Ref]   = @Ref,
					   [Narr]  = @Narr,
					   [Value] = @Value
				 WHERE [RecordId] = @RecordId
			END
		ELSE
			BEGIN
				INSERT
				  INTO [dbo].[BankRecOutstandingTrans]
					 (
					   [BankAc],
					   [Type],
					   [Date],
					   [Ref],
					   [Batch],
					   [Pref],
					   [Narr],
					   [Value],
					   [RecNo]
					 )
				VALUES
					 (
						@BankCode,
						@Type,
						dbo.KEYHM_FNConvertDateToUTC(CAST(@Date AS DATE), @HandlerCode),
						@Ref,
						0,
						dbo.KAAS_FN_ConvertDateToClarion(dbo.KEYHM_FNConvertDateToUTC(GETDATE(),''))  
						+ ([dbo].[ky_ConvertTimeToClarion](dbo.KEYHM_FNConvertDateToUTC(GETDATE(),'')) / 100 ),
						@Narr,
						@Value,
						0
					 )
			END
	END
	ELSE
		BEGIN
			DELETE 
			  FROM [dbo].[BankRecOutstandingTrans]
			 WHERE [RecordId] = @RecordId
		END

  		COMMIT TRAN
	END TRY

	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
			   @ErrorSeverity = ERROR_SEVERITY(), 
			   @ErrorState    = ERROR_STATE()

	 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			  IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END 
	END CATCH
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_CreateSAMWriteOffIssueInvoice' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_CreateSAMWriteOffIssueInvoice] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_CreateSAMWriteOffIssueInvoice]
		(
				@ParamsBatchNo      INT         = 0,
				@ParamsType         VARCHAR(1)  = '',
				@ParamsRef          VARCHAR(20) = '',
				@ParamsDate         DATETIME    = NULL,
				@ParamsAllocBatch  	INT         = 0,
				@HandlerCode		VARCHAR(15) = ''
		)
AS
/*******************************************************************************************************
* Create Write Off Issue Invoice Batch  Details                                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateSAMWriteOffIssueInvoice]        					       *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-12    Balamurugan C        Created                                                           *
* 2022-02-28    Balamurugan.C        Modified - Handled TCL Statements                                 *
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRANSACTION
			DECLARE 
					@LastPref             INT            = 0,
					@CurrentYear	      INT            = 0,
					@CurPer               INT            = 0,
					@SystemCurrenyValue   DECIMAL(17,6)  = 0
						
			 SELECT @CurrentYear        = [Year],
				    @CurPer             = [CurPer],
				    @SystemCurrenyValue = [IECONVERT]
		       FROM [dbo].[Control]
					 

	DECLARE  @Code            CHAR(10)		,
			 @Ref             CHAR(10)		,
			 @Fee             VARCHAR(10)	,
			 @Branch          VARCHAR(3)	,
			 @Narr            CHAR(100)		,
			 @Matter          VARCHAR(20)	,
			 @Supp            CHAR(10)		,
			 @Value           DECIMAL(17, 2),
			 @VatCode         CHAR(1)		,
			 @VatVal          DECIMAL(17, 2),
			 @ClientYN        CHAR(1)		,
			 @Outlay          CHAR(1)		,
			 @Pending         CHAR(1)		,
			 @EntryCurrency   CHAR(1)		,
			 @CurrencyVat     DECIMAL(17, 2),
			 @OutlayCode      CHAR(4)		,
			 @ThirdParty      CHAR(1)		,
			 @Payee           CHAR(60)		,
			 @HeadPref        INT			,
			 @HeadBatch       INT			,
			 @AllocBatch      INT			,
			 @AllocPref       INT			,
			 @AllocRef        CHAR(10)		,
			 @AllocValue      DECIMAL(17, 2),
			 @AllocWriteOff   CHAR(1)		,
			 @Psupp           CHAR(10)		,
			 @Undetaking      SMALLINT		,
			 @CaseAssCode     VARCHAR(6)	,
			 @OnceOffPayment  CHAR(1)		,
			 @PayClient       CHAR(1)		,
			 @ClientCode      VARCHAR(10)	,
			 @EFTemailYorN    CHAR(1)		,
			 @RegisteredPost  INT			,
			 @PreBilledOutlay BIT			,
			 @KeyId		      INT			    
  
   DECLARE batchDetails_Cursor CURSOR FOR
   						 SELECT [Code],
								[Ref],
								[Fee],
								[Branch],
								[Narr],
								[Matter],
								[Supp],
								[Value],
								[VatCode],
								[VatVal],
								[ClientYN],
								[Outlay],
								[Pending],
								[EntryCurrency],
								[CurrencyVat],
								[OutlayCode],
								[ThirdParty],
								[Payee],
								[HeadPref],
								[HeadBatch],
								[AllocBatch],
								[AllocPref],
								[AllocRef],
								[AllocValue],
								[Allocwriteoff],
								[Psupp],
								[Undetaking],
								[CaseAssCode],
								[OnceOffPayment],
								[PayClient],
								[ClientCode],
								[EFTEmailYorN],
								[RegisteredPost],
								[PreBilledOutlay]
						   FROM [dbo].[BatchDetails]
						  WHERE [BatchNo] = @ParamsAllocBatch  

      OPEN batchDetails_Cursor

     FETCH 
 NEXT FROM batchDetails_Cursor
      INTO        
		 @Code              
		,@Ref             
		,@Fee             
		,@Branch          
		,@Narr            
		,@Matter          
		,@Supp            
		,@Value           
		,@VatCode         
		,@VatVal          
		,@ClientYN        
		,@Outlay          
		,@Pending           
		,@EntryCurrency   
		,@CurrencyVat     
		,@OutlayCode      
		,@ThirdParty      
		,@Payee           
		,@HeadPref        
		,@HeadBatch       
		,@AllocBatch      
		,@AllocPref       
		,@AllocRef        
		,@AllocValue      
		,@AllocWriteOff   
		,@Psupp           
		,@Undetaking      
		,@CaseAssCode     
		,@OnceOffPayment  
		,@PayClient       
		,@ClientCode      
		,@EFTemailYorN    
		,@RegisteredPost  
		,@PreBilledOutlay 
	 WHILE @@FETCH_STATUS = 0
		BEGIN
		   SELECT @LastPref = [LastPref] + 1 FROM [dbo].[Control] WITH(NOLOCK) WHERE [NEXT_DOC_NO] = 0  
		          INSERT 
			        INTO [dbo].[Batchdetails]
					  (     
						 [BatchNo],
						 [Type],
						 [Code],
						 [Pref],
						 [Ref],
						 [Date],
						 [Fee],
						 [Branch],
						 [Narr],
						 [Matter],
						 [Supp],
						 [Value],
						 [Vatcode],
						 [Vatval],
						 [Clientyn],
						 [Outlay],
						 [Pending],
						 [Year],
						 [Perno],
						 [Entrycurrency],
						 [CurrencyValue],
						 [Currencyvat],
						 [Outlaycode],
						 [Thirdparty],
						 [Payee],
						 [Headpref],
						 [Headbatch],
						 [Allocbatch],
						 [Allocpref],
						 [Allocref],
						 [Allocvalue],
						 [Allocwriteoff],
						 [Psupp],
						 [Undetaking],
						 [Caseasscode],
						 [Onceoffpayment],
						 [Payclient],
						 [ClientCode],
						 [EFTEmailYorN],
						 [RegisteredPost],
						 [PreBilledOutlay]
					  )

	(	SELECT 			 @ParamsBatchNo                                            /*[BatchNo]*/
						,@ParamsType            								   /*[Type]*/
						,@Code            										   /*[Code]*/
						,@LastPref   											   /*[Pref]*/
						,@Ref             										   /*[Ref]*/
						,dbo.KEYHM_FNConvertDateToUTC(@ParamsDate,@HandlerCode)    /*[Date]*/        
						,@Fee             										   /*[Fee]*/
						,@Branch          										   /*[Branch]*/
						,@Narr            										   /*[Narr]*/
						,@Matter          										   /*[Matter]*/
						,@Supp            										   /*[Supp]*/
						,@Value           										   /*[Value]*/
						,@VatCode         										   /*[Vatcode]*/
						,@VatVal          										   /*[Vatval]*/
						,@ClientYN        										   /*[Clientyn]*/
						,@Outlay          										   /*[Outlay]*/
						,@Pending         										   /*[Pending]*/
						,@CurrentYear            								   /*[Year]*/
						,@CurPer           										   /*[Perno]*/
						,@EntryCurrency   										   /*[Entrycurrency]*/
						,@Value * @SystemCurrenyValue   						   /*[CurrencyValue]*/
						,@CurrencyVat     										   /*[Currencyvat]*/
						,@OutlayCode      										   /*[Outlaycode]*/
						,@ThirdParty      										   /*[Thirdparty]*/
						,@Payee           										   /*[Payee]*/
						,@HeadPref        										   /*[Headpref]*/
						,@HeadBatch       										   /*[Headbatch]*/
						,@AllocBatch      										   /*[Allocbatch]*/
						,@AllocPref       										   /*[Allocpref]*/
						,@AllocRef        										   /*[Allocref]*/
						,@AllocValue      										   /*[Allocvalue]*/
						,@AllocWriteOff   										   /*[Allocwriteoff]*/
						,@Psupp           										   /*[Psupp]*/
						,@Undetaking      										   /*[Undetaking]*/
						,@CaseAssCode     										   /*[Caseasscode]*/
						,@OnceOffPayment  										   /*[Onceoffpayment]*/
						,@PayClient       										   /*[Payclient]*/
						,@ClientCode      										   /*[ClientCode]*/
						,@EFTemailYorN    										   /*[EFTEmailYorN]*/
						,@RegisteredPost  										   /*[RegisteredPost]*/
						,@PreBilledOutlay 										   /*[PreBilledOutlay]*/
						)

				UPDATE [dbo].[Control] 
				   SET [LASTPREF] = (@LastPref) 
				 WHERE [NEXT_DOC_NO] = 0  

		        SELECT @LastPref = [LastPref] + 1 FROM [dbo].[Control] WITH(NOLOCK) WHERE [NEXT_DOC_NO] = 0  

				 FETCH 
			 NEXT FROM batchDetails_Cursor
				  INTO        
						 @Code                     
						,@Ref                       
						,@Fee             
						,@Branch          
						,@Narr            
						,@Matter          
						,@Supp            
						,@Value           
						,@VatCode         
						,@VatVal          
						,@ClientYN        
						,@Outlay          
						,@Pending             
						,@EntryCurrency   
						,@CurrencyVat     
						,@OutlayCode      
						,@ThirdParty      
						,@Payee           
						,@HeadPref        
						,@HeadBatch       
						,@AllocBatch      
						,@AllocPref       
						,@AllocRef        
						,@AllocValue      
						,@AllocWriteOff   
						,@Psupp           
						,@Undetaking      
						,@CaseAssCode     
						,@OnceOffPayment  
						,@PayClient       
						,@ClientCode      
						,@EFTemailYorN    
						,@RegisteredPost  
						,@PreBilledOutlay 

		  END
	 CLOSE batchDetails_Cursor;
DEALLOCATE batchDetails_Cursor;

		COMMIT TRANSACTION

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH

END
GO

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

CREATE PROCEDURE [dbo].[KAAS_DeleteBatchDetails] (
       @KeyId DECIMAL)
AS
/*******************************************************************************************************
* Delete Batch Details                                                                                 *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_DeleteBatchDetails]                                              *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-10    Revathy D        Created                                                               *
* 2022-02-11    John Ginnane     Revised to match standard                                             *
* 2022-02-16    Balamurugan.C    Added new line end of the procedure                                   *
* 2022-02-25    Balamurugan.C    Modified - Handled TCL Statements                                     *
********************************************************************************************************/
BEGIN
   SET NOCOUNT ON
    BEGIN TRY
	 BEGIN TRAN  
			DELETE [BAD]
			  FROM [dbo].[BatchDetails] AS [BAD]
			 WHERE [BAD].[KEYID] =  @KeyId
   		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	 END CATCH
    SET NOCOUNT OFF
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_DeleteBatchHeader] (
       @BatchNo INT)
AS
/*******************************************************************************************************
* Delete Batch Header                                                                                  *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_DeleteBatchHeader]                                               *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-10    Revathy D        Created                                                               *
* 2022-02-11    John Ginnane     Revised to match standard                                             *
* 2022-02-16    Balamurugan.C    Added new line end of the procedure                                   *
* 2022-02-23    Balamurugan.C    Modified - Handled TCL Statements                                     *
********************************************************************************************************/
BEGIN
    SET NOCOUNT ON
     BEGIN TRY
	  BEGIN TRAN  

		DELETE [BAH]
		  FROM [dbo].[BatchH] AS [BAH]
		 WHERE [BAH].[BATCHNO] =  @BatchNo

		DELETE [BAD]
		  FROM [dbo].[BatchDetails] AS [BAD]
		 WHERE [BAD].[BATCHNO] = @BatchNo
        		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	 END CATCH
    SET NOCOUNT OFF
 END
 GO

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

CREATE PROCEDURE [dbo].[KAAS_DeleteDebtorsLedgerAllocation] (
       @KeyId    INT,
       @Result   TINYINT   OUTPUT)
AS
  /*******************************************************************************************************
  * Used to Insert supplier ledger allocation                                                            *
  * Stored Procedure Name: [dbo].[KAAS_DeleteDebtorsLedgerAllocation]                                    *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-03-26   Natarajan S        Created                                                              *
  * 2021-03-28   Natarajan S        Modified - Added @result parameter after update                      *
  * 2023-11-30   John Ginnane       #17517 - Fixed conversion issues and refactored code                 *
  ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    -- Make sure record exists
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Allocations] AS [ALO]
                    WHERE [ALO].[KEYID] = @KeyId)
    BEGIN
        SET @Result = 0
        RETURN
    END

    BEGIN TRY
        BEGIN TRANSACTION

        DECLARE @INVBATCHNO  INT
        DECLARE @RECBATCHNO  INT
        DECLARE @VALUE       DECIMAL(17, 2)
        DECLARE @FEES        DECIMAL(17, 2)
        DECLARE @OUTLAY      DECIMAL(17, 2)
        DECLARE @VAT         DECIMAL(17, 2)
        DECLARE @AllNo       INT
                            
        SELECT @INVBATCHNO  = [ALO].[BATCHNO],
               @RECBATCHNO  = [ALO].[ABATCHNO],
               @VALUE       = [ALO].[VALUE],
               @FEES        = [ALO].[FEES],
               @OUTLAY      = [ALO].[OUTLAY],
               @VAT         = [ALO].[VAT],
               @AllNo       = [ALO].[AllNo]
          FROM [dbo].[Allocations] AS [ALO]
         WHERE [ALO].[KEYID] = @KeyId
        
        UPDATE [DTL]
           SET [DTL].[OSVALUE]  = CASE WHEN [DTL].[Type]= 'R'
                                       THEN [DTL].[OSValue] + @Value
                                       ELSE [DTL].[OSValue] - @Value END,
               [DTL].[OSFEES]   = CASE WHEN [DTL].[Type] = 'R'
                                       THEN [DTL].[OSFees] + @FEES
                                       ELSE [DTL].[OSFees] - @FEES END,
               [DTL].[OSOUTLAY] = CASE WHEN [DTL].[Type] = 'R'
                                       THEN [DTL].[OSOutlay] + @OUTLAY
                                       ELSE [DTL].[OSOutlay] - @OUTLAY END,
               [DTL].[OSVat]    = CASE WHEN [DTL].[Type] = 'R'
                                       THEN [DTL].[OSVat] + @VAT
                                       ELSE [DTL].[OSVat] - @VAT END                                  
          FROM [dbo].[DebtorsLedger] AS [DTL]
         WHERE [DTL].[BatchNo] IN (@INVBATCHNO, @RECBATCHNO)
                            
        DELETE [ALO]
          FROM [dbo].[Allocations] AS [ALO]
         WHERE [ALO].[AllNo] = @AllNo

        SET @Result = 1

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        SET @Result = 0

        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
END
GO
IF OBJECT_ID(N'KAAS_DeleteMasters',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_DeleteMasters]
GO

CREATE PROCEDURE 
	[dbo].[KAAS_DeleteMasters]
	(
		@TableName varchar(100),
		@CodeVal varchar(20),
		@Result int =0 Output
	)

AS

/*******************************************************************************************************
* Delete Master details                                                                                * 
*          select * from departments                                                                   *
* Stored Procedure Name : [dbo].[KAAS_DeleteMasters] 'departments',	''	 							   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-17    Natarajan S      Created  
* 2021-03-01	Ghayathri.S.V    Modified Delete Logic for Category Type
 *******************************************************************************************************/

BEGIN
 SET NOCOUNT ON  
	BEGIN TRY
		BEGIN TRAN
			IF(@TableName = 'CategoryType')
				BEGIN
					DELETE 
				      FROM   [dbo].[CategoryType] 
		             WHERE   CategoryType = @CodeVal
		               SET   @Result =1
			    END
		    ELSE
				DECLARE @Qry Nvarchar(max)

				DECLARE @ColCode varchar(20)
				    SET @ColCode = (	SELECT 
											C.COLUMN_NAME 
										FROM  
											INFORMATION_SCHEMA.TABLE_CONSTRAINTS T  
										JOIN 
											INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE C  
										ON 
											C.CONSTRAINT_NAME=T.CONSTRAINT_NAME  
										WHERE  
											C.TABLE_NAME=@TableName  
										AND
											T.CONSTRAINT_TYPE='PRIMARY KEY'
									)


					SET  @Qry = 'DELETE FROM '+@TableName+' WHERE ' +@ColCode+'=''' +@CodeVal +''''

					SET  @Result =1
					exec sp_executesql  @Qry
		COMMIT TRAN
	END TRY
		BEGIN CATCH
			DECLARE @ErrorMsg      NVARCHAR(4000), 
					@ErrorSeverity INT,
					@ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

		  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END 
			END CATCH
   SET NOCOUNT OFF
 END


 GO


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

go 

CREATE PROCEDURE [dbo].[Kaas_DeleteMatterledger] (@LRef INT,@Result	TINYINT OUTPUT) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  * Used to delete the matter ledger                                                                     *
  * Stored Procedure Name: [dbo].[Kaas_DeleteMatterledger]												 * 
  * Modification History:                                                                                *
  * 2021-04-12 Natarajan S        Created																 *      
   *******************************************************************************************************/
  BEGIN 
  DELETE FROM 
		[dbo].[MatterLedger]
	WHERE
	    [LREF]=@LRef
	 SET @Result = 1
  END 

go 




IF OBJECT_ID(N'KAAS_DeleteNominalAccountDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_DeleteNominalAccountDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_DeleteNominalAccountDetails]
		(
				@Code			VARCHAR(10)  = '',
				@Mode			VARCHAR(10)  = '',
				@User			VARCHAR(10)  = ''
		)
AS
/*******************************************************************************************************
* Validate and Delete the Nominal Account Details                                                                     
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_DeleteNominalAccountDetails]   			            		   *
*                                                                                                      *
* Modification History:                                                                                *
* Ghayathri.S.V			09-Feb-2022				Created                                                *
* Balamurugan.C         01-Mar-2022             Modified - Handled TCL Statements   and formatting     *    
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON
	  BEGIN TRY
        BEGIN TRAN
			IF(@Mode = 'VALIDATE')
				BEGIN
					DECLARE @Balance					DECIMAL(17,2) = 0,
							@deleteCount				INT = 0,
							@LastYearBalanceOne			DECIMAL(17,2) = 0,
							@LastYearBalanceTwo			DECIMAL(17,2) = 0,
							@LastYearBalanceThree		DECIMAL(17,2) = 0,
							@LastYearBalanceFour		DECIMAL(17,2) = 0,
							@LastYearBalanceFive		DECIMAL(17,2) = 0,
							@LastYearBalanceSix			DECIMAL(17,2) = 0,
							@LastYearBalanceSeven		DECIMAL(17,2) = 0,
							@LastYearBalanceEight		DECIMAL(17,2) = 0,
							@LastYearBalanceNine		DECIMAL(17,2) = 0,
							@LastYearBalanceTen			DECIMAL(17,2) = 0,
							@LastYearBalanceEleven		DECIMAL(17,2) = 0,
							@LastYearBalanceTweleve		DECIMAL(17,2) = 0,
							@CurrentDate                DATE          = NULL

					SELECT @Balance					=	[Balance], 
						   @LastYearBalanceOne		=   [LASTYEAR1], 
						   @LastYearBalanceTwo		=	[LASTYEAR2], 
						   @LastYearBalanceThree	=	[LASTYEAR3], 
						   @LastYearBalanceFour		=	[LASTYEAR4],
						   @LastYearBalanceFive		=	[LASTYEAR5],
						   @LastYearBalanceSix		=	[LASTYEAR6],
						   @LastYearBalanceSeven	=	[LASTYEAR7],
						   @LastYearBalanceEight	=	[LASTYEAR8],
						   @LastYearBalanceNine		=	[LASTYEAR9],
						   @LastYearBalanceTen		=	[LASTYEAR10],
						   @LastYearBalanceEleven	=	[LASTYEAR11],
						   @LastYearBalanceTweleve	=	[LASTYEAR12] 
					  FROM [dbo].[Nominal] 
					 WHERE [Code]					=	@Code
			
					   SET @CurrentDate   = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](GETDATE(),   @User)), 0)

					IF(@Balance <> 0 OR 
					  (@LastYearBalanceOne <> 0 OR @LastYearBalanceTwo <> 0 OR @LastYearBalanceThree <> 0 OR @LastYearBalanceFour <> 0
					  OR @LastYearBalanceFive <> 0 OR @LastYearBalanceSix <> 0 OR @LastYearBalanceSeven <> 0 OR @LastYearBalanceEight <> 0
					  OR @LastYearBalanceNine <> 0 OR @LastYearBalanceTen <> 0 OR @LastYearBalanceEleven <> 0 OR @LastYearBalanceTweleve <> 0))
							BEGIN
								IF(@Balance <> 0)
									BEGIN
										SELECT 'Balance Outstanding'		AS [Message]
									END
								ELSE
									BEGIN
										SELECT  'Balances From Last Year'	AS [Message]
									END
							END
			ELSE
					BEGIN
							SET @deleteCount = 
							(
								SELECT COUNT(1) 
								  FROM [dbo].[Nominal] [NOM]
									   JOIN [dbo].[NominalLedger] [NOL]
								         ON [NOM].[Code] = [NOL].[Code]
								 WHERE [NOM].[Code] = @Code
							)

							IF(@deleteCount > 0)
								BEGIN
									SELECT 'Transactions Present'	 AS [Message]
								END
							ELSE
								BEGIN
									SELECT 'Delete Nominal Account'	 AS [Message]
								END
					END

				END
				IF(@Mode = 'DELETE' )
					BEGIN
							DELETE 
							  FROM [dbo].[ChequeNumbers] 
							 WHERE [BankCode]  =   @Code

							DELETE
							  FROM [dbo].[Nominal]
							 WHERE [Code]	   =   @Code

							 --Insert Into Log Table 
							INSERT 
							  INTO [dbo].[Log]       					
							    (
								   [Date], 
								   [User], 
								   [Event]
							    )
							VALUES            
							    (
								   @CurrentDate,
								   @User, 
								   'Delete Nominal ' + @Code
							     )
							INSERT 
							  INTO [dbo].[Log]       					
							    (
								   [Date], 
								   [User], 
								   [Event]
							    )
							VALUES            
								(
								   @CurrentDate,
								   @User, 
								   'Delete ChequeNumbers of ' + @Code
								)
						    SELECT '1' AS [Message]
					END
   	       COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH
  SET NOCOUNT OFF
END
GO

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

GO
CREATE PROCEDURE [dbo].[KAAS_DeleteNominalBudget]
	(
		@RecordId DECIMAL
	)
AS
/*******************************************************************************************************
* Delete Nominal Budget                                                                                * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_DeleteNominalBudget]        								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-27   Revathy D         Created                                                               *
* 2022-03-01   Balamurugan C     Modified - Handled TCL Statements   and formatting                    *
 *******************************************************************************************************/

BEGIN
 SET NOCOUNT ON  
	BEGIN TRY
        BEGIN TRAN
			 DELETE 
			   FROM [dbo].[NominalBudgets] 
			  WHERE [RECORDID] =  @RecordId 
	   	       
		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
			DECLARE @ErrorMsg      NVARCHAR(4000), 
				    @ErrorSeverity INT,
				    @ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

	      RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH
 SET NOCOUNT OFF


 END


 GO


IF OBJECT_ID(N'KAAS_DeleteSAMAccruals', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_DeleteSAMAccruals]
END
GO
CREATE PROCEDURE 
	   [dbo].[KAAS_DeleteSAMAccruals]
 (
	@RecordId    INT
 )
AS 
/*******************************************************************************************************
* [dbo].[KAAS_DeleteSAMAccruals]                                                                          *
* Description: Used to delete accrual detail                                                             *					  
* Modification History:                                                                                *
* 2021-08-04   Revathy D        Created							                                       *      
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON  
    BEGIN
        DELETE FROM [dbo].[Accruals] 
		      WHERE [RECORDID] = @RecordId
    END   
 SET NOCOUNT OFF
END 

GO




IF EXISTS (SELECT TOP 1 1 
           FROM   sys.[objects] SO 
           WHERE  SO.[name] = N'KAAS_DeleteSupplierLedger' 
                  AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_DeleteSupplierLedger] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_DeleteSupplierLedger] 
	   (
			@RecordId INT,
			@Result	  TINYINT OUTPUT
	   ) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  * Used to delete the supplier ledger                                                                   *
  * Stored Procedure Name: [dbo].[KAAS_DeleteSupplierLedger]										     * 
  * Modification History:                                                                                *
  * 2021-07-07 Natarajan S        Created																 *
  * 2022-02-28 Balamurugan.C      Modified - Handled TCL Statements                                      *      
   *******************************************************************************************************/
  BEGIN 
	SET NOCOUNT ON
	   BEGIN TRY
		 BEGIN TRAN

			DELETE 
			  FROM [dbo].[SupplierLedger]
			 WHERE [RecordId]=@RecordId
			
			   SET @Result = 1

		 COMMIT TRAN

		END TRY
		BEGIN CATCH
			DECLARE @ErrorMsg      NVARCHAR(4000), 
					@ErrorSeverity INT,
					@ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

		  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END  
		END CATCH
	SET NOCOUNT OFF
  END 

GO 




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

CREATE PROCEDURE [dbo].[KAAS_DeleteSupplierLedgerAllocation] (
       @KeyId    INT,
       @Result   TINYINT OUTPUT)
AS
  /*******************************************************************************************************
  * Used to delete a single supplier ledger allocation                                                   *
  * Stored Procedure Name: [dbo].[KAAS_DeleteSupplierLedgerAllocation]                                   *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-03-26   Natarajan S     Created                                                                 *
  * 2022-02-28   Balamurugan.C   Modified - Handled TCL Statements                                       *
  * 2023-10-19   Revathy.D       Modified - Added Type 'B' to the existing condition (Ticket id:17256)   *
  * 2024-01-30   John Ginnane    #17689 - Delete now updates figures correctly and refactored code       *
  ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    -- Make sure record exists
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Allocations] AS [ALO]
                    WHERE [ALO].[KEYID] = @KeyId)
    BEGIN
        SET @Result = 0
        RETURN
    END

    BEGIN TRY
        BEGIN TRANSACTION

        DECLARE @BILLRECORDID    INT
        DECLARE @PAYMENTRECORDID INT
        DECLARE @VALUE           DECIMAL(17, 2)
        DECLARE @AllNo           INT

        SELECT @BILLRECORDID    = ISNULL([BIL].[RECORDID], 0),
               @PAYMENTRECORDID = ISNULL([PAY].[RECORDID], 0),
               @VALUE           = ISNULL([ALO].[VALUE], 0),
               @AllNo           = ISNULL([ALO].[AllNo], 0)
          FROM [dbo].[Allocations] AS [ALO]
               LEFT OUTER JOIN [dbo].[SupplierLedger] AS [BIL]
                            ON [ALO].[BATCHNO] = [BIL].[BATCHNO]
                           AND [ALO].[PREF]    = [BIL].[PREF]
               LEFT OUTER JOIN [dbo].[SupplierLedger] AS [PAY]
                            ON [ALO].[ABATCHNO] = [PAY].[BATCHNO]
                           AND [ALO].[OPREF]    = [PAY].[PREF]
         WHERE [ALO].[KEYID] = @KeyId

        UPDATE [SPL]
           SET [SPL].[OSValue] =  CASE WHEN [SPL].[ORIGINAL] > 0 -- This is how we know whether to subtract or add the allocation value, according to original code
                                            THEN [SPL].[OSValue] + @VALUE
                                       ELSE [SPL].[OSValue] - @VALUE END
           FROM [dbo].[SupplierLedger] AS [SPL]
          WHERE [SPL].[RECORDID] IN (@BILLRECORDID, @PAYMENTRECORDID)
        
        DELETE [ALO]
          FROM [dbo].[Allocations] AS [ALO]
         WHERE [ALO].[AllNo] = @AllNo

        SET @Result = 1

        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        SET @Result = 0

        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
END
GO
IF EXISTS (SELECT TOP 1 1 
           FROM   sys.[objects] SO 
           WHERE  SO.[name] = N'Kaas_DeleteUndertaking' 
                  AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[Kaas_DeleteUndertaking] 
  END 
GO 
CREATE PROCEDURE [dbo].[Kaas_DeleteUndertaking] 
	(
			 @RecordId	    INT,
			 @MatterCode    VARCHAR(20),
			 @Narrative     VARCHAR(MAX),
			 @ClientMin     VARCHAR(30),
			 @ActionId      INT,
			 @DiaryMessage  VARCHAR(MAX),
			 @LogMessage    VARCHAR(MAX),
			 @User          VARCHAR(30) = '',
			 @Result	    TINYINT OUTPUT
	 ) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  * Used to delete the matter ledger                                                                     *
  * Stored Procedure Name: [dbo].[Kaas_DeleteUndertaking]	115,'000001/0000','test','20.00',7489,       *
                           'test','test',0											                     * 
  * Modification History:                                                                                *
  * 2021-04-12 Natarajan S        Created																 *
  * 2022-03-08 Balamurugan.C      Modified - Handled TCL Statements and Formatting                       * 
  * 2023-10-25 Revathy.D          Modified - Added the missed param 'Handler code' to KAAS_INSERTSAMMatterLedgerComment    *         
   *******************************************************************************************************/
  BEGIN
    BEGIN TRY
		BEGIN TRAN 
			  DECLARE @CurrDate    DATETIME,
			  	      @TIMECONVERT INT;

				  SET @CurrDate    = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](GETDATE(), @User)), 0)
				  SET @TIMECONVERT = [dbo].[KAAS_ConvertTimeToClarion](GETDATE())

			   DELETE 
				 FROM [dbo].[Undertakings]
				WHERE [RECORDID]=@RecordId
				  SET @Result = 1  

				 EXEC [dbo].[KAAS_INSERTSAMMatterLedgerComment] @MatterCode,@Narrative,@ClientMin,@CurrDate,@User,@Result

			   UPDATE [dbo].[diary] 
				  SET [DATE]     =  @CurrDate,
					  [STATUS]   =  1,
					  [TEXT1]    =  @DiaryMessage
				WHERE [ACTIONID] =  @ActionId

			   INSERT 
				 INTO [dbo].[Log]
				  (   [DATE],
					  [USER],
					  [EVENT]
				  )
			   VALUES
				  (   @CurrDate,
					  @User,
					  @LogMessage
				  )
			   INSERT
				 INTO [dbo].[DesktopMessages]
				   (  [MESSAGE],
					  [HEADING],
					  [DATE],
					  [TIME],
					  [BUTTON],
					  [DURATION],
					  [NAME],
					  [FLAG],
					  [EXTRAS],
					  [EXTRAL]
				   )
			   VALUES
				   (  @LogMessage,             /*[MESSAGE]*/
					  'Undertaking Deleted',   /*[HEADING]*/
					  @TIMECONVERT,			   /*[DATE]*/
					  @TIMECONVERT,			   /*[TIME]*/
					  0,					   /*[BUTTON]*/
					  0,					   /*[DURATION]*/
					  'admin',				   /*[NAME]*/
					  0,					   /*[FLAG]*/
					  ' ',					   /*[EXTRAS]*/
					  0						   /*[EXTRAL]*/
				   )

		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH
 END
GO


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

CREATE PROCEDURE
       [dbo].[KAAS_ExcludeEFTDetail]
      (
		@BATCHNO      VARCHAR(20)
	  )
AS
/*************************************************************************************************************                                                *
 * Modification History                                                                                      *
 * 2024-03-19   Ghayathri S.V     Created																     *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

UPDATE BatchH SET EFTYorN = 'N' WHERE BatchNo = @BATCHNO 

SET NOCOUNT OFF

END
GO




IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_FetchBankReconciliationStatement' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_FetchBankReconciliationStatement] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_FetchBankReconciliationStatement]
	(
		@RecNo      INT         = 0,
		@Mode		VARCHAR(15) = ''
	)
AS
/*******************************************************************************************************
* Fetch the Bank Reconciliation Statement Records													   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_FetchBankReconciliationStatement]   			                   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-31    Balamurugan C        Created                                                           *
* 2022-02-08    Balamurugan C        Modified - Added Bank Complete Transaction Data                   *
* 2022-02-08    Balamurugan C        Modified - Added Undo Recon Details                               *
*******************************************************************************************************/
BEGIN
	SET NOCOUNT ON;
	IF(@Mode = 'GRID')
		BEGIN
			SELECT [RecNo],
				   RTRIM([BankAc]) AS [BankAc],
				   [RecDate],
				   [DateComplete],
				   [OpeningBalance],
				   [Lodgements],
				   [Cheques],
				   [LastRec],
				   [OsLodgements]
			  FROM [dbo].[BankRecHistory] WITH(NOLOCK)
			 WHERE [RecNo] <> 0
		END
	IF(@Mode = 'BYRECON')
		BEGIN
			SELECT [RecNo],
				   RTRIM([BankAc])	 AS [BankAc],
				   [RecDate],
				   [DateComplete],
				   [LastRec],
				   RTRIM([Currency]) AS [Currency],
				   [OpeningBalance],
				   [Lodgements],
				   [Cheques],
				   [OsLodgements],
				   [OsCheques],
				   [BankBal],
				   [ClosingBal],
				   [Diff]
		      FROM [dbo].[BankRecHistory] WITH(NOLOCK)
		     WHERE [RecNo] = @RecNo

			SELECT RTRIM([BCT].[BankAc]) AS [BankAc],
				   RTRIM([BCT].[Type])	 AS [Type],
				   [BCT].[Date],
				   RTRIM([BCT].[Ref])    AS [Ref],
				   [BCT].[Batch],
				   [BCT].[Pref],
				   RTRIM([BCT].[Narr])	 AS [Narr],
				   [BCT].[Value],
				   [BCT].[OsRecNo],
				   [BCT].[RecNo],
				   RTRIM([BCT].[Ticked]) AS [Ticked],
				   [RecordId],
				   [BCT].[NomTransId]
			  FROM [dbo].[BankRecCompleteTrans] [BCT]
			 WHERE [BCT].[RecNo] = @RecNo
		END
	IF(@Mode = 'UNDORECON')
		BEGIN
		    SELECT [RecNo],
		   	       RTRIM([BankAc]) AS [BankAc],
		   	       [RecDate],
				   [NOL].[Desc]    AS [BankDesc]
		      FROM [dbo].[BankRecHistory] WITH(NOLOCK)
			  JOIN [dbo].[Nominal] [NOL]
			    ON [NOL].[Code] = RTRIM([BankAc])
		     WHERE [DateComplete] IS NULL
		END
	SET NOCOUNT OFF;
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_FetchSAMBankReconHistory' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_FetchSAMBankReconHistory] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_FetchSAMBankReconHistory]
	( 
		@BankCode		   VARCHAR(10)  = '',
		@Mode			   VARCHAR(20)  = '',
		@HandlerCode       VARCHAR(10)  = ''
	)
AS
  /*******************************************************************************************************
  * Bank Reconciliation -Browse Forward Previous Reconciliation Details                                  * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_FetchSAMBankReconHistory]   			            		     *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2022-01-17    Balamurugan C        Created                                                           *
  *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON;
		IF(@Mode = 'ReconDetails')
			BEGIN
				SELECT ROW_NUMBER() OVER(ORDER BY [BankAc] ASC) AS [RowNum],
					   [RecNo]		                            AS [RecNo],
					   RTRIM([BankAc])                          AS [BankAc],
					   [dbo].KEYHM_FNConvertUTCDateToTargetTimeZone([RecDate], @handlerCode)      AS [RecDate],
					   [dbo].KEYHM_FNConvertUTCDateToTargetTimeZone([DateComplete], @handlerCode) AS [DateComplete],
					   [LastRec]	                            AS [LastRec],
					   RTRIM([Currency])	                    AS [Currency],
					   [OpeningBalance]                         AS [OpeningBalance],
					   [Lodgements]                             AS [Lodgements],
					   [Cheques]                                AS [Cheques],
					   [OsLodgements]                           AS [OsLodgements],
					   [OsCheques]                              AS [OsCheques],
					   [BankBal]                                AS [BankBal],
					   [ClosingBal]                             AS [ClosingBal],
					   [Diff]                                   AS [Diff]
				  FROM [dbo].[BankRecHistory]
				 WHERE [RecNo]		   = 0
				  AND  RTRIM([BankAc]) = @BankCode
			END
			IF(@Mode = 'OutstadingTrans')
			BEGIN
				SELECT RTRIM([BankAc])	AS [BankAc],
					   RTRIM([Type])    AS [Type],
					   [dbo].KEYHM_FNConvertUTCDateToTargetTimeZone([Date], @handlerCode) AS [Date],
					   RTRIM([Ref])		AS [Ref],
					   [Batch]          AS [Batch],
					   [Pref]           AS [Pref],
					   RTRIM([Narr])    AS [Narr],
					   [Value]          AS [Value],
					   [RecNo]          AS [RecNo],
					   [RecordId]       AS [RecordId]      
				  FROM [dbo].[BankRecOutstandingTrans]
				 WHERE RTRIM([BankAc]) = @BankCode
				   AND [RecNo]		   = 0
			END
	SET NOCOUNT OFF;
END
GO

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

CREATE PROCEDURE
       [dbo].[KAAS_FetchContacts]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Code',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
* This procedure is used To Fetch Contacts for Browse Contacts page					*
* CaseContacts AND CaseAssociateTypes .												*
*                                                                                   *
* Stored Procedure Name	: [dbo].[KAAS_FetchContacts]        						*
*                                                                                   *
* Modification History	:                                                           *
* 2021-07-14	Prabhu V		Created	
* 2022-07-14   Ghayathri S.V	Modified to implement dynamic sql query to fetch sort
								and search datas 
* 2023-05-05   Revathy D     	Added address field in the search datas             *
 ************************************************************************************/
BEGIN
DECLARE		@sql		      NVARCHAR(max)
DECLARE	    @search		      NVARCHAR(500) = ''
DECLARE		@offset		      INT = @PageSize * (@PageNumber -1)




SET			@sql =		'SELECT DISTINCT
								[Con].[Code], 
								[Con].[Name], 
								[Con].[Address], 
								[Con].[Principal], 
								[Con].[FE], 
								[Con].[Client], 
								[Con].[Nation], 
								[Con].[ClientGroup], 
								[Con].[OpenMatters], 
								[Con].[StartDate], 
								[Con].[BillBal], 
								[Con].[OutlayBal], 
								[Con].[ClientCur], 
								[Con].[ClientDep], 
								[Con].[RSINo], 
								[Con].[OtherRef], 
								[Con].[OpsisRef], 
								[Con].[ContactNo], 
								[Con].[CompBillOnOff], 
								[Con].[TaxType] 
						   FROM [dbo].[contacts] [Con]  
	                      WHERE	[Con].[Client] = ''Y''' +  
		                   'AND  ( 
									[Con].[Code]    LIKE' + '''%' + @SearchString + '%' + '''' +
									'OR
									[Con].[Name]      LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[Con].[Address]      LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[Con].[Nation]    LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[Con].[OtherRef]  LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[Con].[BillBal]   LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[Con].[Principal]   LIKE ' + '''%' + @SearchString + '%' + '''' +
									
								 ')
					 ORDER BY '  +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET '  +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT '  +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

EXEC Sp_executesql @sql

						SELECT      COUNT(*)  'TotalRecord'
						  FROM      [dbo].[contacts] [Con]  
						 WHERE      [Con].[Client] = 'Y' 
						   AND		( 
										[Con].[Code]      LIKE '%' + @SearchString + '%' 
										OR
										[Con].[Name]      LIKE '%' + @SearchString + '%'
										OR
										[Con].[Address]      LIKE '%' + @SearchString + '%'
										OR
										[Con].[Nation]    LIKE '%' + @SearchString + '%' 
										OR
										[Con].[OtherRef]  LIKE '%' + @SearchString + '%' 
										OR
										[Con].[BillBal]   LIKE '%' + @SearchString + '%' 
										OR
										[Con].[Principal]   LIKE '%' + @SearchString + '%' 
										
									 )
END

GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_FetchCrystalReportSetupDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_FetchCrystalReportSetupDetails] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_FetchCrystalReportSetupDetails]
AS
/*******************************************************************************************************
* Fetch all Crystal Report and Relevent Report Group Details                                           *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_FetchCrystalReportSetupDetails]   			            	   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-03-10    Balamurugan C        Created                                                           *
* 2023-02-21    Nithyanandham M      Modified-Table name has been updated to newly created one         * 
*******************************************************************************************************/
BEGIN
		SET NOCOUNT ON

			DECLARE @TempReportTable TABLE
				(
					[ReportId]    DECIMAL,
					[Name]        VARCHAR(500),
					[FileName]    VARCHAR(500),
					[GroupName]   VARCHAR(500),
					[Notes]       VARCHAR(5000),
					[Synopsis]    VARCHAR(5000),
					[Report_Type] VARCHAR(10),
					[Created_On]  DATETIME
				)
		INSERT INTO @TempReportTable
				(
					[ReportId],  
					[Name],      
					[FileName],
					[Notes],
					[Synopsis],
					[Report_Type],
					[Created_On],
					[GroupName]
				)
				(
			 SELECT [CRR].[ReportId],
					[CRR].[Name],
					[CRR].[FileName],
					[CRR].[Notes],
					[CRR].[Synopsis],
					[CRR].[Report_Type],
					[CRR].[Created_On],
					[CGP].[GroupName] 
			   FROM [dbo].[KaaS_CRReport] [CRR]
			   JOIN [dbo].[KaaS_CRReportGroup] [CRG]
				 ON [CRG].[Reportid] = [CRR].[Reportid]
			   JOIN [dbo].[KaaS_CRGroup] [CGP]
				 ON [CGP].[groupid]  = [CRG].[groupid]
				)
			 SELECT [ReportId]		AS [ReportId],
					[Name]			AS [Name],
					[FileName]		AS [FileName],
					[Notes]			AS [Notes],
					[Synopsis]		AS [Synopsis],
					[Report_Type]	AS [ReportType],
					[Created_On]	AS [CreatedOn],
					STUFF((SELECT ', ' + CAST([GroupName] AS VARCHAR(MAX)) [text()]
							 FROM @TempReportTable 
							WHERE [ReportId] = [TMP].[ReportId]
					 FOR XML PATH(''), TYPE)
					.value('.','NVARCHAR(MAX)'),1,2,' ') [GroupName]
			   FROM @TempReportTable [TMP]
		   GROUP BY [ReportId],
					[Name],
					[FileName],
					[Notes],
					[Synopsis],
					[Report_Type],
					[Created_On]
		   ORDER BY [Name]

		SET NOCOUNT OFF
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_FetchNominalLedgerByCode' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_FetchNominalLedgerByCode] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_FetchNominalLedgerByCode]
	(
		@Code      VARCHAR(10) = ''
	)
AS
/*******************************************************************************************************
* Fetch Nominal Ledger by Code where ReconNo is 0											           *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_FetchNominalLedgerByCode]   			                           *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-02-01    Balamurugan C        Created                                                           *
*******************************************************************************************************/
BEGIN
  SET NOCOUNT ON

	SELECT [NML].[Code],
		   [NML].[Branch],
		   [NML].[BatchNo],
		   [NML].[Pref],
		   [NML].[Date],
		   [NML].[Ref],
		   [NML].[Narr],
		   [NML].[Matter],
		   [NML].[Supp],
		   [NML].[Value],
		   [NML].[EntryDate],
		   [NML].[RecordId],
		   [BAH].[Type]
	  FROM [dbo].[NominalLedger] [NML]
 LEFT JOIN [dbo].[BatchH] [BAH]
	    ON [BAH].[BatchNo] = [NML].[BatchNo]
	 WHERE [NML].[Code] = @Code
	   AND [NML].[RecNo] = 0 
  ORDER BY [NML].[Code] ASC,
           [NML].[Date] ASC,
		   [NML].[RecordId] ASC

	SELECT [Balance]
	  FROM [dbo].[Nominal]
	 WHERE [Code] = @Code

  SET NOCOUNT OFF

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_FetchSAMBankReconValidationDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_FetchSAMBankReconValidationDetails] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_FetchSAMBankReconValidationDetails]
	( 
		@BankAc	           VARCHAR(10)   = '',
		@Mode              VARCHAR(25)   = ''
	)
AS
/*******************************************************************************************************
* Bank Reconciliation -  Validation for Start Bank Reconcilation                                       *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_FetchSAMBankReconValidationDetails]   			                       *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-21    Balamurugan C        Created                                                           *
*******************************************************************************************************/
BEGIN
	IF(@Mode='FetchReconNo')
		BEGIN
			SELECT [RecNo]   AS [RecNo],
				   [RecDate] AS [RecDate]
			  FROM [dbo].[BankRecHistory]
			 WHERE [BankAc]   = @BankAc
			   AND [DateComplete] IS NULL
		END
	IF(@Mode='PendingRecon')
		BEGIN

			IF EXISTS
			(
				SELECT TOP 1 1
				  FROM [dbo].[BankRecHistory] 
				 WHERE [BankAc]   = @BankAc
				   AND [RecNo]    = 0
			)
			BEGIN
				IF EXISTS
				(
					SELECT TOP 1 1 
					  FROM [dbo].[BankRecHistory] 
					 WHERE [BankAc]   = @BankAc
					   AND [DateComplete] IS NULL
				)
					BEGIN
						SELECT 'Y'	AS [PendingStatus]
					END
				ELSE
					BEGIN
						SELECT 'N'  AS [PendingStatus]
					END
			END
			ELSE
				BEGIN
					SELECT 'O'	AS [PendingStatus]
				END
		END

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_FetchSAMDebtorsAllocatedValue' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_FetchSAMDebtorsAllocatedValue] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_FetchSAMDebtorsAllocatedValue]
	    (
			@BatchNo	INT  = 0,
			@Pref		INT	 = 0
		)
AS
/*******************************************************************************************************
* Get Debtors Ledger Alllocated and Original Value	                                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_FetchSAMDebtorsAllocatedValue]	        	     			   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-08    vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN
	SET NOCOUNT ON;

		 SELECT [Original],
				[OsValue] 
		   FROM [dbo].[DebtorsLedger]
		  WHERE [BatchNo] = @BatchNo
			AND [Pref]    = @Pref

	SET NOCOUNT OFF;
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_FetchSAMPaymentDropDownList]
	(
		@Mode		VARCHAR(15)
	)

AS

/*******************************************************************************************************
* Fetches Payment - Enter Cheque all dropdown values                                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_FetchSAMPaymentDropDownList]   								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2024-01-31    Balamurugan.C         Created                                                          *
* 2024-03-20    Ghayathri.S.V         Modified : Included code to fetch the client contact details     *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

IF(@Mode='EnterPayment')

BEGIN
/*Bank Details*/

		SELECT RTRIM([NOM].[Code]) 				AS [Code],
			   RTRIM([NOM].[Desc]) 				AS [Desc],
			   [NOM].[Type], 
			   [NOM].[Pb], 
			   [NOM].[Seq], 
			   [NOM].[Clientac]					AS [Client], 
			   [NOM].[Deposityn]				AS [Deposit], 
			   [NOM].[Deposittype]				AS [DepType], 
			   [NOM].[BankBranch],
			   ISNULL([NOM].[IBAN],'')			AS [Iban],
			   ISNULL([NOM].[ACCOUNTNAME],'')	AS [AccountName],
			   ISNULL([NOM].[ACCOUNTNO],'')		AS [AccountNumber],
			   ISNULL([NOM].[SORTCODE],'')		AS [SortCode],
			   ISNULL([NOM].[BIC],'')			AS [Bic],
			   ISNULL([NOM].[Branch],'')		AS [Branch],
			   NOM.[LASTNO]						AS [LastNumber]
		 FROM [dbo].[Nominal] [NOM] 
		WHERE [NOM].[TYPE] = 'BANK' 
		  AND [NOM].[RETIRED] <> 'Y' 
	 ORDER BY [NOM].[CODE] ASC


 /*Narratives*/

	   SELECT RTRIM(ISNULL([NAR].[CODE], ''))      AS [Code],
			 RTRIM(ISNULL([NAR].[NARRATIVE], ''))  AS [Narrative]
		FROM [dbo].[Narratives] AS [NAR]
	 ORDER BY RTRIM(ISNULL([NAR].[CODE], '')) ASC

/*All Supplier List*/

	   SELECT [Code],
		      [Name],
		      [Address],
		      [Nominal],
		      [Phone],
		      ISNULL([EmailAddress],'') AS [EmailAddress],
		      [TaxNo],
		      [ServiceCode],
		      ISNULL([VATNo],'')		   AS [VATNo],
		      [DeftpStatus],			   
		      ISNULL([BankName],'')		   AS [BankName],
		      ISNULL([BankAddress],'')	   AS [BankAddress],
		      ISNULL([BankSortCode],'')    AS [BankSortCode],
		      ISNULL([BankAccNo],'')	   AS [BankAccNo],
		      ISNULL([Iban],'')			   AS [Iban],
		      ISNULL([Bic],'')			   AS [Bic],
		      ISNULL([BankType],'')		   AS [BankType],
		      ISNULL([EFTEmailAddress],'') AS [EFTEmailAddress],
		      [Retired],
			  [TPBAL]					   AS [ThirdPartyBalance],
			  [BALANCE]					   AS [Balance],
			  [BALANCEFWD]				   AS [BalanceFwd]
		 FROM [dbo].[Suppliers]
	 ORDER BY [Code] ASC

/*EFT Alert Settings*/

 SELECT TOP 1 [EFTYN] AS [EFTAlert]
	     FROM [dbo].[EFTDetails]

/*Branch Details*/
	   SELECT RTRIM([BRANCHCODE])	 AS [Code],
		      RTRIM([DESCRIPTION])   AS [Description]
	     FROM [dbo].[Branch]

/*Client Contact Details*/
	   SELECT [BIC]	 AS [Bic],
		      [IBAN]   AS [Iban],
			  [BankSortCode]   AS [BankSortCode],
			  [BankAccNo]   AS [BankAccNo],
			  [Code]	 AS [Code],
			  [Name]	 AS [Name]
	     FROM [dbo].[Contacts]
END
ELSE
BEGIN

		/*Vat Codes*/

		 SELECT	[VAC].[CODE] AS [Vat],
				[VAC].[RATE] AS [Rate]     
		   FROM [dbo].[VATCodes] [VAC]
		  WHERE [VAC].RETIRED <> 'Y'
	   ORDER BY [VAC].[CODE] ASC

	   /*Outlay Codes*/

		 SELECT RTRIM([OCD].[CODE]) AS [Code],
				RTRIM([OCD].[DESCRIPTION]) AS [Description]
		   FROM [dbo].[OutlayCode] [OCD]
	   ORDER BY [OCD].[CODE] ASC


/*All Supplier List*/

	   SELECT [Code],
		      [Name],
		      [Address],
		      [Nominal],
		      [Phone],
		      ISNULL([EmailAddress],'') AS [EmailAddress],
		      [TaxNo],
		      [ServiceCode],
		      ISNULL([VATNo],'')		   AS [VATNo],
		      [DeftpStatus],			   
		      ISNULL([BankName],'')		   AS [BankName],
		      ISNULL([BankAddress],'')	   AS [BankAddress],
		      ISNULL([BankSortCode],'')    AS [BankSortCode],
		      ISNULL([BankAccNo],'')	   AS [BankAccNo],
		      ISNULL([Iban],'')			   AS [Iban],
		      ISNULL([Bic],'')			   AS [Bic],
		      ISNULL([BankType],'')		   AS [BankType],
		      ISNULL([EFTEmailAddress],'') AS [EFTEmailAddress],
		      [Retired],
			  [TPBAL]					   AS [ThirdPartyBalance],
			  [BALANCE]					   AS [Balance],
			  [BALANCEFWD]				   AS [BalanceFwd]
		 FROM [dbo].[Suppliers]
	 ORDER BY [Code] ASC

/*Fee Earners List*/

	   SELECT [FEE].[Code],
			  [FEE].[Name],
			  [FEE].[Branch],
			  [FEE].[Nominal]
		 FROM [dbo].[FeeEarnerCodes] [FEE] 
		WHERE [FEE].[Retired] <> 'Y' 
	 ORDER BY [FEE].[Code] ASC

/*Nominal List*/

	SELECT [NOM].[CODE] AS [Code],
		   [NOM].[DESC] AS [Description],
		   [NOM].[TYPE] AS [Type]
	  FROM [dbo].[Nominal] [NOM] 
  ORDER BY [NOM].[CODE] ASC

 /*Narratives*/

	   SELECT RTRIM(ISNULL([NAR].[CODE], ''))      AS [Code],
			  RTRIM(ISNULL([NAR].[NARRATIVE], ''))  AS [Narrative]
		 FROM [dbo].[Narratives] AS [NAR]
	 ORDER BY RTRIM(ISNULL([NAR].[CODE], '')) ASC

END

SET NOCOUNT OFF

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetApprovedChequeRequisitionDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetApprovedChequeRequisitionDetails] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_GetApprovedChequeRequisitionDetails]
		(
			@Mode   VARCHAR(5) = '',
			@ReqNo	INT		   = 0
		)
AS
/*******************************************************************************************************
* Fetches the Approved Cheque Reqisition Details                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[dbo].[KAAS_GetApprovedChequeRequisitionDetails]      				   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-13    Balamurugan.C        Created                                                           *
* 2021-10-22    Balamurugan.C        Modified - Added Third Party Column and handled fetch             *
                                                the record based on grid mode and single record mode 
* 2022-06-08    Ghayathri.S.V        Modified - Added outlay balance and current client balance columns
											    in select statement while fetching the records.
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
			SELECT   
				   [CRH].[ReqNo]		AS [ReqNo],
				   [CRH].[Date]			AS [Date],
				   [CRH].[Who]			AS [Who],
				   [CRH].[Bank]			AS [Bank],
				   [CRH].[Value]		AS [Value],
				   [CRH].[Narrative]	AS [Narrative],
				   [CRH].[Payee]		AS [Payee],
				   [CRH].[Status]		AS [Status],
				   [CRH].[ReturnReason]	AS [ReturnReason],
				   [CRH].[FeeEarner]	AS [FeeEarner],
				   [CRH].[Supply]		AS [Supply],
				   [CRH].[OutlayCode]	AS [OutlayCode],
				   [CRH].[EFTYorN]		AS [EFTYorN],
				   [CRH].[ThirdParty]   AS [ThirdParty],
				   [CRD].[ReqNo]		AS [DetailsReqNo],
				   [CRD].[Matter]		AS [Matter],
				   [CRD].[Nominal]		AS [Nominal],
				   [CRD].[RecordID]		AS [RecordID],
				   [MAT].[Code]			AS [MatterCode],
				   [MAT].[ClientCode]	As [ClientCode], 
				   [MAT].[FeCode]		AS [MatterFeeEarnerCode],
				   [MAT].[Dept]			AS [Dept],
				   [MAT].[Wtype]		AS [Wtype], 
				   [MAT].[Branch]		AS [Branch],
				   [MAT].[FileNum]		AS [FileNum],
				   [MAT].[ThirdPart]	AS [ThirdPart],
				   [MAT].[ThPartSol]	AS [ThPartSol],
				   [MAT].[OldRef]		AS [OldRef],
				   [MAT].[Pcode]		AS [Pcode],
				   [MAT].[PFeCode]		AS [PFeCode],
				   [MAT].[User1]		AS [User1], 
				   [MAT].[User2]        AS [User2], 
				   [MAT].[User3]        AS [User3], 
				   [MAT].[FileColour]	AS [FileColour], 
				   [MAT].[OUTFileNo]	AS [OUTFileNo], 
				   [MAT].[Closed]		AS [Closed],
				   [MAT].[OutlayBal]    AS [OutlayBal],
				   [MAT].[ClientCurBal] AS [ClientCurBal]
			  FROM [dbo].[ChequeRequisitionHeader] [CRH]
   LEFT OUTER JOIN [dbo].[ChequeRequisitionDetail] [CRD] 
			    ON [CRH].[ReqNo]= [CRD].[ReqNo] 
   LEFT OUTER JOIN [dbo].[Matters] [MAT] 
			    ON [CRD].[Matter]= [MAT].[Code] 
			 WHERE [CRH].[Status] = '1'
			   AND [CRH].[ReqNo] = CASE WHEN @Mode='All' THEN [CRH].[ReqNo] ELSE @ReqNo END 
		  ORDER BY [CRH].[Status] ASC, 
		           [CRH].[ReqNo] ASC

	SET NOCOUNT OFF
END
GO




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

AS
/*******************************************************************************************************
* Fetches the case associate types                                                                     * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetAssociatesTypes]   							     		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-09    Revathy D        Created                                                               *
 *******************************************************************************************************/

BEGIN
 SET NOCOUNT ON 
	SELECT  
		RTRIM(ISNULL([ACT].[CODE],''))     AS [Code], 
		[ACT].[DESCRIPTION]                AS [Description]
	FROM 
		[dbo].[AssociateTypes] [ACT] 
	ORDER BY  
		[ACT].[CODE] ASC

 SET NOCOUNT OFF
END

GO





IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KAAS_GetBankDetails]') AND type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[KAAS_GetBankDetails]
END
GO
/****** Object:  StoredProcedure [dbo].[KAAS_GetBankDetails]    Script Date: 23-03-2021 16:19:44 ******/
CREATE PROCEDURE [dbo].[KAAS_GetBankDetails]

AS

/*******************************************************************************************************
* Fetches the Bank details                                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetBankDetails]   											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-03-23    Revathy D        Created                                                               *
* 2021-08-09    Vinodhkumar M    Modified - columns added                                              *
* 2021-09-09    Balamurugan      Modified - columns added _branch 
* 2022-10-06   Ghayathri        Modified - columns added - LastNumber                                 *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

SELECT  
  RTRIM(NOM.[Code]) 			AS [Code],
  RTRIM(NOM.[Desc]) 			AS [Desc],
  NOM.[Type], 
  NOM.[Pb], 
  NOM.[Seq], 
  NOM.[Clientac]				AS [Client], 
  NOM.[Deposityn]				AS [Deposit], 
  NOM.[Deposittype]				AS [DepType], 
  NOM.[BankBranch],
  ISNULL(NOM.[IBAN],'')			AS [Iban],
  ISNULL(NOM.[ACCOUNTNAME],'')	AS [AccountName],
  ISNULL(NOM.[ACCOUNTNO],'')	AS [AccountNumber],
  ISNULL(NOM.[SORTCODE],'')		AS [SortCode],
  ISNULL(NOM.[BIC],'')			AS [Bic],
  ISNULL(NOM.[Branch],'')		AS [Branch],
  NOM.[LASTNO]		            AS [LastNumber]
FROM 
  dbo.[Nominal] NOM 
WHERE NOM.[TYPE] = 'BANK' 
  AND NOM.[RETIRED] <> 'Y' 
ORDER BY  
  NOM.[CODE] ASC

SET NOCOUNT OFF

END


GO



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

CREATE PROCEDURE [dbo].[KAAS_GetBatchByNo] (
                  @BatchNo     INT,
                  @handlerCode VARCHAR(10) = NULL
                  )
AS
/*******************************************************************************************************
* Fetches the batch details of unposted payments                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetBatchByNo]   												   *
*                                                                                                      *
* Modification History:                                                                                *
* 03 May  2021    Natarajan S        Created														   *
* 13 July 2021    Natarajan S        Modified - Formatted as per coding standard					   * 
* 16 August 2021  Vinodhkumar M      Modified - Branch and ClientBank fields is added    			   *         
* 03 Dec 2021     Vinodhkumar M      Modified - Payment and clear date fields is added    			   *   
* 07 Dec 2021     Vinodhkumar M      Modified - CorrectCopy,Postfwd,invcr fields is added			   *
* 03 Jan 2022     Ghayathri.S.V      Modified - Added Subtot Row while selecting data                  * 
* 11 Jan 2021     Vinodhkumar M      Modified - writedown,writebackhrs,writebackValue fields is added  *
* 04 Feb 2022     Balamurugan C      Modified - Added Single Line Column                               * 
* 21 Nov 2022     Ghayathri.S.V      Modified - Added Template Column while selecting data             *    
 *******************************************************************************************************/
BEGIN
 SET NOCOUNT ON
  SELECT [BAT].[BatchNo]			                                                      AS [BatchNo],
		 [BAT].[Type]			                                                          AS [Type],
		 [BAT].[Code]			                                                          AS [Code],
		 [BAT].[Ref]				                                                      AS [Ref],
		 [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[Date], @handlerCode)       AS [Date],
		 [BAT].[BRANCH]																	  AS [Branch],
		 [BAT].[CLIENTBANK]																  AS [ClientBank],
		 [BAT].[Matter]			                                                          AS [Matter],
		 [BAT].[Supp]			                                                          AS [Supp],
		 [BAT].[Narr]			                                                          AS [Narr],
		 [BAT].[Value]			                                                          AS [Value],
		 [BAT].[Posted]			                                                          AS [Posted],
		 [BAT].[PerNo]			                                                          AS [PerNo],
		 [BAT].[Year]			                                                          AS [Year],
		 [BAT].[EntryDate]		                                                          AS [EntryDate],
		 [BAT].[RecNo]			                                                          AS [RecNo],
		 [BAT].[ChequeReqNo]	                                                          AS [ChequeReqNo],
		 [BAT].[Pref]			                                                          AS [Pref],
		 [BAT].[Payee]			                                                          AS [Payee],
		 [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[ENTRYDATE], @handlerCode)  AS [ENTRYDATE],
		 [HAN].[NAME]		                                                              AS [UserCode],
		 [BAT].[EFTYorN]		                                                          AS [EFTYorN],
		 [BAT].[EFTSent]		                                                          AS [EFTSent],
		 [BAT].[ClientAc]		                                                          AS [ClientAc],
		 [BAT].[ThirdParty]		                                                          AS [Thirdparty],
		 [BAT].[PayClient]		                                                          AS [PayClient],
		 [BAT].[OnceOffPayment]	                                                          AS [OnceOffPayment],
		 [BAT].[ClientCode]		                                                          AS [ClientCode],
		 [BAT].[PaymentMethod]															  AS [PaymentMethod],
		 [BAT].[ClearedDate]															  AS [ClearedDate],
		 [BAT].[CORRECTCOPY]															  AS [CorrectCopy],
		 [BAT].[POSTFWD]																  AS [PostFwd],
		 [BAT].[INVCR]																	  AS [Invcr],
		 [BAT].[SUBTOT]																	  AS [SubTot],
		 [BAT].[WRITEDOWN]																  AS [WriteDown],
		 [BAT].[WRITEBACKHOURS]															  AS [WriteBackHours],
		 [BAT].[WRITEBACKVALUE]															  AS [WriteBackValue],
		 [BAT].[SINGLELINE]                                                               AS [SingleLine],
		 [BAT].[TEMPLATE]																  AS [Template],
		 [BAT].[EFTFileNumber]															  AS [EFTFileNumber],
		 [BAT].[EFTFileName]															  AS [EFTFileName],
		 [BAT].[CaseAssCode]															  AS [CaseAssCode],
		 [BAT].[EFTEmailYorN]                                                             AS [EFTEmailYorN]
    FROM [dbo].[BatchH] [BAT]
	LEFT JOIN [dbo].[Handlers] [HAN]
	  ON ([HAN].[Code] = [BAT].[UserCode])
	  OR ([HAN].[NAME] = [BAT].[UserCode])
   WHERE [BAT].[BatchNo] = @BatchNo
 SET NOCOUNT OFF
END

GO

IF OBJECT_ID(N'KAAS_GetBatchDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetBatchDetails]
GO
CREATE PROCEDURE [dbo].[KAAS_GetBatchDetails]
				(@PageNumber    INT,
				 @PageSize	    INT,
				 @SearchString  VARCHAR(500) = '',
				 @SortColumn    VARCHAR(100) = 'ENTRYDATE',
				 @SortOrder     VARCHAR(100) = 'ASC',
				 @handlerCode   VARCHAR(10) = '',
				 @Type			VARCHAR(4) = '')
AS

/*******************************************************************************************************
* Fetches the batch details of unposted receipts                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetBatchDetails]   											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-03-19    Revathy D        Created                                                               *
* 2021-08-20    Vinodhkumar M    Modifed-Added branch field                                            *
* 2021-09-03    Vinodhkumar M    Modifed-Added vat total,outlay total,fee total                        *
* 2021-11-08    Vinodhkumar M    Modifed-Added Payment method, ClearedDate		                       *
* 2021-11-11    Vinodhkumar M    Modifed-Changed Null to empty string for handlercode parameter        *
* 2022-01-06    Vinodhkumar M    Modifed-Added cost transfer awating Process Query for Receipt type    *
* 2022-03-29    Vignesh M        Modifed-Added S13 column Added         		                       *
* 2022-05-09    Vignesh M        Modified - UTC Conversion Removed                                     *
* 2022-07-14	Ghayathri.S.V	 Modified as dynamic query to implement scroll, sort and search        *
* 2024-05-13	Balamurugan.C	 Modified - Added User Code in search condition                        *
* 2024-05-22    Nithyanandham M  Modifed-Added Client Name, Matter Description Columns                 *
 *******************************************************************************************************/

BEGIN
	SET NOCOUNT ON
	DECLARE			   @sql		NVARCHAR(max),
				    @offset		INT = @PageSize * (@PageNumber -1),
			 @WhereConditon		NVARCHAR(max)

	 IF @Type = 'M'
	  BEGIN
		SET @WhereConditon = 'WHERE'
	  END
	ELSE
	  BEGIN
		SET @WhereConditon = 'WHERE [TEM].[POSTED] = ''N'''  + 'AND'
	  END

		SET			  @sql = 'DECLARE @TEMP Table 
								([BatchNo]        [int]            NOT NULL,
								 [Type]           [char](1)        NULL,
								 [Code]           [char](10)       NULL,	
								 [Ref]            [char](10)       NULL,
								 [Date]           [datetime]       NULL,
								 [Matter]         [varchar](20)    NULL,
								 [SubTotal]       [decimal](17, 2) NULL,
								 [Supp]           [char](10)       NULL,
								 [Narr]           [char](150)      NULL,
								 [Value]          [decimal](17, 2) NULL,	
								 [Posted]         [char](1)        NULL,
								 [Branch]         [varchar](3)     NULL,	
								 [PerNo]          [smallint]       NULL,
								 [Year]           [smallint]       NULL,
								 [EntryDate]      [datetime]       NULL,
								 [RecNo]          [int]            NULL,
								 [ChequeReqNo]    [int]            NULL,	
								 [UserCode]       [char](8)        NULL,
								 [Pref]           [int]            NULL,
								 [ClientAc]       [char](1)        NULL,
								 [EFT]            [char](1)        NOT NULL,
								 [ClientBank]     [char](10)       NULL,
								 [ThirdParty]     [char](1)        NULL,
								 [Payee]          [char](60)       NULL,
								 [EFTSent]        [char](1)        NOT NULL,
								 [PayClient]      [char](1)        NOT NULL,
								 [OnceOffPayment] [char](1)        NOT NULL,
								 [ClientCode]     [varchar](10)    NULL,
								 [Feetotal]		  [decimal](17, 2) NULL,
								 [Outlaytotal]	  [decimal](17, 2) NULL,
								 [VatTotal]		  [decimal](17, 2) NULL,
								 [WriteDown]      [datetime]       NULL,
								 [WriteBackHours] [decimal](7, 2)  NULL,
								 [WriteBackValue] [decimal](13, 2) NULL,
								 [CreditInvoiceNo][int]            NULL,
								 [Invcr]          [char](1)        NULL,
								 [Fee]            [varchar](10)    NULL,
								 [PaymentMethod]  [int]			   NULL,
								 [ClearedDate]    [datetime]       NULL,
								 [S13]            [char](1)        NULL,
								 [ClientName]     [varchar](80)    NULL,
								 [Description]    [varchar](200)   NULL)

							INSERT INTO @TEMP 
								 SELECT [BAH].[BatchNo], 
										RTRIM(ISNULL([BAH].[Type],'''')), 
										[BAH].[Code], 
										RTRIM(ISNULL([BAH].[Ref],'''')), 
										[BAH].[Date],  
										[BAH].[Matter], 
										[BAH].[SUBTOT],
										[BAH].[Supp], 
										[BAH].[Narr], 
										[BAH].[Value], 
										[BAH].[Posted],   
										[BAH].[Branch],
										[BAH].[PerNo], 
										[BAH].[Year],
										[BAH].[EntryDate],
										[BAH].[RecNo], 
										[BAH].[ChequeReqNo],
										[BAH].[UserCode],
										[BAH].[Pref],
										[BAH].[ClientAc],
										[BAH].[EFTYorN],
										[BAH].[CLIENTBANK],
										[BAH].[ThirdParty],
										[BAH].[Payee], 
										[BAH].[EFTSent], 
										[BAH].[PayClient],
										[BAH].[OnceOffPayment],
										[BAH].[ClientCode],
										[BAH].[FEETOT],
										[BAH].[OUTLAYTOT],
										[BAH].[VATTOT],
										[BAH].[WRITEDOWN],
										[BAH].[WRITEBACKHOURS],
										[BAH].[WRITEBACKVALUE],
										[BAH].[CREDITINVOICENO],
										[BAH].[INVCR],
										[BAH].[FEE],
										[BAH].[PaymentMethod],
										[BAH].[ClearedDate],
										[MAT].[S13],
										[MAT].[ClientName],
										[Mat].[Description]
								 FROM   [dbo].[BatchH] [BAH]
							LEFT JOIN   [DBO].[matters] [MAT] ON [MAT].[Code] = [BAH].[MATTER]
								WHERE   [BAH].[TYPE] = ' + '''' +  @Type  + '''' + 

							   'BEGIN
									SELECT		  * 
									  FROM		  @TEMP [TEM] ' +
							@WhereConditon        + 
										'(
												  [TEM].[BatchNo]      LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[Ref]	       LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
											      [TEM].[Date]         LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[Value]        LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[Code]         LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[Narr]         LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[Supp]		   LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[CLIENTBANK]   LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[Matter]       LIKE' + '''%' +  @SearchString + '%' + '''' +
												  'OR 
												  [TEM].[UserCode]     LIKE' + '''%' +  @SearchString + '%' + '''' +
										  ')
	   						      ORDER BY '      +  @SortColumn + ' '  + @SortOrder + ' ' +
								   'OFFSET '      +  CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
							   'FETCH NEXT '      +  CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY;

									SELECT			COUNT(*)  ''TotalRecord''
									  FROM			@TEMP [TEM] 
									  WHERE			[TEM].[POSTED] = ''N'''  + 'AND
										  (
													[TEM].[BatchNo]      LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Ref]			 LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Date]         LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Value]        LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Code]         LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Narr]         LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Supp]		 LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[CLIENTBANK]   LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[Matter]       LIKE' + '''%' +  @SearchString + '%' + '''' +
													'OR 
													[TEM].[UserCode]    LIKE' + '''%' +  @SearchString + '%' + '''' +
										  ')
							      END'

EXEC Sp_executesql @sql
			IF @Type = 'R'
				BEGIN
					SELECT COUNT(*) AS [CostAwaitingProcessCount]
					  FROM [dbo].[CostTransGathering]
				END

SET NOCOUNT OFF

END

GO



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

CREATE PROCEDURE [dbo].[KAAS_GetBatchHeaderAndDetailByNo] (
                  @BatchNo     INT,
				  @handlerCode VARCHAR(10) = NULL
                  )
AS
/*******************************************************************************************************
* Fetches Batch Header and Detail Based on Batch Number (Common to All Batches)                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetBatchHeaderAndDetailByNo]   								   *
*                                                                                                      *
* Modification History:                                                                                *
* 01 Feb  2024    Balamurugan C        Created														   *  
 *******************************************************************************************************/
BEGIN
 SET NOCOUNT ON

 /*Batch Header*/

  SELECT [BAT].[BatchNo]			                                                      AS [BatchNo],
		 [BAT].[Type]			                                                          AS [Type],
		 [BAT].[Code]			                                                          AS [Code],
		 [BAT].[Ref]				                                                      AS [Ref],
		 [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[Date], @handlerCode)       AS [Date],
		 [BAT].[BRANCH]																	  AS [Branch],
		 [BAT].[CLIENTBANK]																  AS [ClientBank],
		 [BAT].[Matter]			                                                          AS [Matter],
		 [BAT].[Supp]			                                                          AS [Supp],
		 [BAT].[Narr]			                                                          AS [Narr],
		 [BAT].[Value]			                                                          AS [Value],
		 [BAT].[Posted]			                                                          AS [Posted],
		 [BAT].[PerNo]			                                                          AS [PerNo],
		 [BAT].[Year]			                                                          AS [Year],
		 [BAT].[EntryDate]		                                                          AS [EntryDate],
		 [BAT].[RecNo]			                                                          AS [RecNo],
		 [BAT].[ChequeReqNo]	                                                          AS [ChequeReqNo],
		 [BAT].[Pref]			                                                          AS [Pref],
		 [BAT].[Payee]			                                                          AS [Payee],
		 [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[ENTRYDATE], @handlerCode)  AS [ENTRYDATE],
		 [HAN].[NAME]		                                                              AS [UserCode],
		 [BAT].[EFTYorN]		                                                          AS [EFTYorN],
		 [BAT].[EFTSent]		                                                          AS [EFTSent],
		 [BAT].[ClientAc]		                                                          AS [ClientAc],
		 [BAT].[ThirdParty]		                                                          AS [Thirdparty],
		 [BAT].[PayClient]		                                                          AS [PayClient],
		 [BAT].[OnceOffPayment]	                                                          AS [OnceOffPayment],
		 [BAT].[ClientCode]		                                                          AS [ClientCode],
		 [BAT].[PaymentMethod]															  AS [PaymentMethod],
		 [BAT].[ClearedDate]															  AS [ClearedDate],
		 [BAT].[CORRECTCOPY]															  AS [CorrectCopy],
		 [BAT].[POSTFWD]																  AS [PostFwd],
		 [BAT].[INVCR]																	  AS [Invcr],
		 [BAT].[SUBTOT]																	  AS [SubTot],
		 [BAT].[WRITEDOWN]																  AS [WriteDown],
		 [BAT].[WRITEBACKHOURS]															  AS [WriteBackHours],
		 [BAT].[WRITEBACKVALUE]															  AS [WriteBackValue],
		 [BAT].[SINGLELINE]                                                               AS [SingleLine],
		 [BAT].[TEMPLATE]																  AS [Template],
		 [BAT].[EFTFileNumber]															  AS [EFTFileNumber],
		 [BAT].[EFTFileName]															  AS [EFTFileName],
		 [BAT].[CaseAssCode]															  AS [CaseAssCode],
		 [BAT].[EFTEmailYorN]                                                             AS [EFTEmailYorN]
    FROM [dbo].[BatchH] [BAT]
	LEFT JOIN [dbo].[Handlers] [HAN]
	  ON ([HAN].[Code] = [BAT].[UserCode])
	  OR ([HAN].[NAME] = [BAT].[UserCode])
   WHERE [BAT].[BatchNo] = @BatchNo

   /*Batch Details*/
   /*If Batch Detail Present then it will execute the select query*/

 IF (SELECT COUNT(1) FROM [dbo].[BatchDetails] WHERE [BATCHNO] = @BatchNo) > 0
	BEGIN
   	 SELECT [BTD].[BatchNo], 
			[BTD].[Type], 
			[BTD].[Code], 
			[BTD].[Pref], 
			[BTD].[Ref], 
			[dbo].KEYHM_FNConvertUTCDateToTargetTimeZone(BTD.[Date], @handlerCode)  AS [Date], 
			[BTD].[Fee], 
			[BTD].[Narr], 
			[BTD].[Matter], 
			[BTD].[Supp], 
			[BTD].[Value], 
			[BTD].[VatCode],
			[BTD].[VatVal],
			[BTD].[Outlay], 
			[BTD].[Year], 
			[BTD].[PerNo], 
			[BTD].[OutlayCode], 
			[BTD].[HeadBatch], 
			[BTD].[AllocBatch], 
			[BTD].[AllocPref], 
			[BTD].[KeyId] ,
			[BTD].[ClientYN],
			[BTD].[AllocRef],
			[BTD].[AllocValue],
			[BTD].[AllocWriteOff],
			[BTD].[Payee],
			[BTD].[Branch],
			[BTD].[ThirdParty],
			[BTD].[PayClient],
			[BTD].[OnceOffPayment],
			[BTD].[ClientCode],
			[BTD].[EFTEmailYorN],
			[BTD].[CaseAssCode],
			[BTD].[HeadPref],
			[BTD].[Supp],
			[BAH].[POSTED],
			[MAT].[S13]
	   FROM [dbo].[BatchDetails] [BTD] 
  LEFT JOIN [dbo].[BatchH] [BAH]  ON [BAH].[BATCHNO] = [BTD].[BATCHNO]
  LEFT JOIN [dbo].[matters] [MAT] ON [MAT].[Code] = [BTD].[MATTER] 
	  WHERE [BTD].[BATCHNO] = @BatchNo
   ORDER BY [BTD].[BATCHNO] ASC, 
		    [BTD].[PREF] ASC, 
		    [BTD].[KEYID] ASC
	END
 SET NOCOUNT OFF
END
GO

IF OBJECT_ID(N'KAAS_GetCaseAssociatesNames',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetCaseAssociatesNames]
GO
CREATE PROCEDURE 
	   [dbo].[KAAS_GetCaseAssociatesNames] 
		(
			@TypeCode varchar(1000)
	    )

AS
/*******************************************************************************************************
* Fetches the case associate names                                                                     * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetCaseAssociatesNames]   								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-09    Revathy D        Created                                                               *
 *******************************************************************************************************/

BEGIN
 SET NOCOUNT ON   

	SELECT  
		[ACV].[NAMECODE] AS Code,  
		CASE WHEN 
	 		RTRIM(ISNULL([CAN].[COMPANY],'')) <> ''    
				THEN RTRIM([CAN].[NAME]) + ' ('+ RTRIM([CAN].[COMPANY]) +')'    
	    		ELSE RTRIM([CAN].[NAME]) 
	 	END       	                        AS [NameNCompany],			 
		[CAN].[ADDRESS]                     AS [Address], 
		[CAN].[PHONENO]						AS [Phone], 
		[ACV].[CATEGORY]					AS [Category], 
		[ACV].[TYPECODE]					AS [Type], 
		[CAN].[NAME]						AS [Name],
		[CAN].[COMPANY]						AS [Company], 
		RTRIM(ISNULL([CAT].[NAMECODE],''))  AS [NAMECODE], 
		RTRIM(ISNULL([CAT].[TYPECODE],''))  AS [TYPECODE], 
		[CAN].[NOTES]						AS [Notes]  
	FROM  
		 [dbo].[AssociateCategoryView] [ACV] 
	  LEFT OUTER JOIN [dbo].[CaseAssociatesNames] [CAN] 
		   	   ON  [ACV].[NAMECODE]= [CAN].[CODE] 
	  LEFT OUTER JOIN [dbo].[CaseAssoicatesTypes] [CAT] 
		   	   ON  [ACV].[NAMECODE]= [CAT].[NAMECODE] AND  [ACV].[TYPECODE]= [CAT].[TYPECODE]
	WHERE 
	    UPPER([ACV].[TYPECODE]) = UPPER(@TypeCode)  
	ORDER BY  
		[ACV].[TYPECODE] ASC, 
		[ACV].[NAMECODE] ASC

 SET NOCOUNT OFF

END

GO



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

CREATE PROCEDURE [dbo].[KAAS_GetCategoryContactList]
	(
		@CategoryType	VARCHAR(10)  = '',
		@Category		VARCHAR(10)  = ''
	)
AS

/*******************************************************************************************************
* Get contact list based on category code and type                                                     * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetCategoryContactList]        							       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-01    Vinodhkumar M        Created                                                           *
 *******************************************************************************************************/

BEGIN
		SELECT      [CAT].[RECORDID]			AS	[RecordId],
					[CAT].[CONTACT]				AS  [Contact],
					[CAT].[CATEGORYTYPE]		AS  [CategoryType],
					[CAT].[CATEGORY]			AS	[Category],
					[CAT].[DATE]				AS	[Date],
					[CAT].[FIELDVALUE1]			AS	[FieldValue1],
					[CAT].[FIELDVALUE2]			AS	[FieldValue2],
					[CAT].[FIELDVALUE3]			AS	[FieldValue3],
					[CAT].[FIELDVALUE4]			AS	[FieldValue4],
					[CAT].[FIELDVALUE5]			AS	[FieldValue5],
					[CAT].[FIELDVALUE6]			AS	[FieldValue6],
					[CAT].[FIELDVALUE7]			AS	[FieldValue7],
					[CAT].[FIELDVALUE8]			AS	[FieldValue8],
					[CAT].[FIELDVALUE9]			AS	[FieldValue9],
					[CAT].[FIELDVALUE10]		AS	[FieldValue10],
					[CONT].[Name]				AS	[Name]
		 FROM		
					[DBO].[ContactCategories] [CAT]
		 LEFT JOIN 
					[Contacts] [CONT] ON [CONT].[Code] = [CAT].[CONTACT]
		 WHERE		
					[CategoryType] = @CategoryType 
		   AND		[Category]     = @Category
 END

GO

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


CREATE PROCEDURE
       [dbo].[KAAS_GetClosedMatterDetails]
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 *																					*
 * 2021-12-27   Vinodhkumar.M	Created to Fetch the Closed Matter details for SAM  *
 ************************************************************************************/
BEGIN
	SELECT  A.[Code]					AS [Code], 
			A.[FECODE]					AS [FECode], 
			B.[Name]					AS [Name],
			A.[Description]				AS [Description], 
			A.[OldRef]					AS [OldRef], 
			A.[FileNum]					AS [FileNum], 
			A.[Dept]					AS [Dept], 
			A.[WTYPE]					AS [WorkType], 
			A.[User1]					AS [Ref1], 
			A.[User2]					AS [Ref2], 
			A.[User3]					AS [Ref3], 
			A.[CloseDate]				AS [CloseDate],
			A.[OrgClosedDate]			AS [OriginalClosedDate],
			A.[ReOpenedDate]			AS [ReopenedDate],
			B.[Address]					AS [Address],
			A.[Comment]					AS [Comment]
	FROM    [dbo].[Matters] A 
	LEFT JOIN 
		    [dbo].[contacts] B ON  A.[CLIENTCODE]= B.[CODE]   
	WHERE   
			[Closed] = 'Y'  
	ORDER BY  
			A.CODE ASC
END

GO


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

CREATE PROCEDURE
       [dbo].[KAAS_GetCostTransferCandidates]
      (@DATE             DATETIME)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_GetCostTransferCandidates]                                                                 *
 *                                                                                                           *
 * Get Cost Transfer Candidates by Date                                                                      *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * First compatible version:                5.8.1.19                                                 *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Copied From [dbo].[ky_NETSPGetCostTransferCandidates]                                                     *
 * Modification History                                                                                      *
 * 2022-02-04   Vignesh.M         Created                                                                    *
 * 2022-02-15   Prabhu.V          Added IsWriteOff and Tagged to bind it by default as false                 *
 * 2024-03-01   Ghayathri S.V     Modified																     *
 * 2024-04-02   Ghayathri S.V     Modified to include Row Number 											 *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

SET @DATE = ISNULL(@DATE, CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112)))

IF @DATE = CONVERT(DATETIME, '19000101', 112)
  BEGIN
    SET @DATE = CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 112))
  END

  SELECT [DL].[MATTER]                                             AS [Matter],
         RTRIM(ISNULL([BRC].[BRANCHCODE], ''))                     AS [BranchCode],
         RTRIM(ISNULL([BRC].[DESCRIPTION], ''))                    AS [Branch],
         [SM].[Name]                                               AS [Name],
         [SM].[Description]                                        AS [Description],
         [DL].[DATE]                                               AS [LedgerDate],
         [DL].[ORIGINAL]                                           AS [Original],
         [DL].[OSVALUE]                                            AS [OSValue],
         [PBO].[PreBilledOutlay]                                   AS [UnpaidOutlay],
         [MAT].[ClientCurBal]                                      AS [ClientBalance],
         [ML].[VALUECC]                                            AS [ClearedClientBalance],
         CASE WHEN   [DL].[OSVALUE]
                   - [PBO].[PreBilledOutlay]
                   - [ALC].[AllocatedValue] <= -[ML].[VALUECC]
                   THEN   [DL].[OSVALUE]
                        - [PBO].[PreBilledOutlay]
                        - [ALC].[AllocatedValue]
              ELSE - [ML].[VALUECC]
                   - [ALC].[AllocatedValue] END                    AS [TransferAmount],
         [DL].[REF]                                                AS [BillNo],
         [DL].[BATCHNO]                                            AS [BatchNo],
         [MAT].[DebtBal]                                           AS [DebtBal],
         [DL].[PREF]                                               AS [PREF],
		 ROW_NUMBER() OVER (ORDER BY (SELECT 1))				   AS [RowNumber]
    FROM [dbo].[DebtorsLedger] [DL]
         INNER JOIN [dbo].[SearchMatters] [SM]
                    INNER JOIN [dbo].[matters] [MAT]
                               LEFT OUTER JOIN [dbo].[Branch] [BRC]
                                            ON [BRC].[BRANCHCODE] = [MAT].[Branch]
                            ON [MAT].[Code] = [SM].[Code]
                 ON [SM].[Code] = [DL].[MATTER]
         CROSS APPLY (SELECT SUM([MLCCV].[VALUECC]) AS [VALUECC]
                        FROM [dbo].[MatLedgerCurClearedView] [MLCCV]
                             WITH (NOEXPAND)
                       WHERE [MLCCV].[MATTER] = [DL].[MATTER]
                         AND [MLCCV].[ClearedDate] <= @DATE) [ML]
         CROSS APPLY (SELECT ISNULL(SUM([BD].[VALUE]), 0) AS [PreBilledOutlay]
                        FROM [dbo].[BatchDetails] [BD]
                       WHERE [BD].[BATCHNO] = [DL].[BATCHNO]
                         AND [BD].[OUTLAY] = 'O'
                         AND [BD].[PreBilledOutlay] = 1) [PBO]
         CROSS APPLY (SELECT ISNULL(SUM([BDA].[VALUE]), 0) AS [AllocatedValue]
                        FROM [dbo].[BatchDetails] [BDA]
                             INNER JOIN [dbo].[BatchH] [BHA]
                                     ON [BHA].[BATCHNO] = [BDA].[BATCHNO]
                                    AND ISNULL([BHA].[POSTED], 'N') <> 'Y'
                       WHERE [BDA].[ALLOCBATCH] = [DL].[BATCHNO]
                         AND [BDA].[ALLOCPREF] = [DL].[PREF]
                         AND [BDA].[TYPE] = 'R'
                         AND [BDA].[OUTLAY] = 'D') [ALC]
   WHERE [DL].[OSVALUE] > 0
     AND [DL].[TYPE] = 'I'
     AND ISNULL([ML].[VALUECC], 0) < 0 --<= -[DL].[OSVALUE] --to get the same output as the original
     AND CASE WHEN   [DL].[OSVALUE]
                   -- [PBO].[PreBilledOutlay]
                   - [ALC].[AllocatedValue] <= -[ML].[VALUECC]
                   THEN   [DL].[OSVALUE]
                        -- [PBO].[PreBilledOutlay]
                        - [ALC].[AllocatedValue]
              ELSE - [ML].[VALUECC]
                   - [ALC].[AllocatedValue] END > 0
ORDER BY [DL].[MATTER]

SET NOCOUNT OFF

END
GO


IF OBJECT_ID(N'KAAS_GetCreditorsList',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetCreditorsList]
GO
CREATE PROCEDURE [dbo].[KAAS_GetCreditorsList]
				(@handlerCode VARCHAR(10) = NULL)
AS

/*******************************************************************************************************
* Fetches the creditors list                                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetCreditorsList]   											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-01    Revathy D        Created                                                               *
 *******************************************************************************************************/
    
BEGIN
	SET NOCOUNT ON
				 SELECT [CLT].[SUPPLYCODE]													   AS [Supplycode], 
					    [CLT].[BATCHNO]														   AS [Batchno], 
					    [CLT].[PREF]														   AS [Pref], 
					    [CLT].[REF]															   AS [Ref], 
					    dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([CLT].[DATE], @handlerCode) AS [Date], 
					    [CLT].[ORIGVALUE]													   AS [Origvalue], 
					    [CLT].[OSVALUE]														   AS [Osvalue], 
					    [CLT].[PAYVALUE]												       AS [Payvalue], 
					    [CLT].[RECORDID]							                           AS [Recordid],
					    [SUP].[CODE]														   AS [Code], 
					    [SUP].[NAME]														   AS [Name], 
					    [SUP].[NOMINAL]														   AS [Nominal]
				   FROM [dbo].[CreditorsList] [CLT]
	    LEFT OUTER JOIN [dbo].[Suppliers] [SUP] 
					 ON [CLT].[SUPPLYCODE] = [SUP].[CODE]
			   ORDER BY [CLT].[SUPPLYCODE]   ASC, 
					    [CLT].[BATCHNO]      ASC, 
					    [CLT].[RECORDID]     ASC   

SET NOCOUNT OFF

END

GO



IF OBJECT_ID(N'KAAS_GetDateValidationControls',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetDateValidationControls]
GO
CREATE PROCEDURE [dbo].[KAAS_GetDateValidationControls] 
AS
/*******************************************************************************************************
* This sp is used to GET THE CONTROL setting    													   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetDateValidationControls]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-19    Revathy           Created                                                              *
* 2021-05-23    Balamurugan       Modified - Default Outlay Code Added                                 *
 *******************************************************************************************************/ 
BEGIN
	SET NOCOUNT ON

SELECT 
  CASE WHEN [DateFutValidation] = ''  THEN 0 
  ELSE ISNULL([DateFutValidation],0) END          AS DateFutValidation, 
  CASE WHEN [DatePastValidation] = ''  THEN 0 
  ELSE ISNULL([DatePastValidation],0) END         AS DatePastValidation,
  ISNULL(VAC.[Code],'')                           AS DefaultVATCode, 
  ISNULL(VAC.[Rate],0.00)                         AS DefaultVATRate,
  RTRIM(ISNULL(CNL.[Creditor],''))		          AS CreditorControlAc,
  RTRIM(ISNULL(CNL.[Client],''))  		          AS ClientControlAc,
  RTRIM(ISNULL(CNL.[DefaultClientAc],''))  	      AS DefaultClientAc,
  RTRIM(ISNULL(CNL.[DefaultClientDep],''))        AS DefaultClientDepAc,
  YearEndDate								      AS YearEndDate,
  [dbo].[KAAS_FN_GetDateFromClarion](PeriodEnd)	  AS PeriodEndDate,
  RTRIM(Outlay)									  AS DefaultOutlayCode				
FROM [dbo].[CONTROL] CNL
LEFT JOIN [dbo].[VATcodes] VAC ON CNL.[Vatexclude] = VAC.[Code]

	SET NOCOUNT OFF
END

GO


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

CREATE PROCEDURE [dbo].[KAAS_GetDebtorsLedger] (
       @PageNumber    INT,
       @PageSize      INT,
       @SearchString  VARCHAR(500),
       @SortColumn    VARCHAR(100),
       @SortOrder     VARCHAR(100),
       @MatterCode    VARCHAR(20))
AS
/*******************************************************************************************************
 * Fetches the Debtors Ledger by Matter Code                                                           *
 *                                                                                                     *
 * Stored Procedure Name : [dbo].[KAAS_GetSAMDebtorsLedgerbyMatterCode]                                *
 *                                                                                                     *
 * Modification History:                                                                               *
 * 2021-03-25    Prabhu V        Created                                                               *
 * 2021-12-02    Vinodhkumar.M   Modified - Account Bal, Cleared Bal query added                       *
 * 2022-07-19    Ghayathri.S.V   Modified - To implement dynamic sql query to fetch sort               *
 *                                          and search datas and fetch debtor ledger balances          *
 * 2022-07-19    Ghayathri.S.V   Modified - Included Narrative column in Search filter                 *
 * 2024-02-21    John Ginnane    Refactored and renamed procedure                                      *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    SET @SortColumn = ISNULL(NULLIF(@SortColumn, ''), 'RECORDID')
    IF @SortOrder NOT IN ('ASC', 'DESC')
    BEGIN
        SET @SortOrder = 'ASC'
    END

    DECLARE @sql    NVARCHAR(max)
    DECLARE @offset INT = @PageSize * (@PageNumber - 1)

    SET @sql =  'SELECT LTRIM(RTRIM([DTL].[MATTER]))                   AS [MatterCode],
                        ISNULL(LTRIM(RTRIM([SM].[Description])), '''') AS [MatterDescription],
                        ISNULL(LTRIM(RTRIM([SM].[Name])), '''')        AS [ClientName],
                        ISNULL(LTRIM(RTRIM([DTL].[TYPE])), '''')       AS [Type],
                        LTRIM(RTRIM([DTL].[CLIENT]))                   AS [ClientCode],
                        [DTL].[DATE]                                   AS [Date],
                        ISNULL(LTRIM(RTRIM([DTL].[REF])), '''')        AS [Ref],
                        [DTL].[BATCHNO]                                AS [BatchNo],
                        [DTL].[PREF]                                   AS [PRef],
                        ISNULL(LTRIM(RTRIM([DTL].[NARR])), '''')       AS [Narrative],
                        ISNULL([DTL].[ORIGINAL], 0)                    AS [Original],
                        ISNULL([DTL].[OSVALUE], 0)                     AS [OSValue],
                        ISNULL([DTL].[ORFEES], 0)                      AS [OriginalFees],
                        ISNULL([DTL].[OROUTLAY], 0)                    AS [OriginalOutlay],
                        ISNULL([DTL].[ORVAT], 0)                       AS [OriginalVAT],
                        ISNULL([DTL].[OSFEES], 0)                      AS [OSFees],
                        ISNULL([DTL].[OSOUTLAY], 0)                    AS [OSOutlay],
                        ISNULL([DTL].[OSVAT], 0)                       AS [OSVAT],
                        ISNULL(LTRIM(RTRIM([DTL].[VATCODE])), '''')    AS [VATCode],
                        ISNULL([DTL].[PER], 0)                         AS [Period],
                        ISNULL([DTL].[YEAR], 0)                        AS [Year],
                        [DTL].[RECORDID]                               AS [RecordID]
                   FROM [dbo].[DebtorsLedger] AS [DTL]
                        INNER JOIN [dbo].[SearchMatters] AS [SM]
                                ON [SM].[Code] = [DTL].[MATTER]
                  WHERE [DTL].[MATTER] =  ''' + @MatterCode  + '''' +
                   'AND ([DTL].[DATE]       LIKE ' + '''%' + @SearchString + '%' + '''' +
                     'OR [DTL].[BATCHNO]    LIKE ' + '''%' + @SearchString + '%' + '''' +
                     'OR [DTL].[PREF]       LIKE ' + '''%' + @SearchString + '%' + '''' +
                     'OR [DTL].[NARR]       LIKE ' + '''%' + @SearchString + '%' + '''' +
                     'OR [SM].[Name]        LIKE ' + '''%' + @SearchString + '%' + '''' +
                     'OR [SM].[Description] LIKE ' + '''%' + @SearchString + '%' + '''' + ')
                        ORDER BY ' + @SortColumn + ' ' + @SortOrder + ' ' +
                         'OFFSET ' + CAST(@offset   AS NVARCHAR(MAX)) + ' ROWS ' +
                     'FETCH NEXT ' + CAST(@PageSize AS NVARCHAR(MAX)) + ' ROWS ONLY'

    EXEC sp_executesql @sql

    SELECT COUNT(1) AS [TotalRecords]
      FROM [dbo].[DebtorsLedger] AS [DTL]
           INNER JOIN [dbo].[SearchMatters] AS [SM]
                   ON [DTL].[MATTER] = [SM].[Code]
     WHERE ISNULL([DTL].[MATTER], '') = @MatterCode
       AND ([DTL].[DATE]       LIKE '%' + @SearchString + '%'
         OR [DTL].[BATCHNO]    LIKE '%' + @SearchString + '%'
         OR [DTL].[PREF]       LIKE '%' + @SearchString + '%'
         OR [DTL].[NARR]       LIKE '%' + @SearchString + '%'
         OR [SM].[Name]        LIKE '%' + @SearchString + '%'
         OR [SM].[Description] LIKE '%' + @SearchString + '%')

    SELECT ISNULL(SUM([DTL].[ORIGINAL]), 0) AS [DebtorClearedBalance],
           ISNULL([MAT].[DebtBal], 0)       AS [DebtorAccountBalance],
           ISNULL(SUM([DTL].[OSVALUE]), 0)  AS [OSValue]
      FROM [dbo].[matters] AS [MAT]
           LEFT OUTER JOIN [dbo].[DebtorsLedger] AS [DTL]
                        ON [MAT].[Code] = [DTL].[MATTER]
                       AND ISNULL([DTL].[ClearedDate], [DTL].[DATE]) <= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
     WHERE [MAT].[Code] = @MatterCode
           GROUP BY [MAT].[Code],
                    [MAT].[DebtBal]
END
GO
IF OBJECT_ID(N'KAAS_GetDebtorsLedgerAllocations', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetDebtorsLedgerAllocations]
END
GO

CREATE PROCEDURE [dbo].[KAAS_GetDebtorsLedgerAllocations] (
       @RecordID INT)
AS
/*******************************************************************************************************
 * Returns a list of allocations for the specified debtors ledger record                               *
 *                                                                                                     *
 * Stored Procedure Name : [dbo].[KAAS_GetDebtorsLedgerAllocations]                                    *
 *                                                                                                     *
 * Modification History:                                                                               *
 * 2021-03-31   Prabhu V        Created                                                                *
 * 2024-02-21   John Ginnane   Refactored and renamed procedure                                        *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    SELECT LTRIM(RTRIM([DTL].[MATTER]))                 AS [MatterCode],
           ISNULL(LTRIM(RTRIM([SM].[Description])), '') AS [MatterDescription],
           ISNULL(LTRIM(RTRIM([SM].[Name])), '')        AS [ClientName],
           ISNULL(LTRIM(RTRIM([DTL].[TYPE])), '')       AS [Type],
           LTRIM(RTRIM([DTL].[CLIENT]))                 AS [ClientCode],
           [DTL].[DATE]                                 AS [Date],
           ISNULL(LTRIM(RTRIM([DTL].[REF])), '')        AS [Ref],
           [DTL].[BATCHNO]                              AS [BatchNo],
           [DTL].[PREF]                                 AS [PRef],
           ISNULL(LTRIM(RTRIM([DTL].[NARR])), '')       AS [Narrative],
           ISNULL([DTL].[ORIGINAL], 0)                  AS [Original],
           ISNULL([DTL].[OSVALUE], 0)                   AS [OSValue],
           ISNULL([DTL].[ORFEES], 0)                    AS [OriginalFees],
           ISNULL([DTL].[OROUTLAY], 0)                  AS [OriginalOutlay],
           ISNULL([DTL].[ORVAT], 0)                     AS [OriginalVAT],
           ISNULL([DTL].[OSFEES], 0)                    AS [OSFees],
           ISNULL([DTL].[OSOUTLAY], 0)                  AS [OSOutlay],
           ISNULL([DTL].[OSVAT], 0)                     AS [OSVAT],
           ISNULL(LTRIM(RTRIM([DTL].[VATCODE])), '')    AS [VATCode],
           ISNULL([DTL].[PER], 0)                       AS [Period],
           ISNULL([DTL].[YEAR], 0)                      AS [Year],
           [DTL].[RECORDID]                             AS [RecordID]
      FROM [dbo].[DebtorsLedger] AS [DTL]
                        INNER JOIN [dbo].[SearchMatters] AS [SM]
                                ON [SM].[Code] = [DTL].[MATTER]
     WHERE [DTL].[RECORDID] = @RecordID

    SELECT ISNULL([ALO].[BATCHNO], 0)                 AS [BatchNo],
           ISNULL([ALO].[PREF], 0)                    AS [Pref],
           [ALO].[DATE]                               AS [AllocationDate],
           [DTL].[DATE]                               AS [TransactionDate],
           ISNULL([ALO].[ABATCHNO], 0)                AS [ABatchNo],
           ISNULL([ALO].[OPREF], 0)                   AS [OPref],
           ISNULL(LTRIM(RTRIM([ALO].[OREF])), '')     AS [ORef],
           ISNULL([ALO].[VALUE], 0)                   AS [Value],
           ISNULL([ALO].[FEES], 0)                    AS [Fees],
           ISNULL([ALO].[OUTLAY], 0)                  AS [Outlay],
           ISNULL([ALO].[VAT], 0)                     AS [VAT],
           ISNULL(LTRIM(RTRIM([ALO].[USERCODE])), '') AS [UserCode],
           ISNULL([ALO].[AllNo], 0)                   AS [AllNo],
           ISNULL([ALO].[KEYID], 0)                   AS [KeyID]
      FROM [dbo].[DebtorsLedger] AS [DTL]
           INNER JOIN [dbo].[Allocations] AS [ALO]
                   ON [DTL].[BATCHNO] = [ALO].[BATCHNO]
                  AND [DTL].[PREF]    = [ALO].[PREF]
     WHERE [DTL].[RECORDID] = @RecordID
           ORDER BY [ALO].[AllNo] ASC,
                    [ALO].[KEYID] ASC

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

GO

CREATE PROCEDURE [dbo].[KAAS_GetDebtorsLedgerDetailsByClient]
	(
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Client',
			@SortOrder     VARCHAR(100) = 'ASC',
			@Code		   VARCHAR(10)  = ''
	)
AS

/*******************************************************************************************************
* Fetches the Debtors Ledger details by client														   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetDebtorsLedgerDetailsByClient]   							   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-06    Balamurugan C        Created														   *  
* 2021-11-11    Balamurugan C        Updated - Batch No is added    
* 2022-07-18    Ghayathri.S.V        Modified to implement dynamic sql query to fetch sort
									 and search datas and fetch debtor ledger balances                                        
 *******************************************************************************************************/
BEGIN
	DECLARE		   @sql        NVARCHAR(max)
	DECLARE		   @search	   NVARCHAR(500) = ''
	DECLARE		   @offset	   INT = @PageSize * (@PageNumber -1)

	SET	  @sql =  'SELECT  [BatchNo],
						   [RecordId],
				           [Type],
						   [Date],
						   [Matter],
						   [Ref],
					   	   [Narr],
						   [Original],
						   [OsValue]
					FROM   [dbo].[DebtorsLedger]
	               WHERE   [Client] =  ''' + @Code  + '''' +  
		           'AND    ( 
							 [BatchNo]   LIKE' + '''%'  + @SearchString + '%' + '''' +	
							 'OR
							 [Date]		 LIKE ' + '''%' + @SearchString + '%' + '''' +
						     'OR
							 [Matter]    LIKE ' + '''%' + @SearchString + '%' + '''' +
							 'OR
							 [Ref]       LIKE ' + '''%' + @SearchString + '%' + '''' +
							 'OR
							 [Narr]      LIKE ' + '''%' + @SearchString + '%' + '''' +
						   ')
		        ORDER BY '      +    @SortColumn + ' '  + @SortOrder + ' ' +
	             'OFFSET '      +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
			 'FETCH NEXT '      +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

	EXEC Sp_executesql @sql

				SELECT      COUNT(*)  'TotalRecord'
				  FROM		[dbo].[DebtorsLedger]
	             WHERE      Client =   @Code
			       AND		( 
						      [BatchNo]   LIKE '%' + @SearchString + '%'  
							  OR
							  [Date]	  LIKE '%' + @SearchString + '%' 
							  OR
							  [Matter]    LIKE '%' + @SearchString + '%'
							  OR
							  [Ref]       LIKE '%' + @SearchString + '%'
							  OR
							  [Narr]      LIKE '%' + @SearchString + '%'

							)

				SELECT     ISNULL(SUM(ISNULL([Original], 0)), 0)   AS [DebtorOriginalBalance], 
					       ISNULL(SUM(ISNULL([OSVALUE], 0)), 0)    AS [DebtorOsValueBalance]
				  FROM     [dbo].[DebtorsLedger]
	             WHERE     Client =   @Code

END

GO

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

CREATE PROCEDURE
       [dbo].[KAAS_GetEFTDetailsPopupData]
      (
		@CODE      VARCHAR(20)
	   )
AS
/*************************************************************************************************************                                                *
 * Modification History                                                                                      *
 * 2024-03-19   Ghayathri S.V     Created																     *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON


   SELECT		  A.[EFTYN]					AS [EftYn],
 				  A.[EFTLIMIT]				AS [EftLimit], 
				  A.[EFTTRANSACTIONLIMIT]	AS [EftTransactionLimit], 
				  A.[BANKFILENAME]			AS [BankFileName],
				  A.[LOCATION]				AS [Location],
				  A.[FILENUMBER]			AS [FileNumber],  
				  A.[RECORDID]				AS [RecordId]
     FROM		  dbo.[EFTDetails] A 
    WHERE		  A.[RecordID] = 1
 ORDER BY		  A.[RecordID] ASC

      IF(@CODE != '')
    BEGIN
   SELECT		  NOM.[SORTCODE]				AS [SortCode],
 				  NOM.[ACCOUNTNO]				AS [AccountNumber], 
				  NOM.[IBAN]					AS [Iban], 
				  NOM.[BIC]						AS [Bic],
				  NOM.[ORGIDNUMBER]				AS [OrgNumber]
     FROM		  dbo.[Nominal] NOM
    WHERE		  NOM.[CODE] = @CODE
 ORDER BY		  NOM.[CODE] ASC
	  END

SET NOCOUNT OFF

END
GO


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

CREATE PROCEDURE
       [dbo].[KAAS_GetEFTGridDetails]
      (
	    @FROMDATE  DATETIME,
	    @TODATE    DATETIME,
		@CODE      VARCHAR(20),
		@TYPE	   CHAR(1)
	   )
AS
/*************************************************************************************************************                                                *
 * Modification History                                                                                      *
 * 2024-03-19   Ghayathri S.V     Created																     *
 * 2024-03-25   Ghayathri S.V     Modified - Updated the logic around Batch NUmber to fetch the details 	 *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

DECLARE @BATCHNO INT

SET @BATCHNO = NULL 

SELECT TOP 1 @BATCHNO = BATCHNO FROM BatchH ORDER BY BATCHNO DESC

SET @FROMDATE = ISNULL(@FROMDATE, CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 102)))
SET @TODATE = ISNULL(@TODATE, CONVERT(DATETIME, CONVERT(VARCHAR, GETDATE(), 102)))

IF @TYPE = 'T' OR @TYPE = 'R'
	BEGIN
		SELECT					A.[BATCHNO]			AS [BatchNo],
 								A.[REF]				AS [Ref], 
								A.[TYPE]			AS [Type], 
								A.[DATE]			AS [Date],
								A.[VALUE]			AS [Value],
								A.[CLIENTBANK]		AS [BankCode],  
								A.[PAYEE]			AS [Payee],
								A.[EFTEMAILYORN]	AS [EmailEft],
								A.[BRANCH]			AS [Branch],
								A.[NARR]			AS [Narr],
								A.[SUPP]			AS [SupplierCode],
								B.[NAME]			AS [SupplierName],
								A.[CLIENTCODE]		AS [ClientCode],
								A.[CASEASSCODE]		AS [CaseAssCode],
								A.[EFTSENT]			AS [EftSent]
		FROM					dbo.BatchH A 
		LEFT OUTER JOIN			dbo.Suppliers B 
		ON						A.SUPP= B.CODE
		WHERE					(A.[Type] = @TYPE	AND A.[Posted] = 'Y' 
		AND						A.[EFTSent] <> 'Y'  AND A.[EFTYorN] = 'Y' 
		AND					    A.[CLIENTBANK] = @CODE 
		AND						A.[DATE] >= CONVERT(DATETIME, @FROMDATE, 102) 
		AND						A.[DATE] <= CONVERT(DATETIME, @TODATE, 102))  
		AND						(A.[POSTED] >= 'Y')   AND (( A.[POSTED] > 'Y' )  OR ((  A.[BATCHNO] <= @BATCHNO )))
		ORDER BY				A.[POSTED] ASC, A.[BATCHNO] ASC
	END
ELSE
	BEGIN
		SELECT					A.[BATCHNO]			AS [BatchNo],
 								A.[REF]				AS [Ref], 
								A.[TYPE]			AS [Type], 
								A.[DATE]			AS [Date],
								A.[VALUE]			AS [Value],
								A.[CODE]			AS [BankCode],  
								A.[PAYEE]			AS [Payee],
								A.[EFTEMAILYORN]	AS [EmailEft],
								A.[BRANCH]			AS [Branch],
								A.[NARR]			AS [Narr],
								A.[SUPP]			AS [SupplierCode],
								B.[NAME]			AS [SupplierName],
								B.[EmailAddress]	AS [SupplierEmailAddress],
								A.[CLIENTCODE]		AS [ClientCode],
								A.[CASEASSCODE]		AS [CaseAssCode],
								A.[EFTSENT]			AS [EftSent]
		FROM					dbo.BatchH A 
		LEFT OUTER JOIN			dbo.Suppliers B 
		ON						A.SUPP= B.CODE
		WHERE					(A.[Type] = @TYPE	AND A.[Posted] = 'Y' 
		AND						A.[EFTSent] <> 'Y'  AND A.[EFTYorN] = 'Y' 
		AND					    A.Code = @CODE 
		AND						A.[DATE] >= CONVERT(DATETIME, @FROMDATE, 102) 
		AND						A.[DATE] <= CONVERT(DATETIME, @TODATE, 102))  
		AND						(A.[POSTED] >= 'Y')   AND (( A.[POSTED] > 'Y' )  OR ((  A.[BATCHNO] <= @BATCHNO )))
		ORDER BY				A.[POSTED] ASC, A.[BATCHNO] ASC
	END
SET NOCOUNT OFF

END
GO




IF OBJECT_ID(N'KAAS_GetFeeEarnerCodesMasterDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetFeeEarnerCodesMasterDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_GetFeeEarnerCodesMasterDetails]
                 (
                   @Code	   VARCHAR(10) = ''
                 )
AS
/*******************************************************************************************************
* Fetch the Fee Earner Codes Master details															   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetFeeEarnerCodesMasterDetails]   							   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-06-23    Balamurugan C        Created                                                           *
* 2022-03-02	Vignesh.M		    Modified Branch Implemented 									   *
 *******************************************************************************************************/

BEGIN
	SET NOCOUNT ON

			SELECT	[Code],
					[Name],
					[Nominal],
					[Retired],
					[Branch]
			  FROM	[dbo].[FeeEarnerCodes]
			 WHERE  [CODE] = @Code
		  ORDER BY  [CODE]

   SET NOCOUNT OFF
END
GO


IF OBJECT_ID(N'KAAS_GetHandlerDropdownList', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetHandlerDropdownList]
END
GO
CREATE PROCEDURE 
       [dbo].[KAAS_GetHandlerDropdownList]
AS
BEGIN
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_GetHandlerDropdownList]                                                                     *
 *                                                                                                           *
 * Description: This procedure is used to check Handler Code exists or not                                   *
 *                                                                                                           *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification history:                                                                                     *
 * 2021-06-25  Natarajan S            Created																 *
 * 2021-06-29  Natarajan S			  Modified - Added charges group										 *
 * 2021-07-09  Balamurugan C		  Modified - Fee Earner Details 									     *
 *************************************************************************************************************/

        	  	SELECT [HAN].[Code]                     AS [Code], 
        	  		   [HAN].[Team]	                    AS [Description]
        	  	  FROM [dbo].[Handlers] [HAN] 
        	  	 WHERE [HAN].[TeamCode] = 'Y' 
        	  	   AND [HAN].[Retired]='N' 
        	  ORDER BY [HAN].[Code] ASC
        	  	
				SELECT [FEE].[Code], 
					   [FEE].[Name] AS [Description],
					   [FEE].[Retired]
				  FROM [dbo].[FeeEarnerCodes] FEE 
			  ORDER BY [FEE].[Code] ASC
        	  
        	  	SELECT RTRIM([TAC].[Code])              AS [Code],
        	  		   [TAC].[Desc]                     AS [Description] 
        	  	  FROM [dbo].[TasksCodes] [TAC] 
        	  	 WHERE [TAC].[AxleTask] = 'N' 
        		    OR [TAC].[AxleTask] = '''' 
        	  ORDER BY [TAC].[Code] ASC
        	  
        	  	SELECT RTRIM([HAN].[Code])              AS [Code],
        	  		   [HAN].[Name]                     AS [Description]
        	  	  FROM [dbo].[Handlers] [HAN] 
       LEFT OUTER JOIN [dbo].[NoOverDueTasks] [NOT] 
		            ON [HAN].[Code]= [NOT].[Handler]   
		         WHERE [HAN].[Retired] <> 'Y'
				   AND [HAN].[Code] <> 'JP   '  
	          ORDER BY [HAN].Code ASC
		
		        SELECT [DEP].[Code]                     AS [Code],
		        	   [DEP].[Description]              AS [Description] 
		          FROM [dbo].Departments [DEP]
		        
		        SELECT RTRIM([BCH].[BranchCode])        AS [Code],
		        	   [BCH].[Description]              AS [Description]
		          FROM [dbo].[Branch] [BCH]
		         WHERE [BCH].[Retired]=0
		        
		        SELECT RTRIM([HCG].[Code])              AS [Code],
		        	   [HCG].[Name]                     AS [Description]
		          FROM [dbo].[HandlerChargeGroups] [HCG]
    
END

GO



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

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[KAAS_GetHandlersMaster]


AS

/*******************************************************************************************************
* Fetches Handlers master list										                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetHandlersMaster]         									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-21    Natarajan S           Created														   *
* 2022-02-09    Vinodhkumar.M         Modifed - added email fields								       *
 *******************************************************************************************************/

BEGIN

	SELECT  [HAN].CODE		AS [Code],
			[HAN].TEAM		AS [Team],
			[HAN].NAME		AS [Name],
			[HAN].RATE		AS [Rate],
			[HAN].RETIRED	AS [Retired],
			[HAN].[EMAIL]   AS [Email]
	   FROM [dbo].Handlers	AS [HAN]
   ORDER BY [HAN].CODE ASC


END

GO

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

CREATE PROCEDURE [dbo].[KAAS_GetInvoiceList] (
                  @Matter   VARCHAR(50) = NULL
                  )
AS
/*******************************************************************************************************
* Fetches the Invoice list                                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetInvoiceList] '000001/0003'								                       *
*                                                                                                      *
* Modification History:                                                                                *
* 14 Jul 2021    Natarajan S        Created														       *                                          
 *******************************************************************************************************/
BEGIN
 SET NOCOUNT ON
         SELECT [DBL].[RecordId]   AS [RecordId],
	            [DBL].[BATCHNO]    AS [BatchNo],
                [DBL].[Type]       AS [Type],
                [DBL].[Ref]        AS [Ref],
                [CON].[Name]       AS [Narr],
                [DBL].[Date]       AS [Date],
                [DBL].[Original]   AS [Original], 
                [DBL].[OSValue]    AS [OsValue],
		        [DBL].[OSFees]     AS [OsFees],
		        [DBL].[OsOutlay]   AS [OsOutlay],
		        [DBL].[OsVat]      AS [OsVat]
           FROM [dbo].[DebtorsLedger] [DBL]               
LEFT OUTER JOIN [dbo].[Matters] [MAT] 
             ON [DBL].[MATTER]         = [MAT].[Code]     
LEFT OUTER JOIN [dbo].[Contacts] [CON]
             ON [MAT].[ClientCode]     = [CON].[Code]  
          WHERE [DBL].[Matter]         = @Matter
            AND [DBL].[OSValue] > 0  
       ORDER BY [DBL].[Matter]           ASC, 
                [DBL].[Date]             ASC, 
                [DBL].[RecordId]         ASC
 SET NOCOUNT OFF
END

GO

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

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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_GetKeyhouseMenuList]
	 (
		@HandlerCode VARCHAR(10),
		@Mode		 VARCHAR(10),
		@ApplType    VARCHAR(10) = 'SAM'
	 )
AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetKeyhouseMenuList]      									   *
* Description: To get SAM and CASE menu List		    											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2023-12-28    Balamurugan C        Created                                                           *
* 2024-01-09    Balamurugan C        Added column of MenuOpenNewTab									   *
* 2024-01-09    Sadiq Basha N        Added column of MenuOpenDialogBox								   *
* 2024-01-17    Balamurugan C        Changed Order By logic          								   *
* 2024-01-22	Balamurugan C		 Fetch Handler Supervior Key                                       *
* 2024-02-13	Balamurugan C		 Modified : Remove the menu from list when view access set         *
                                                to false (Removed the write or read access conition)   *
* 2024-04-04	Balamurugan C        Modified : Added the new logic in menu master table to            *
                                                fetch the case management menus                        *
									 Note: Changed the SP name from KAAS_GetAccountsMenuList to        *
											KAAS_GetKeyhouseMenuList because both case and SAM menu's  *
											handled                                                    *
 *******************************************************************************************************/
BEGIN
	IF(@ApplType = 'SAM')
	  BEGIN
		SELECT * FROM (
				SELECT 
					[AMM].[MenuId]               AS [MenuId],
					[AMM].[MenuName]             AS [MenuName],
					[AMM].[MenuParentId]         AS [MenuParentId],
					[AMM].[MenuRoute]            AS [MenuRoute],
					[AMM].[MenuIconName]         AS [MenuIconName],
					[AMM].[MenuCode]             AS [MenuCode],
					[AMM].[MenuOrder]			 AS [MenuOrder],
					[AMM].[MenuOpenNewTab]	     AS [MenuOpenNewTab],
					[AMM].[MenuOpenDialogBox]	 AS [MenuOpenDialogBox],
					ISNULL([HMP].[HandlerPermissionMapId],0) AS [HandlerPermissionMapId],
					CASE WHEN (
						SELECT COUNT([SHMP].MenuId) 
						FROM [dbo].[HandlerMenuPermissionMap] [SHMP]
						WHERE [SHMP].[HandlerCode] = @HandlerCode
					) > 0 THEN CASE WHEN [HMP].[ReadAccess] IS NULL THEN 1 ELSE [HMP].[ReadAccess] END ELSE 1 END AS [ReadAccess],
					CASE WHEN (
						SELECT COUNT([SHMP].MenuId) 
						FROM [dbo].[HandlerMenuPermissionMap] [SHMP]
						WHERE [SHMP].[HandlerCode] = @HandlerCode
					) > 0 THEN CASE WHEN [HMP].[WriteAccess] IS NULL THEN 0 ELSE [HMP].[WriteAccess] END ELSE 0 END AS [WriteAccess]
				FROM [dbo].[KeyhouseMenuList] [AMM]
				LEFT JOIN [dbo].[HandlerMenuPermissionMap] [HMP]
					ON [HMP].MenuId = [AMM].MenuId AND [HMP].[HandlerCode] = @HandlerCode
					WHERE [AMM].MenuIsActive = 1 AND [AMM].[MenuApplicationType] = 'A'
			) FA 
		WHERE (@Mode = 'Menu' AND (FA.ReadAccess = 1)) OR 
			  (@Mode <> 'Menu' AND FA.MenuCode NOT IN ('DASHBOARD','VIEW_DASHBOARD','USER_ACCESS'))
	 ORDER BY CASE WHEN FA.[MenuParentId] = 0 THEN 0 ELSE 1 END, -- Rows with MenuParentId = 0 come first
						FA.[MenuParentId] ASC,
						FA.[MenuOrder] ASC;
	END
IF(@ApplType ='CASE')
BEGIN
	SELECT * FROM (
				SELECT 
					[AMM].[MenuId]               AS [MenuId],
					[AMM].[MenuName]             AS [MenuName],
					[AMM].[MenuParentId]         AS [MenuParentId],
					[AMM].[MenuRoute]            AS [MenuRoute],
					[AMM].[MenuIconName]         AS [MenuIconName],
					[AMM].[MenuCode]             AS [MenuCode],
					[AMM].[MenuOrder]			 AS [MenuOrder],
					[AMM].[MenuOpenNewTab]	     AS [MenuOpenNewTab],
					[AMM].[MenuOpenDialogBox]	 AS [MenuOpenDialogBox],
					ISNULL([HMP].[HandlerPermissionMapId],0) AS [HandlerPermissionMapId],
					CASE WHEN (
						SELECT COUNT([SHMP].MenuId) 
						FROM [dbo].[HandlerMenuPermissionMap] [SHMP]
						WHERE [SHMP].[HandlerCode] = @HandlerCode
					) > 0 THEN CASE WHEN [HMP].[ReadAccess] IS NULL THEN 1 ELSE [HMP].[ReadAccess] END ELSE 1 END AS [ReadAccess],
					CASE WHEN (
						SELECT COUNT([SHMP].MenuId) 
						FROM [dbo].[HandlerMenuPermissionMap] [SHMP]
						WHERE [SHMP].[HandlerCode] = @HandlerCode
					) > 0 THEN CASE WHEN [HMP].[WriteAccess] IS NULL THEN 0 ELSE [HMP].[WriteAccess] END ELSE 0 END AS [WriteAccess]
				FROM [dbo].[KeyhouseMenuList] [AMM]
				LEFT JOIN [dbo].[HandlerMenuPermissionMap] [HMP]
					ON [HMP].MenuId = [AMM].MenuId AND [HMP].[HandlerCode] = @HandlerCode
					WHERE [AMM].MenuIsActive = 1 AND [AMM].[MenuApplicationType] = 'C'
			) FA 
		WHERE (@Mode = 'Menu' AND (FA.ReadAccess = 1)) OR 
			  (@Mode <> 'Menu' AND FA.MenuCode NOT IN ('CASE_USER_ACCESS'))
	 ORDER BY CASE WHEN FA.[MenuParentId] = 0 THEN 0 ELSE 1 END, -- Rows with MenuParentId = 0 come first
						FA.[MenuParentId] ASC,
						FA.[MenuOrder] ASC;
END

	--Fetch Handler Code Supervisor Key

	SELECT [Supervisor] 
	  FROM [dbo].[HandlerNETLogons]
	 WHERE [HANDLER] = @HandlerCode


END
GO

IF OBJECT_ID(N'KAAS_GetMatterValues',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetMatterValues]
GO
CREATE PROC dbo.[KAAS_GetMatterValues]
(
@MatterCode VARCHAR(20)
)
AS

/*******************************************************************************************************
* To fetch the matter billing details                                                                  * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetMatterValues]      	            					       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-18    Revathy D        Created                                                               *
* 2021-11-30    Vinodhkumar M    Modified - MatterCode values fetch from matters table                 *
* 2021-11-30    Balamurugan C    Modified - Added Client  Balance                               *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

DECLARE @RECORDCOUNT INT
SET @RECORDCOUNT = (SELECT COUNT(*) FROM [dbo].[Matters] WHERE [Code] = @MatterCode) 
IF( @RECORDCOUNT > 0) 
BEGIN
	   SELECT [MAT].[DebtBal]		   AS [BillingAc],
			  [MAT].[OutlayBal]		   AS [OutlayAc],
			  [MAT].[ClientCurBal]	   AS [CurrentAc],
			  [MAT].[ClientDepBal]	   AS [DepositAc],
			  [MAT].[ClientBal]		   AS [ClientBal]		  
		FROM  [dbo].[Matters] [MAT]
		WHERE [MAT].[Code] = @MatterCode
END
ELSE
BEGIN
	SELECT 
		0.00 OutlayAc,
		0.00 BillingAc, 
		0.00 CurrentAc,
		0.00 DepositAc,
		0.00 ClientBal
END
SET NOCOUNT OFF

END
GO

IF OBJECT_ID(N'KAAS_GetMatterValuesWithClosedDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetMatterValuesWithClosedDetails]
GO
CREATE PROC dbo.[KAAS_GetMatterValuesWithClosedDetails]
(
@MatterCode VARCHAR(20)
)
AS

/*******************************************************************************************************
* To fetch the matter billing and Closed details                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetMatterValuesWithClosedDetails]      	            					       *
*                                                                                                      *
* Modification History:                                                                                *
* 2024-05-08   Vignesh M  Created                                                                      *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

DECLARE @RECORDCOUNT INT
SET @RECORDCOUNT = (SELECT COUNT(*) FROM [dbo].[Matters] WHERE [Code] = @MatterCode) 
IF( @RECORDCOUNT > 0) 
BEGIN
	    SELECT 
	        [MAT].[DebtBal]		   AS [BillingAc],
			[MAT].[OutlayBal]		   AS [OutlayAc],
			[MAT].[ClientCurBal]	   AS [CurrentAc],
			[MAT].[ClientDepBal]	   AS [DepositAc],
			[MAT].[ClientBal]		   AS [ClientBal]		  
	   FROM [dbo].[Matters] [MAT]
	  WHERE [MAT].[Code] = @MatterCode
END
ELSE
BEGIN
		SELECT 
			0.00 OutlayAc,
			0.00 BillingAc, 
			0.00 CurrentAc,
			0.00 DepositAc,
			0.00 ClientBal
END
		SELECT	
			[MAT].[Code]			AS [Code],
			[MAT].[ClientCode]		AS [ClientCode],
			[MAT].[Matter]			AS [MatterNo],
			[MAT].[FECode]			AS [FECode],
			[MAT].[Closed]			AS [Closed],
			[MAT].[ClientMin]		AS [ClientMin],
			[MAT].[OutlayBud]		AS [OutlayBud],
			[CON].[Name]			AS [Name],
			[MAT].[Description]		AS [Description]
	   FROM [dbo].[matters] [MAT]
  LEFT JOIN [dbo].[Contacts] [CON]
		 ON [MAT].[ClientCode] = [CON].[Code]
	  WHERE [MAT].[Code] = @MatterCode

SET NOCOUNT OFF

END
GO

IF OBJECT_ID(N'KAAS_GetNextPrefNBatchNo',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetNextPrefNBatchNo]
GO
CREATE PROCEDURE [dbo].[KAAS_GetNextPrefNBatchNo]
(
		@IsBatchHeader      VARCHAR(1) = 'Y',
		@IsUpdateBillHeader VARCHAR(1) = 'N'
	)
AS

/*******************************************************************************************************
* Fetches the next Posting ref and batch number                                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetNextPrefNBatchNo]      								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-10    Revathy D        Created                                                               *
* 2022-02-23    Balamurugan.C    Modified - Handled T-SQL Statements    
* 2022-11-02    Ghayathri.S.V    Modified - Reduced multiple select statements to one select  for 
											fetching details from control table										   *
 *******************************************************************************************************/

BEGIN
 SET NOCOUNT ON   
   	BEGIN TRY
	  BEGIN TRAN  
			DECLARE @NEWBATCH INT
			DECLARE @NEWPREF INT
			DECLARE @NEWBILL INT

			SELECT @NEWBATCH = LASTBATCH + 1,
				   @NEWPREF  = LASTPREF + 1,
				   @NEWBILL  = LASTBILL + 1
			 FROM  [dbo].[control]


			 IF(@IsBatchHeader = 'Y')
				BEGIN
					UPDATE 
						   [dbo].[control] 
					   SET
						   [LASTBATCH] = @NEWBATCH,
						   [LASTPREF]  = @NEWPREF
				END
			 ELSE
				BEGIN 
					UPDATE 
						   [dbo].[control] 
					   SET 
						   [LASTPREF] = @NEWPREF
				END

			 IF(@IsUpdateBillHeader = 'Y')
				BEGIN
					UPDATE 
						   [dbo].[control] 
					   SET
						   [LASTBILL] = @NEWBILL
				END 

			   SELECT
					 [LASTBATCH]	AS [BatchNo],
					 [LASTPREF]		AS [Pref],
					 [CURPER]		AS [CurPer],
					 [YEAR]			AS [Year],
					 [LASTBILL]     AS [BillNo]
				FROM 
					 [dbo].[control]
			
			COMMIT TRAN

	 END TRY

	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	 END CATCH

 SET NOCOUNT OFF


END


GO






IF OBJECT_ID(N'KAAS_GetNominalAccountsDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetNominalAccountsDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_GetNominalAccountsDetails]
		(
			@Code		VARCHAR(10) = '',
			@Mode		VARCHAR(10) = 'GRID'
		)
AS
/*******************************************************************************************************
* Fetches the Nomonal details																		   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetNominalAccountsDetails]   									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-04-28    Balamurugan C        Created														   *
* 2021-05-04    Balamurugan C		 Dropdown Values Added                                             *
* 2021-06-25    Balamurugan C		 Select Nominal Details By Code                                    *
* 2021-10-12    Vinodhkumar M		 retired,Seq - columns added  
* 2021-05-02    Ghayathri.S.V        Balance - columns added
* 2022-06-01    Vignesh M   		 Branch column implemented                                         *
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
	/*MASTER DETAILS FROM NOMINAL TABLE*/
		IF(@Mode='GRID')
			BEGIN 
				SELECT	[Code],
						[Desc],
						[Type],
						[Pb],
						[Balance],
					    [Retired],
						[Seq]
				  FROM  [dbo].[Nominal]
			  ORDER BY  [Code] ASC
			END
		ELSE
			BEGIN
				SELECT	[Code],
						[Desc],
						[Type],
						[Pb],
						[Balance],
						[Seq],
						[Retired],
						[ClientAc],
						[DepositYN],
						[DepositType],
						[ChequeReq],
						[ChequePrinter],
						[LastNo],
						[Bank],
						[BankBranch],
						[BankType],
						[BankPhone],
						[BankAddress],
						[AccountNo],
						[AccountName],
						[SortCode],
						[WithdrawNames],
						[AcOpened],
						[AcClosed],
						[Iban],
						[Bic],
						[OrgIDNumber],
						[Branch]
				  FROM 	[dbo].[Nominal]
				 WHERE	[Code] = @Code
			 ORDER  BY  [Code] ASC
			END
		/*STATIC DETAILS FOR NOMINAL TYPE DROPDOWN*/
			SELECT RTRIM([NTYCODE]) AS 'Code',
				   RTRIM([NTYDESC]) AS 'Description'
			  FROM [dbo].[NominalTypes]
		 ORDER  BY [NTYCODE] ASC 

		/*STATIC DETAILS FOR NOMINAL REQPORT SEQ*/
			SELECT RTRIM([CODE]) AS 'Code',
				   RTRIM([DESC]) AS 'Desc',
				   [PB]		     AS 'Pb'
			  FROM [dbo].[NominalReportSeq]
		 ORDER  BY [Code] ASC 

		/*STATIC DETAILS FOR DEPOSIT TYPE*/
			SELECT RTRIM([CODE])        AS 'Code',
				   RTRIM([DESCRIPTION]) AS 'Description'
			  FROM [dbo].[DepositType]
		 ORDER  BY [Code] ASC 

	SET NOCOUNT OFF
END
GO

IF OBJECT_ID(N'KAAS_GetNominalBudgetDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetNominalBudgetDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_GetNominalBudgetDetails]
	(
		@Year    INT         = 0,
		@Code    VARCHAR(10) = ''
	)
AS
/*******************************************************************************************************
* Fetches the Nomonal Budget details																   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetNominalBudgetDetails]   									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-06    Balamurugan C        Created														   *
* 2021-06-23    Balamurugan C        Added Code where clause									       *
* 2024-04-24    Balamurugan C        Branch Description Added to the select list					   *                                             
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
	/*GRID DETAILS FROM NOMINAL BUDGET*/
		SELECT [NOM].[RecordID],
			   [NOM].[Code],
			   [NOM].[Branch],
			   [NOM].[Year],
			   [NOM].[Period],
			   [NOM].[Budget],
			   [BRN].[Description] AS [BranchName]
		  FROM [dbo].[NominalBudgets] [NOM]
	 LEFT JOIN [dbo].[Branch] [BRN] 
	        ON [BRN].[BranchCode] = [NOM].[Branch]
		WHERE  [NOM].[Year] = @Year AND
			   [NOM].[Code] = @Code	
		ORDER  BY [NOM].[Code] ASC 
	SET NOCOUNT OFF
END

GO

IF OBJECT_ID(N'KAAS_GetNominalLedgerDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetNominalLedgerDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_GetNominalLedgerDetails]
	(
			@PageNumber    INT = 1,
			@PageSize	   INT = 100,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Code',
			@SortOrder     VARCHAR(100) = 'ASC',
			@Year		   INT         = 0,
			@Code          VARCHAR(10) = '',
			@Flag          VARCHAR(15) = '',
			@Branch        VARCHAR(5) = ''
	)
AS

/*******************************************************************************************************
* Fetches the Nominal Ledger details																   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetNominalLedgerDetails]   									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-14    Balamurugan C        Created														   *  
* 2021-05-14    Prabhu V             Added Type column to identity Bank type Account				   *  
* 2021-09-23    Prabhu V             Added Alias name to prevent ambiguous error    				   *
* 2022-01-04    Vinodhkumar.M        Modified - Added Balance, Cleared Query from Clarion		       *       
* 2022-02-17    Prabhu.V             if branch selected data should be filtered with branch
* 2022-07-19    Ghayathri.S.V        Modified - To implement dynamic sql query to fetch sort
									            and search datas and fetch debtor ledger balances      * 
* 2022-08-09    Ghayathri.S.V		Modified - To add matter column and removed columns for 
											   server side pagination search							
* 2024-03-01    Revathy.D		     Modified - Included RecNo,Reconcile Status fields                  *											   
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
	/*NOMINAL TYPE LIST*/
	IF(@Flag='NOMINALDETAILS')
		BEGIN
			SELECT 
				 [Code],
				 [Desc],
				 [Type]
			FROM [dbo].[Nominal]
			ORDER BY [Code] ASC
		END

	/*GRID DETAILS FROM NOMINAL LEDGER*/
	IF(@Flag='NOMINALLEDGER')
		BEGIN
			DECLARE		   @sql        NVARCHAR(max)
			DECLARE		   @search	   NVARCHAR(500) = ''
			DECLARE		   @offset	   INT = @PageSize * (@PageNumber -1)
			SET	  @sql =  'SELECT     [NOL].[Pref],
									  [NOL].[Date],
									  [NOL].[RecordId],
									  [NOL].[Code],
									  [NOL].[Ref],
									  [NOL].[Narr],
									  [NOL].[Matter],
									  [NOL].[Supp],
									  [NOL].[Value],
									  [NOL].[BatchNo],
									  [NOL].[Branch],
									  [NOL].[Year],
									  [NOL].[ClearedDate],
									  [BH].[Type],
									  [NOL].[RecNo],
									  CASE WHEN ISNULL([NOL].[RecNo],0) <= 0 
									  THEN ''Outstanding''
									  ELSE ''Reconciled'' END AS [RecStatus]
			                 FROM     [dbo].[NominalLedger] [NOL] 
					    LEFT JOIN     [BatchH] [BH] 
							   ON     [BH].[BatchNo] = [NOL].[BatchNo]
				            WHERE     [NOL].[Code] = ''' + @Code  + '''' +  
			                 'AND     [NOL].[Year] = ' + CAST(@Year AS NVARCHAR(10))  +  
			                 'AND     ( [NOL].BRANCH = ''' + @Branch  + '''' + ')
							  AND      ( 
										 [NOL].[Pref]		LIKE' + '''%'  + @SearchString + '%' + '''' +	
										 'OR
										 [NOL].[Date]		LIKE ' + '''%' + @SearchString + '%' + '''' +
										 'OR
										 [NOL].[Ref]		LIKE ' + '''%' + @SearchString + '%' + '''' +
										 'OR
										 [NOL].[Narr]		LIKE ' + '''%' + @SearchString + '%' + '''' +
										 'OR
										 [NOL].[BatchNo]    LIKE ' + '''%' + @SearchString + '%' + '''' +
										 'OR
										 [NOL].[Matter]       LIKE ' + '''%' + @SearchString + '%' + '''' +
						              ')
		               ORDER BY '      +    @SortColumn + ' '  + @SortOrder + ' ' +
	                    'OFFSET '      +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
			        'FETCH NEXT '      +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

			EXEC Sp_executesql @sql

						 SELECT        COUNT(*)  'TotalRecord'
						   FROM        [dbo].[NominalLedger] [NOL]
					  LEFT JOIN        [BatchH] [BH] 
							 ON        [BH].[BatchNo] = [NOL].[BatchNo]
						  WHERE        [NOL].[Code] = @Code 
							AND		   [NOL].[Year] = @Year
							AND		   ([NOL].BRANCH = @Branch)	
							AND		   ( 
										  [NOL].[Pref]     LIKE '%' + @SearchString + '%'  
										  OR
										  [NOL].[Date]	   LIKE '%' + @SearchString + '%' 
										  OR
										  [NOL].[Ref]      LIKE '%' + @SearchString + '%'
										  OR
										  [NOL].[Narr]	   LIKE '%' + @SearchString + '%'
										  OR
										  [NOL].[BatchNo]  LIKE '%' + @SearchString + '%'
										  OR
										  [NOL].[Matter]     LIKE '%' + @SearchString + '%'

							          )

			/*Query for Balance*/
			SELECT   ISNULL(SUM(ISNULL([NOL].[VALUE], 0)), 0) AS Balance 
			  FROM  [dbo].[Nominalledger] [NOL]
			 WHERE  [NOL].[YEAR] = @Year
			   AND  [NOL].[CODE] = @Code
			   AND  (@Branch = '' OR [NOL].BRANCH = @Branch)

			 /*Query for Cleared Balance*/
			SELECT ISNULL(SUM(ISNULL([NML].[VALUE], 0)), 0)  AS ClearedBalance
              FROM [dbo].[NominalLedger] AS [NML] 
             WHERE [NML].[CODE] = @Code
               AND ISNULL([NML].[ClearedDate], [NML].[DATE]) <= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
               AND [NML].[YEAR] = @Year
			   AND (@Branch = '' OR [NML].BRANCH = @Branch)
		END
	SET NOCOUNT OFF
END

GO


 
IF  EXISTS 
(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KAAS_GetNominalList]') AND type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[KAAS_GetNominalList]
END	
GO
CREATE PROCEDURE [dbo].[KAAS_GetNominalList]

AS

/*******************************************************************************************************
* Fetches the Nominal list                                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetNominalList]      											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-03-23    Revathy D        Created   
* 2022-02-01    Ghayathri SV	 Modified : Added Type column to selecte statement
 *******************************************************************************************************/

BEGIN

SELECT 
	NOM.[CODE] AS Code,
    NOM.[DESC] AS [Description],
	NOM.[TYPE] AS [Type]
FROM
	[dbo].[Nominal] NOM
ORDER BY
	NOM.[CODE] ASC


END

GO






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


CREATE PROCEDURE
       [dbo].[KAAS_GetOpenMatterDetails]
AS
/************************************************************************************
 * Fetching Open Matter Details														*
 *																					*
 * 2021-03-10   Prabhu.V		 Created to Fetch the Open Matter details for SAM   *
 * 2021-10-07   Balamurugan.C	 Added ChargeBal Field								*
 * 2021-11-23   Vinodhkumar.M	 Added outlayBal,CLientCurBal,ClientDepBal Field    *
 * 2022-01-20   Vinodhkumar.M	 Added CloseDate,OriginalClosedDate,RepenDate Field 
 * 2022-02-25   Ghayathri.S.V	 Modified the Order by Clause according to Matter Code *
 ************************************************************************************/
BEGIN
SELECT  A.[Code], 
		A.[ClientCode], 
		A.[Description],
		A.[FECODE] As FeeCode, 
		A.[Dept], 
		A.[WTYPE] As WorkType, 
		A.[Branch], 
		A.[Comment], 
		A.[FileNum], 
		A.[ThirdPart], 
		A.[THPARTSOL], 
		A.[OldRef], 
		A.[PCode], 
		A.[PFECode], 
		A.[User1], 
		A.[User2], 
		A.[User3], 
		A.[FileColour], 
		A.[OUTFILENO], 
		A.[Closed],
		A.[ChargeBal], 
		B.[CODE], 
		B.[Name], 
		B.[Address], 
		B.[FE], 
		B.[CLIENT], 
		B.[CLIENTGROUP], 
		B.[OTHERREF], 
		B.[OPSISREF], 
		B.[CONTACTNO], 
		B.[COMPBILLONOFF], 
		B.[TAXTYPE],
		A.[OutlayBal],
		A.[ClientCurBal],
		A.[ClientDepBal],
		A.[CloseDate],
		A. [ORGCLOSEDDATE] AS [OriginalClosedDate],
		A.[REOPENEDDATE]   AS [ReopenedDate]

FROM				dbo.[Matters] A 
LEFT JOIN			dbo.[RecentMatterList] R ON R.[MATTER] =  A.[Code] AND R.[FEE]= 'ADM'
LEFT OUTER JOIN		dbo.[contacts] B ON  A.[CLIENTCODE]= B.[CODE]   
WHERE				[Closed] <> 'Y'  
--GROUP BY [A].[Code]
ORDER BY			A.[Code] ASC
END

GO


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

AS

/*******************************************************************************************************
* Fetches the Nominal list                                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[GetOutlayCodeList]      											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-03-23    Revathy D        Created                                                               *
* 2021-08-20    Vinodhkumar.M      Modified-Include Right Trim                                         *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

SELECT 
	RTRIM(OCD.[CODE]) AS Code,
    RTRIM(OCD.[DESCRIPTION]) AS [Description]
FROM
	[dbo].[OutlayCode] OCD
ORDER BY
	OCD.[CODE] ASC

SET NOCOUNT OFF

END

GO



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

CREATE PROCEDURE [dbo].[KAAS_GetOutstandingInvoices] (
       @MatterCode VARCHAR(20))
AS
/****************************************************************************************
 * Gets the outstanding invoices for a matter                                           *
 *                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_GetSAMOutstandingInvoices]                       *
 *                                                                                      *
 * Modification History:                                                                *
 * 2020-05-18   Revathy         Copied from KAAS_GetOutstandingInvoices                 *
 * 2020-10-11   Vinodhkuamr M   Updated - Removed space in Alias Names                  *
 * 2022-02-03   Balamurugan C   Changes in query to fetch the Batch Posted or Not       *
 * 2024-02-22   John Ginnane    Refactored and renamed procedure                        *
 ****************************************************************************************/
BEGIN
    SET NOCOUNT ON

    SELECT LTRIM(RTRIM([DTL].[MATTER]))                   AS [MatterCode],
           ISNULL(LTRIM(RTRIM([SM].[Description])), '''') AS [MatterDescription],
           ISNULL(LTRIM(RTRIM([SM].[Name])), '''')        AS [ClientName],
           ISNULL(LTRIM(RTRIM([DTL].[TYPE])), '''')       AS [Type],
           LTRIM(RTRIM([DTL].[CLIENT]))                   AS [ClientCode],
           [DTL].[DATE]                                   AS [Date],
           ISNULL(LTRIM(RTRIM([DTL].[REF])), '''')        AS [Ref],
           [DTL].[BATCHNO]                                AS [BatchNo],
           [DTL].[PREF]                                   AS [PRef],
           ISNULL(LTRIM(RTRIM([DTL].[NARR])), '''')       AS [Narrative],
           ISNULL([DTL].[ORIGINAL], 0)                    AS [Original],
           ISNULL([DTL].[OSVALUE], 0)                     AS [OSValue],
           ISNULL([DTL].[ORFEES], 0)                      AS [OriginalFees],
           ISNULL([DTL].[OROUTLAY], 0)                    AS [OriginalOutlay],
           ISNULL([DTL].[ORVAT], 0)                       AS [OriginalVAT],
           ISNULL([DTL].[OSFEES], 0)                      AS [OSFees],
           ISNULL([DTL].[OSOUTLAY], 0)                    AS [OSOutlay],
           ISNULL([DTL].[OSVAT], 0)                       AS [OSVAT],
           ISNULL(LTRIM(RTRIM([DTL].[VATCODE])), '''')    AS [VATCode],
           ISNULL([DTL].[PER], 0)                         AS [Period],
           ISNULL([DTL].[YEAR], 0)                        AS [Year],
           [DTL].[RECORDID]                               AS [RecordID],
           ISNULL([BAD].[PreBilledOutlay], 0)             AS [PreBilledOutlay]
      FROM [dbo].[DebtorsLedger] AS [DTL]
           INNER JOIN [dbo].[SearchMatters] AS [SM]
                   ON [SM].[Code] = [DTL].[MATTER]
           OUTER APPLY (SELECT TOP 1 SUM([BAD].[VALUE]) AS [PreBilledOutlay]
                          FROM [dbo].[BatchDetails] AS [BAD]
                         WHERE [BAD].[BATCHNO] = [DTL].[BATCHNO]
                           AND [BAD].[OUTLAY] = 'O'
                           AND [BAD].[PreBilledOutlay] = 1) AS [BAD]
     WHERE [DTL].[MATTER] = @MatterCode
       AND [DTL].[OSVALUE] > 0
           ORDER BY [DTL].[DATE] ASC,
                    [DTL].[RECORDID] ASC

  --  SELECT LTRIM(RTRIM([DTL].[MATTER]))                              AS [MatterCode],
  --         ISNULL(LTRIM(RTRIM([DTL].[TYPE])), '')                    AS [Type],
  --         LTRIM(RTRIM([DTL].[CLIENT]))                              AS [ClientCode],
  --         [DTL].[DATE]                                              AS [Date],
  --         ISNULL(LTRIM(RTRIM([DTL].[REF])), '')                     AS [Ref],
  --         [DTL].[BATCHNO]                                           AS [BatchNo],
  --         [DTL].[PREF]                                              AS [PRef],
  --         ISNULL(LTRIM(RTRIM([DTL].[NARR])), 0)                     AS [Narrative],
  --         ISNULL([DTL].[ORIGINAL], 0)                               AS [Original],
  --         ISNULL([DTL].[ORFEES], 0)                                 AS [OriginalFees],
  --         ISNULL([DTL].[OROUTLAY], 0)                               AS [OriginalOutlay],
  --         ISNULL([DTL].[ORVAT], 0)                                  AS [OriginalVAT],
  --         ISNULL([DTL].[OSVALUE], 0)                                AS [OSValue],
  --         ISNULL([DTL].[OSFEES], 0)                                 AS [OutstandingFees],
  --         ISNULL([DTL].[OSOUTLAY], 0)                               AS [OutstandingOutlay],
  --         ISNULL([DTL].[OSVAT], 0)                                  AS [OutstandingVAT],
  --         ISNULL(LTRIM(RTRIM([DTL].[VATCODE])), '')                  AS [VATCode],
  --         ISNULL([DTL].[PER], 0)                                    AS [Period],
  --         ISNULL([DTL].[YEAR], 0)                                                                             AS [Year],
  --         ISNULL(LTRIM(RTRIM([DTL].[FEECODE])), '')                                                                 AS [LedgerFeeEarnerCode],
  --         ISNULL(LTRIM(RTRIM(LFE.[NAME])), '')                                               AS [LedgerFeeEarner],
  --         CONVERT(INT, [DTL].[RECORDID])                                               AS [RecordID],
  --         RTRIM(ISNULL(MAT.[FECODE], '')) AS [FeeEarnerCode],
  --         RTRIM(ISNULL(FE.[NAME], '')) AS [FeeEarner],
  --         RTRIM(ISNULL(MAT.[DEPT], '')) AS [Dept],
  --         RTRIM(ISNULL(MAT.[WTYPE], '')) AS [WType],
  --         RTRIM(ISNULL(MAT.[BRANCH], '')) AS [Branch],
  --         ISNULL(MAT.[FILENUM], 0) AS [FileNum],
  --         RTRIM(ISNULL(MAT.[THIRDPART], '')) AS [ThirdPart],
  --         RTRIM(ISNULL(MAT.[ThPartSol], '')) AS [ThPartSol],
  --         RTRIM(ISNULL(MAT.[OldRef], '')) AS [OldRef],
  --         RTRIM(ISNULL(MAT.[PCODE], '')) AS [PCODE],
  --         RTRIM(ISNULL(MAT.[PFECODE], '')) AS [PFeeEarnerCode],
  --         RTRIM(ISNULL(PFE.[NAME], '')) AS [PFeeEarner],
  --         RTRIM(ISNULL(MAT.[USER1], '')) AS [User1],
  --         RTRIM(ISNULL(MAT.[USER2], '')) AS [User2],
  --         RTRIM(ISNULL(MAT.[USER3], '')) AS [User3],
  --         RTRIM(ISNULL(MAT.[FileColour], '')) AS [FileColour],
  --         ISNULL(MAT.[OUTFILENO], 0) AS [OutFileNo],
  --         RTRIM(ISNULL(CTC.[NAME], '')) AS [ClientName],
  --         RTRIM(ISNULL(CTC.[FE], '')) AS [ClientFeeEarnerCode],
  --         RTRIM(ISNULL(CFE.[NAME], '')) AS [ClientFeeEarner],
  --         CASE WHEN RTRIM(ISNULL(CTC.[CLIENT], 'N')) = 'Y'
  --                   THEN 'Y'
  --              ELSE 'N' END AS [Client],
  --         RTRIM(ISNULL(CTC.[OTHERREF], '')) AS [OtherRef],
  --         RTRIM(ISNULL(CTC.[OPSISREF], '')) AS [OpsisRef],
  --         ISNULL(CTC.[CONTACTNO], 0) AS [ContactNo],
  --         ISNULL(CTC.[COMPBILLONOFF], 0) AS [CompBillOnOff],
  --         RTRIM(ISNULL(CTC.[CLIENTGROUP], '')) AS [ClientGroup],
  --         RTRIM(ISNULL(CTC.[TAXTYPE], '')) AS [TaxType],
  --         RTRIM(ISNULL(FCL.[COLOURDESC], '')) AS [FileColourDescription],
  --         ISNULL(FCL.[RGBColour], -1) AS [FileColourRGB],
  --         CASE WHEN ISNULL([DTL].[BATCHNO], 0) IN (SELECT DISTINCT [ALL].[BATCHNO]
  --                                                            FROM [dbo].[DebtorsLedger] [DBL]
  --                                                       LEFT JOIN BatchDetails [BAD]
  --                                                              ON [DBL].[BatchNo] = [BAD].[AllocBatch]
  --                                                       LEFT JOIN [dbo].[Allocations] [ALL]
  --                                                              ON [ALL].[BatchNo] = [DBL].[BatchNo]
  --                                                 )
  --              THEN 'Y'
  --          ELSE 'N' END AS [Isallocated],
  --        ISNULL([BAH].[Posted] , 'N') AS [Posted]
  --    FROM [dbo].[DebtorsLedger] AS [DTL]
  --         LEFT OUTER JOIN [dbo].[matters] MAT
  --                         LEFT OUTER JOIN [dbo].[Handlers] FE
  --                                      ON FE.[CODE] = MAT.[FECode]
  --                         LEFT OUTER JOIN [dbo].[Handlers] PFE
  --                                      ON PFE.[CODE] = MAT.[PFECODE]
  --                         LEFT OUTER JOIN [dbo].[contacts] CTC
  --                                         LEFT OUTER JOIN [dbo].[Handlers] CFE
  --                                                      ON CFE.[CODE] = CTC.[FE]
  --                                      ON  MAT.[ClientCode]= CTC.[Code]
  --                 ON  [DTL].[MATTER] = MAT.[Code]
  --         LEFT OUTER JOIN [dbo].[Handlers] LFE
  --                     ON LFE.[CODE] = [DTL].[FEECODE]
  --         LEFT OUTER JOIN [dbo].[FileColours] FCL
  --                      ON FCL.[COLOURCODE] = MAT.[FileColour]
  --         LEFT OUTER JOIN [dbo].[BatchH] [BAH]
  --                      ON [DTL].[BatchNo] = [BAH].[BatchNo]
  --   WHERE [DTL].[MATTER] = @MatterCode
  --     AND [DTL].[OSVALUE] > 0
  --     AND [DTL].[DATE] IS NOT NULL
  --ORDER BY [DTL].[RECORDID] ASC

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

CREATE PROCEDURE [dbo].[KAAS_GetOutstandingSupplierBills] (
       @SupplierCode  VARCHAR(10),
       @HandlerCode   VARCHAR(10) = NULL)
AS
/********************************************************************************************************
 * Fetches outstanding bills from the Supplier Ledger                                                   *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_GetOutstandingSupplierBills]                                     *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-06-04    Revathy D        Created                                                               *
 * 2024-02-12    John Ginnane     #17689 - Refactored and renamed stored procedure                      *
 ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON
    
    SELECT LTRIM(RTRIM([SPL].[SUPP]))   AS [SupplierCode],
           LTRIM(RTRIM([SPL].[TYPE]))   AS [Type],
           [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([SPL].[DATE], @HandlerCode) AS [Date],
           LTRIM(RTRIM([SPL].[REF]))    AS [Ref],
           ISNULL([SPL].[BATCHNO], 0)   AS [BatchNo],
           ISNULL([SPL].[PREF], 0)      AS [Pref],
           LTRIM(RTRIM([SPL].[NARR]))   AS [Narrative],
           ISNULL([SPL].[ORIGINAL], 0)  AS [Original],
           ISNULL([SPL].[OSVALUE], 0)   AS [OSValue],
           dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([SPL].[ENTRYDATE], @HandlerCode) AS [EntryDate],
           LTRIM(RTRIM([SPL].[MATTER])) AS [Matter], 
           ISNULL([SPL].[RECORDID], 0)  AS [RecordID]
      FROM dbo.[SupplierLedger] AS [SPL]
     WHERE [SPL].[SUPP] = @SupplierCode
       AND [SPL].[OSVALUE] < 0
           ORDER BY [SPL].[SUPP] DESC,
                    [SPL].[DATE] DESC,
                    [SPL].[RECORDID] DESC

    SET NOCOUNT OFF
END
GO
IF  EXISTS 
(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KAAS_GetPaymentBatches]') AND type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[KAAS_GetPaymentBatches]
END	
GO
/****** Object:  StoredProcedure [dbo].[KAAS_GetPaymentBatches]    Script Date: 19-03-2021 14:46:11 ******/
 
CREATE PROCEDURE [dbo].[KAAS_GetPaymentBatches] 
(
@handlerCode VARCHAR(10) = NULL
)

AS

/*******************************************************************************************************
* Fetches the batch details of unposted payments                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetPaymentBatches]   											   *
*                                                                                                      *
* Modification History:                                                                                *
* 11 Mar 2021    Natarajan S        Created															   *
* 27-May-2021	 Balamurugan C		Modified-Add few columns                                           *
* 20-August-2021 Vinodhkumar M		Modified-Add Branch columns                                        *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

		   SELECT
				[BAT].[BATCHNO]			AS [BatchNo],
				[BAT].[TYPE]			AS [Type],
				[BAT].[CODE]			AS [Code],
				[BAT].[REF]				AS [Ref],
				[dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[Date], @handlerCode)  AS [Date],
				[BAT].[MATTER]			AS [Matter],
				[BAT].[BRANCH]			AS [Branch],
				[BAT].[SUPP]			AS [Supp],
				[BAT].[NARR]			AS [Narr],
				[BAT].[VALUE]			AS [Value],
				[BAT].[POSTED]			AS [Posted],
				[BAT].[PERNO]			AS [PerNo],
				[BAT].[YEAR]			AS [Year],
				[BAT].[ENTRYDATE]		AS [EntryDate],
				[BAT].[RECNO]			AS [RecNo],
				[BAT].[CHEQUEREQNO]		AS [ChequeReqNo],
				[BAT].[PREF]			AS [Pref],
				[BAT].[PAYEE]			AS [Payee],
				[dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[ENTRYDATE], @handlerCode)  AS [ENTRYDATE],
				[BAT].[USERCODE]		AS [UserCode],
				[BAT].[EFTYorN]			AS [EFTYorN],
				[BAT].[EFTSent]			AS [EFTSent],
				[BAT].[ThirdParty]		AS [Thirdparty],
				[BAT].[PayClient]		AS [PayClient],
				[BAT].[OnceOffPayment]		AS [OnceOffPayment],
				[BAT].[ClientCode]		AS [ClientCode]

		    FROM	
				[dbo].[BatchH] BAT 
		   WHERE 
				[BAT].[TYPE] = 'P' AND  [BAT].[POSTED] = 'N'
		   ORDER BY
				[BAT].[POSTED] ASC,
				[BAT].[ENTRYDATE] ASC

SET NOCOUNT OFF

END

GO

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

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
 
CREATE PROCEDURE [dbo].[KAAS_GetPaymentClientList]


AS

/*******************************************************************************************************
* Fetches the Payment Screen -Client Details                                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetPaymentClientList]      									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-19    Balamurugan.C        Created                                                               *
 *******************************************************************************************************/

BEGIN

SELECT 
		[Code],
		[OtherRef],
		[Name],
		[Address],
		[BankName],
		[BankSortCode],
		[BankAccNo],
		[Iban],
		[Bic],
		[EFTEmailAddress]
FROM
	[dbo].[Contacts]
ORDER BY
		[Code] ASC


END

GO

IF OBJECT_ID(N'KAAS_GetPaymentSupplierList', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetPaymentSupplierList]
END
GO
CREATE PROCEDURE [dbo].[KAAS_GetPaymentSupplierList]
	(
		@ThirdParty   VARCHAR(1)  = '',
		@Code		  VARCHAR(10) = ''
	)

AS
/*******************************************************************************************************
* Fetches the Payment Screen -Supplier Details,Master Supplier Details                                 * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetPaymentSupplierList]      									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-19    Balamurugan.C        Created														   *
* 2021-06-16	Balamurugan.C		 Modified-Added Columns                                            *
* 2022-01-04	Vinodhkumar.M		 Modified-Added TPBal,Balance,BalanceFwd Columns                   *
* 2023-10-12	Vignesh M    		 Modified-Null exception is handled				                   *
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
		    SELECT
				 RTRIM([Code]) AS 'Code', 
				 [Description]
			FROM [dbo].[ServiceCodes]

		    SELECT 
		    		 [Code],
		    		 [Name],
		    		 [Address],
		    		 [Nominal],
		    		 [Phone],
		    		 ISNULL([EmailAddress],'') AS [EmailAddress],
		    		 [TaxNo],
		    		 [ServiceCode],
		    		 ISNULL([VATNo],'') AS [VATNo],
		    		 [DeftpStatus],
		    		 ISNULL([BankName],'') AS [BankName],
		    		 ISNULL([BankAddress],'') AS [BankAddress],
		    		 ISNULL([BankSortCode],'') AS [BankSortCode],
		    		 ISNULL([BankAccNo],'') AS [BankAccNo],
		    		 ISNULL([Iban],'') AS [Iban],
		    		 ISNULL([Bic],'') AS [Bic],
		    		 ISNULL([BankType],'') AS [BankType],
		    		 ISNULL([EFTEmailAddress],'') AS [EFTEmailAddress],
		    		 [Retired],
					 [TPBAL]					AS	[ThirdPartyBalance],
					 [BALANCE]					AS  [Balance],
					 [BALANCEFWD]				AS  [BalanceFwd]
		    FROM     [dbo].[Suppliers]
		    WHERE    [DeftpStatus] = CASE WHEN @ThirdParty='Y' THEN 'Y' ELSE [DeftpStatus] END AND
		    	     [Code]= CASE WHEN ISNULL(@Code,'')<>'' THEN @Code ELSE [Code] END
		    ORDER BY [Code] ASC

	SET NOCOUNT OFF
END
GO


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


CREATE PROCEDURE [dbo].[KAAS_GetPostedBatchDetails]
                (@Search        NVARCHAR(MAX),
				 @PageNumber    INT,
				 @PageSize	    INT,
				 @SearchString  VARCHAR(500) = '',
				 @SortColumn    VARCHAR(100) = 'BatchNo',
				 @SortOrder     VARCHAR(100) = 'ASC',
				 @handlerCode   VARCHAR(10) = '')
AS

/*******************************************************************************************************
* Fetches the batch details of posted receipts                                                         * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetPostedBatchDetails]   										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2024-01-31    Revathy D        Created                                                               *
* 2024-03-26    Vignesh M        Modified - Date filter is implemented                                 *
 *******************************************************************************************************/

BEGIN
	SET NOCOUNT ON
	DECLARE			      @sql		NVARCHAR(max),
				       @offset		INT = @PageSize * (@PageNumber -1),
			    @WhereConditon		NVARCHAR(max)
	DECLARE        @searchtext      VARCHAR(MAX)  
    DECLARE		    @andortype      VARCHAR(3)      
	DECLARE    @andortypevalue      VARCHAR(200)  
	DECLARE      @operatorType      VARCHAR (50)    
	DECLARE      @andorbatchno      VARCHAR(3)      
	DECLARE @andorbatchnovalue      VARCHAR(200)  
	DECLARE   @operatorbatchno      VARCHAR (50)     
	DECLARE         @andorpref      VARCHAR(3)      
	DECLARE    @andorprefvalue      VARCHAR(200)
	DECLARE      @operatorpref      VARCHAR (50)      
	DECLARE          @andorref      VARCHAR(3)      
	DECLARE     @andorrefvalue      VARCHAR(200)
	DECLARE       @operatorref      VARCHAR (50)      
	DECLARE      @andorfeecode      VARCHAR(3)      
	DECLARE @andorfeecodevalue      VARCHAR(200)
	DECLARE   @operatorfeecode      VARCHAR (50)      
	DECLARE         @andordate      VARCHAR(3)      
	DECLARE    @andordatevalue      VARCHAR(200)
	DECLARE      @operatordate      VARCHAR (50)      
	DECLARE        @andortotal      VARCHAR(3)      
	DECLARE   @andortotalvalue      VARCHAR(200)
	DECLARE     @operatortotal      VARCHAR (50)
	DECLARE       @andormatter      VARCHAR(3)      
	DECLARE  @andormattervalue      VARCHAR(200)
	DECLARE    @operatormatter      VARCHAR (50)      
	DECLARE         @andorcode      VARCHAR(3)      
	DECLARE    @andorcodevalue      VARCHAR(200)
	DECLARE      @operatorcode      VARCHAR (50) 
	DECLARE         @andorsupp      VARCHAR(3)      
	DECLARE    @andorsuppvalue      VARCHAR(200)  
	DECLARE      @operatorsupp      VARCHAR (50)     
	DECLARE         @andornarr      VARCHAR(3)      
	DECLARE    @andornarrvalue      VARCHAR(200)  
	DECLARE      @operatornarr     VARCHAR (50)     
      
	DECLARE               @iSL      INT 
	DECLARE @selectORCondition      VARCHAR(MAX) = ''  
	DECLARE			 @operator      VARCHAR(50)  = ' LIKE '

BEGIN TRY      
EXEC sp_xml_preparedocument @iSL OUTPUT, @Search      
END TRY      
BEGIN CATCH      
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<search/>'      
END CATCH  
 
 DECLARE @StartRow INT;
DECLARE @EndRow INT;

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

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

SELECT    
       @searchtext        = ISNULL(SRC.[search], ''),
	   @andortype         = ISNULL(SRC.[andortype], ''),      
       @andortypevalue    = ISNULL(SRC.[andortypevalue], ''),
	   @operatorType      = ISNULL(SRC.[operatortype],''), 
       @andorbatchno      = ISNULL(SRC.[andorbatchno], ''),      
       @andorbatchnovalue = ISNULL(SRC.[andorbatchnovalue], ''),      
       @operatorbatchno   = ISNULL(SRC.[operatorbatchno],''),
	   @andorpref         = ISNULL(SRC.[andorpref], ''),      
       @andorprefvalue    = ISNULL(SRC.[andorprefvalue], ''),      
       @operatorpref      = ISNULL(SRC.[operatorpref],''),
	   @andorref          = ISNULL(SRC.[andorref], ''),      
       @andorrefvalue     = ISNULL(SRC.[andorrefvalue], ''),
	   @operatorref       = ISNULL(SRC.[operatorref],''),      
       @andordate         = ISNULL(SRC.[andordate], ''),      
       @andordatevalue    = ISNULL(SRC.[andordatevalue], ''),      
       @operatordate      = ISNULL(SRC.[operatordate],''),
	   @andortotal        = ISNULL(SRC.[andortotal], ''),      
       @andortotalvalue   = ISNULL(SRC.[andortotalvalue], ''),
	   @operatortotal     = ISNULL(SRC.[operatortotal],''),      
       @andormatter       = ISNULL(SRC.[andormatter], ''),      
       @andormattervalue  = ISNULL(SRC.[andormattervalue], ''), 
	   @andorcode         = ISNULL(SRC.[andorcode], ''),      
       @andorcodevalue    = ISNULL(SRC.[andorcodevalue], ''),      
       @andorsupp         = ISNULL(SRC.[andorsupp], ''),      
       @andorsuppvalue    = ISNULL(SRC.[andorsuppvalue], ''),     
       @andornarr         = ISNULL(SRC.[andornarr], ''),      
       @andornarrvalue    = ISNULL(SRC.[andornarrvalue], ''),      
       @andorfeecode      = ISNULL(SRC.[andorfee], ''),      
       @andorfeecodevalue = ISNULL(SRC.[andorfeevalue], '')      
  FROM OPENXML(@iSL, N'search')      
  WITH (      
        [search]              VARCHAR(MAX)    '@search',         
        [andortype]           VARCHAR(3)      'andor/andorfield[@name="Type"]/@andor',      
        [andortypevalue]      VARCHAR(200)    'andor/andorfield[@name="Type"]/@search',
		[operatortype]        VARCHAR(100)    'andor/andorfield[@name="Type"]/@operator',      
        [andorbatchno]        VARCHAR(3)      'andor/andorfield[@name="BatchNo"]/@andor',      
        [andorbatchnovalue]   VARCHAR(100)    'andor/andorfield[@name="BatchNo"]/@search',
		[operatorbatchno]     VARCHAR(100)    'andor/andorfield[@name="BatchNo"]/@operator',       
        [andorpref]           VARCHAR(3)      'andor/andorfield[@name="Pref"]/@andor',      
        [andorprefvalue]      VARCHAR(100)    'andor/andorfield[@name="Pref"]/@search',   
		[operatorpref]        VARCHAR(100)    'andor/andorfield[@name="Pref"]/@operator',   
        [andorref]            VARCHAR(3)      'andor/andorfield[@name="Ref"]/@andor',      
        [andorrefvalue]       VARCHAR(100)    'andor/andorfield[@name="Ref"]/@search',
		[operatorref]         VARCHAR(100)    'andor/andorfield[@name="Ref"]/@operator',      
        [andordate]           VARCHAR(3)      'andor/andorfield[@name="Date"]/@andor',      
        [andordatevalue]      VARCHAR(100)    'andor/andorfield[@name="Date"]/@search',      
        [operatordate]        VARCHAR(100)    'andor/andorfield[@name="Date"]/@operator',
		[andortotal]          VARCHAR(3)      'andor/andorfield[@name="Value"]/@andor',      
        [andortotalvalue]     VARCHAR(100)    'andor/andorfield[@name="Value"]/@search',      
        [operatortotal]       VARCHAR(100)    'andor/andorfield[@name="Value"]/@operator',
		[andormatter]         VARCHAR(3)      'andor/andorfield[@name="Matter"]/@andor',      
        [andormattervalue]    VARCHAR(100)    'andor/andorfield[@name="Matter"]/@search',     
		[operatormatter]      VARCHAR(100)    'andor/andorfield[@name="Matter"]/@operator',
		[andorcode]           VARCHAR(3)      'andor/andorfield[@name="Code"]/@andor',      
        [andorcodevalue]      VARCHAR(100)    'andor/andorfield[@name="Code"]/@search',      
        [operatorcode]        VARCHAR(100)    'andor/andorfield[@name="Code"]/@operator',
		[andorsupp]           VARCHAR(3)      'andor/andorfield[@name="Supp"]/@andor',      
        [andorsuppvalue]      VARCHAR(100)    'andor/andorfield[@name="Supp"]/@search',
		[operatorsupp]        VARCHAR(100)    'andor/andorfield[@name="Supp"]/@operator',
		[andornarr]           VARCHAR(3)      'andor/andorfield[@name="Narr"]/@andor',      
        [andornarrvalue]      VARCHAR(100)    'andor/andorfield[@name="Narr"]/@search',
		[operatornarr]        VARCHAR(100)    'andor/andorfield[@name="Narr"]/@operator',
		[andorfee]            VARCHAR(3)      'andor/andorfield[@name="Fee"]/@andor',      
        [andorfeevalue]       VARCHAR(100)    'andor/andorfield[@name="Fee"]/@search',
		[operatorfee]         VARCHAR(100)    'andor/andorfield[@name="Fee"]/@operator') SRC      
                 
	  EXEC sp_xml_removedocument @iSL

	  /*Date Filter*/
	     DECLARE @isDateFilter      NVARCHAR(max) = '0'
		 DECLARE @Day               NVARCHAR(max) = '00'
		 DECLARE @Month             NVARCHAR(max) = '00'
		 DECLARE @Year              NVARCHAR(max) = '1900'
		 DECLARE @DateFilter        NVARCHAR(max) = ''
		 SET @DateFilter = [dbo].[KAAS_FN_DateFilter](@SearchString)
		 IF @DateFilter != ''
		 BEGIN
			SET @Day   = SUBSTRING(@DateFilter,1,2)
			SET @Month = SUBSTRING(@DateFilter,4,2)
			SET @Year  = SUBSTRING(@DateFilter,7,4)
			IF @Day != '00' OR @Month != '00' OR @Year != '1900'
			BEGIN
				SET @isDateFilter = '1'
			END
		 END
	  /*Date Filter*/

	 	SET			  @sql = 'SELECT 
			                IDENTITY(INT, 1,1) AS [RowNumber],
			                       * INTO
			                     #TEMP
		                      FROM
							 
								 (SELECT [BAH].[BatchNo], 
								        CASE WHEN RTRIM(ISNULL([BAH].[Type],'''')) = ''P''
										  THEN ''Payment''
									    WHEN RTRIM(ISNULL([BAH].[Type],'''')) = ''B''
							              THEN ''Bill''
									    WHEN RTRIM(ISNULL([BAH].[Type],'''')) = ''T''
										  THEN ''Transfer''
										WHEN RTRIM(ISNULL([BAH].[Type],'''')) = ''I''
										  THEN ''Invoice'' 
										WHEN RTRIM(ISNULL([BAH].[Type],'''')) = ''R''
										  THEN ''Receipt''
										WHEN RTRIM(ISNULL([BAH].[Type],'''')) = ''J''
										  THEN ''Journal'' ELSE '''' 
										END AS  Type, 
										[BAH].[Code], 
										RTRIM(ISNULL([BAH].[Ref],'''')) [Ref], 
										[BAH].[Date],  
										[BAH].[Matter], 
										[BAH].[SUBTOT],
										[BAH].[Supp], 
										[BAH].[Narr], 
										[BAH].[Value], 
										[BAH].[Posted],   
										[BAH].[Branch],										
										[BAH].[Pref],
                                        [BAH].[ClientCode],
										[BAH].[FEE]
								 FROM   [dbo].[BatchH] [BAH]
							LEFT JOIN   [DBO].[matters] [MAT] ON [MAT].[Code] = [BAH].[MATTER]
							    WHERE   [BAH].[POSTED] = ''Y'''
							IF @isDateFilter != '0'
							BEGIN
								IF @Day != '00'
								BEGIN
									SET @sql += N' 
												AND 
												( 
														DAY([BAH].[Date])	  =  ' + ''+ @Day +'' +
											  ')'
								END
								IF @Month != '00'
								BEGIN
									SET @sql += N' 
												AND 
												( 
														MONTH([BAH].[Date])	  =  ' + ''+ @Month +'' +
											  ')'
								END
								IF @Year != '1900'
								BEGIN
									SET @sql += N' 
												AND 
												( 
														YEAR([BAH].[Date])	  =  ' + ''+ @Year +'' +
											  ')'
								END
							END
							ELSE
							BEGIN
						SET @sql += 'AND
										(
												  [BAH].[BatchNo]      LIKE ''%'' +  @SearchString + ''%''
												  OR 
												  [BAH].[Ref]	       LIKE ''%'' +  @SearchString + ''%''
												  OR 
											      [BAH].[Date]         LIKE ''%'' +  @SearchString + ''%''
												  OR 
												  [BAH].[Value]        LIKE ''%'' +  @SearchString + ''%''
												  OR 
												  [BAH].[Code]         LIKE ''%'' +  @SearchString + ''%''
												  OR 
												  [BAH].[Narr]         LIKE ''%'' +  @SearchString + ''%''
												  OR 
												  [BAH].[Supp]		   LIKE ''%'' +  @SearchString + ''%''
												  OR 
												  [BAH].[Matter]       LIKE ''%'' +  @SearchString + ''%''
										  )'
							END


IF @andortype = 'OR'      
  BEGIN 
       
    IF(@operatorType <> '')
		 BEGIN 
			 IF(@operatorType = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) IN ''(''+@andortypevalue+'')'''
				END
			 ELSE IF(@operatorType = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) NOT IN ''(''+@andortypevalue+'')'''
				END
			 ELSE IF(@operatorType = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) = @andortypevalue'
				END
			 ELSE IF(@operatorType = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) <>  @andortypevalue'
				END
			 ELSE IF(@operatorType = 'DCONTAINS')
				BEGIN
				   SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) LIKE ''%'' +@andortypevalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	               SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) LIKE ''%'' +@andortypevalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR RTRIM(ISNULL([BAH].[Type],'''')) LIKE ''%'' +@andortypevalue+''%'''   
	        END 
		END 
IF @andorbatchno = 'OR' 
BEGIN
  IF(@operatorbatchno <> '')				
	   BEGIN 
			 IF(@operatorbatchno = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[BatchNo] IN ''(''+@andorbatchnovalue+'')'''
				END
			 ELSE IF(@operatorbatchno = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[BatchNo] NOT IN ''(''+@andorbatchnovalue+'')'''
				END
			 ELSE IF(@operatorbatchno = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[BatchNo] = andorbatchnovalue'
				END
			 ELSE IF(@operatorbatchno = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[BatchNo] <> @andorbatchnovalue'
				END
			 ELSE IF(@operatorbatchno = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR [BAH].[BatchNo] NOT LIKE ''%'' +@andorbatchnovalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[BatchNo] LIKE ''%'' +@andorbatchnovalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[BatchNo] LIKE ''%'' +@andorbatchnovalue+''%'''   
	        END 
		END 

IF @andorpref = 'OR'
BEGIN 
  IF(@operatorpref <> '')				
	   BEGIN 
			 IF(@operatorpref = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Pref] IN ''(''+@andorprefvalue+'')'''
				END
			 ELSE IF(@operatorpref = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Pref] NOT IN ''(''+@andorprefvalue+'')'''
				END
			 ELSE IF(@operatorpref = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Pref] = @andorprefvalue'
				END
			 ELSE IF(@operatorpref = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Pref] <> @andorprefvalue'
				END
			 ELSE IF(@operatorpref = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Pref] NOT LIKE ''%'' +@andorprefvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Pref] LIKE ''%'' +@andorprefvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Pref] LIKE ''%'' +@andorprefvalue+''%'''   
	        END 
		END 
IF @andorref  = 'OR'      
  BEGIN      
    IF(@operatorRef <> '')
		 BEGIN 
			 IF(@operatorRef = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Ref] IN ''(''+@andorrefvalue+'')'''
				END
			 ELSE IF(@operatorRef = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Ref] NOT IN ''(''+@andorrefvalue+'')'''
				END
			 ELSE IF(@operatorRef = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Ref] = @andorrefvalue'
				END
			 ELSE IF(@operatorRef = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Ref] <> @andorrefvalue'
				END
			 ELSE IF(@operatorRef = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Ref] NOT LIKE ''%'' +@andorrefvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Ref] LIKE ''%'' +@andorrefvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Ref] LIKE ''%'' +@andorrefvalue+''%'''   
	        END 
		END 
IF @andorfeecode   = 'OR'      
  BEGIN      
    IF(@operatorFeeCode <> '')
		 BEGIN 
			 IF(@operatorFeeCode = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Fee] IN ''(''+@andorfeecodevalue+'')'''
				END
			 ELSE IF(@operatorFeeCode = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Fee] NOT IN ''(''+@andorfeecodevalue+'')'''
				END
			 ELSE IF(@operatorFeeCode = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Fee] = @andorfeecodevalue'
				END
			 ELSE IF(@operatorFeeCode = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Fee] <> @andorfeecodevalue'
				END
			 ELSE IF(@operatorFeeCode = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Fee] NOT LIKE ''%'' +@andorfeecodevalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Fee] LIKE ''%'' +@andorfeecodevalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Fee] LIKE ''%'' +@andorfeecodevalue+''%'''   
	        END 
		END 
IF @andordate  = 'OR'      
  BEGIN      
    IF(@operatorDate <> '')
		 BEGIN  

				IF(@andordatevalue = 'StartOfDay')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] IN (CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] NOT IN (CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOfPrevDay')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
  SET @sql = @sql + N' OR [BAH].[Date] IN (SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -1, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
 SET @sql = @sql + N' OR [BAH].[Date] NOT IN (SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -1, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOf7DaysAgo')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -7, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -7, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOf30DaysAgo')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -30, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -30, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOfWeek')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
-- Start of the week
SET @sql = @sql + N' OR [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0)
  AND  [date] < DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) + 1, 0))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN'  OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0)
  AND  [date] < DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) + 1, 0))'
END
END

ELSE IF(@andordatevalue = 'StartOfMonth')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
-- Start of the month
SET @sql = @sql + N' OR [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
  AND  [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
  AND  [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0))'
  END
END

ELSE IF(@andordatevalue = 'StartOfYear')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN'  OR @operatordate = 'CONTAINS')
BEGIN
-- Start of the year
SET @sql = @sql + N' OR [BAH].[Date]  IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
  AND  [date] < DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' OR [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
  AND  [date] < DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))'
END
END

	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Date] IN (CAST(GETDATE() AS DATE))'  
	        END 
	END
IF @andortotal = 'OR'      
  BEGIN      
    IF(@operatorTotal <> '')
		 BEGIN 
			 IF(@operatorTotal = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Value] IN ''(''+@andortotalvalue+'')'''
				END
			 ELSE IF(@operatorTotal = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Value] NOT IN ''(''+@andortotalvalue+'')'''
				END
			 ELSE IF(@operatorTotal = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Value] = @andortotalvalue'
				END
			 ELSE IF(@operatorTotal = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Value] <> @andortotalvalue'
				END
			 ELSE IF(@operatorTotal = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Value] NOT LIKE ''%'' +@andortotalvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Value] LIKE ''%'' +@andortotalvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Value] LIKE ''%'' +@andortotalvalue+''%'''   
	        END 
	END
IF @andormatter = 'OR'      
  BEGIN      
    IF(@operatorMatter <> '')
		 BEGIN 
			 IF(@operatorMatter = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Matter] IN ''(''+@andormattervalue+'')'''
				END
			 ELSE IF(@operatorMatter = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Matter] NOT IN ''(''+@andormattervalue+'')'''
				END
			 ELSE IF(@operatorMatter = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Matter] = @andormattervalue'
				END
			 ELSE IF(@operatorMatter = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Matter] <> @andormattervalue'
				END
			 ELSE IF(@operatorMatter = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Matter] NOT LIKE ''%'' +@andormattervalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Matter] LIKE ''%'' +@andormattervalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Matter] LIKE ''%'' +@andormattervalue+''%'''   
	        END
	END
IF @andorcode  = 'OR'      
  BEGIN      
    IF(@operatorCode <> '')
		 BEGIN 
			 IF(@operatorCode = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Code] IN ''(''+@andorcodevalue+'')'''
				END
			 ELSE IF(@operatorCode = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Code] NOT IN ''(''+@andorcodevalue+'')'''
				END
			 ELSE IF(@operatorCode = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Code] = @andorcodevalue'
				END
			 ELSE IF(@operatorCode = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Code] <> @andorcodevalue'
				END
			 ELSE IF(@operatorCode = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Code] NOT LIKE ''%'' +@andorcodevalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Code] LIKE ''%'' +@andorcodevalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Code] LIKE ''%'' +@andorcodevalue+''%'''   
	        END 
	END
IF @andorsupp  = 'OR'      
  BEGIN      
    IF(@operatorSupp <> '')
		 BEGIN 
			 IF(@operatorSupp = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Supp] IN ''(''+@andorsuppvalue+'')'''
				END
			 ELSE IF(@operatorSupp = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Supp] NOT IN ''(''+@andorsuppvalue+'')'''
				END
			 ELSE IF(@operatorSupp = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Supp] = @andorsuppvalue'
				END
			 ELSE IF(@operatorSupp = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Supp] <> @andorsuppvalue'
				END
			 ELSE IF(@operatorSupp = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Supp] NOT LIKE ''%'' +@andorsuppvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Supp] LIKE ''%'' +@andorsuppvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Supp] LIKE ''%'' +@andorsuppvalue+''%'''   
	        END  
	END
IF @andornarr = 'OR'      
  BEGIN      
    IF(@operatorNarr <> '')
		 BEGIN 
			 IF(@operatorNarr = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Narr] IN ''(''+@andornarrvalue+'')'''
				END
			 ELSE IF(@operatorNarr = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Narr] NOT IN ''(''+@andornarrvalue+'')'''
				END
			 ELSE IF(@operatorNarr = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Narr] = @andornarrvalue'
				END
			 ELSE IF(@operatorNarr = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' OR [BAH].[Narr] <> @andornarrvalue'
				END
			 ELSE IF(@operatorNarr = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' OR  [BAH].[Narr] NOT LIKE ''%'' +@andornarrvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' OR [BAH].[Narr] LIKE ''%'' +@andornarrvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' OR [BAH].[Narr] LIKE ''%'' +@andornarrvalue+''%'''   
	        END 
	END

IF @andortype = 'AND'      
  BEGIN      
    IF(@operatorType <> '')
		 BEGIN 
			 IF(@operatorType = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) IN ''(''+@andortypevalue+'')'''
				END
			 ELSE IF(@operatorType = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) NOT IN ''(''+@andortypevalue+'')'''
				END
			 ELSE IF(@operatorType = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) = @andortypevalue'
				END
			 ELSE IF(@operatorType = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) <>  @andortypevalue'
				END
			 ELSE IF(@operatorType = 'DCONTAINS') 
				BEGIN
				   SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) LIKE ''%'' +@andortypevalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	               SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) LIKE ''%'' +@andortypevalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND RTRIM(ISNULL([BAH].[Type],'''')) LIKE ''%'' +@andortypevalue+''%'''   
	        END 
		END 
IF @andorbatchno = 'AND' 
BEGIN
  IF(@operatorbatchno <> '')				
	   BEGIN 
			 IF(@operatorbatchno = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[BatchNo] IN ''(''+@andorbatchnovalue+'')'''
				END
			 ELSE IF(@operatorbatchno = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[BatchNo] NOT IN ''(''+@andorbatchnovalue+'')'''
				END
			 ELSE IF(@operatorbatchno = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[BatchNo] = @andorbatchnovalue'
				END
			 ELSE IF(@operatorbatchno = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[BatchNo] <> @andorbatchnovalue'
				END
			 ELSE IF(@operatorbatchno = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND [BAH].[BatchNo] NOT LIKE ''%'' +@andorbatchnovalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[BatchNo] LIKE ''%'' +@andorbatchnovalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[BatchNo] LIKE ''%'' +@andorbatchnovalue+''%'''   
	        END 
		END 
IF @andorpref = 'AND'
BEGIN 
  IF(@operatorpref <> '')				
	   BEGIN 
			 IF(@operatorpref = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Pref] IN ''(''+@andorprefvalue+'')'''
				END
			 ELSE IF(@operatorpref = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Pref] NOT IN ''(''+@andorprefvalue+'')'''
				END
			 ELSE IF(@operatorpref = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Pref] = @andorprefvalue'
				END
			 ELSE IF(@operatorpref = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Pref] <> @andorprefvalue'
				END
			 ELSE IF(@operatorpref = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Pref] NOT LIKE ''%'' +@andorprefvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Pref] LIKE ''%'' +@andorprefvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Pref] LIKE ''%'' +@andorprefvalue+''%'''   
	        END 
		END 
IF @andorref  = 'AND'      
  BEGIN      
    IF(@operatorRef <> '')
		 BEGIN 
			 IF(@operatorRef = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Ref] IN ''(''+@andorrefvalue+'')'''
				END
			 ELSE IF(@operatorRef = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Ref] NOT IN ''(''+@andorrefvalue+'')'''
				END
			 ELSE IF(@operatorRef = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Ref] = @andorrefvalue'
				END
			 ELSE IF(@operatorRef = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Ref] <> @andorrefvalue'
				END
			 ELSE IF(@operatorRef = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Ref] NOT LIKE ''%'' +@andorrefvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Ref] LIKE ''%'' +@andorrefvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Ref] LIKE ''%'' +@andorrefvalue+''%'''   
	        END 
		END 
IF @andorfeecode   = 'AND'      
  BEGIN      
    IF(@operatorFeeCode <> '')
		 BEGIN 
			 IF(@operatorFeeCode = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Fee] IN ''(''+@andorfeecodevalue+'')'''
				END
			 ELSE IF(@operatorFeeCode = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Fee] NOT IN ''(''+@andorfeecodevalue+'')'''
				END
			 ELSE IF(@operatorFeeCode = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Fee] = @andorfeecodevalue'
				END
			 ELSE IF(@operatorFeeCode = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Fee] <> @andorfeecodevalue'
				END
			 ELSE IF(@operatorFeeCode = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Fee] NOT LIKE ''%'' +@andorfeecodevalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Fee] LIKE ''%'' +@andorfeecodevalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Fee] LIKE ''%'' +@andorfeecodevalue+''%'''   
	        END 
		END 
IF @andordate  = 'AND'      
  BEGIN      
          
    IF(@operatorDate <> '')
		 BEGIN  

				IF(@andordatevalue = 'StartOfDay')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] IN (CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] NOT IN (CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOfPrevDay')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
  SET @sql = @sql + N' AND [BAH].[Date] IN (SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -1, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
 SET @sql = @sql + N' AND [BAH].[Date] NOT IN (SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -1, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOf7DaysAgo')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -7, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -7, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOf30DaysAgo')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -30, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(day, -30, CAST(GETDATE() AS DATE))
  AND  [date] < CAST(GETDATE() AS DATE))'
END
END

ELSE IF(@andordatevalue = 'StartOfWeek')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
-- Start of the week
SET @sql = @sql + N' AND [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0)
  AND  [date] < DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) + 1, 0))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()), 0)
  AND  [date] < DATEADD(WEEK, DATEDIFF(WEEK, 0, GETDATE()) + 1, 0))'
END
END

ELSE IF(@andordatevalue = 'StartOfMonth')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
-- Start of the month
SET @sql = @sql + N' AND [BAH].[Date] IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
  AND  [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
  AND  [date] < DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) + 1, 0))'
  END
END

ELSE IF(@andordatevalue = 'StartOfYear')
BEGIN
IF(@operatordate = 'EQUALS' OR @operatordate = 'IN' OR @operatordate = 'CONTAINS')
BEGIN
-- Start of the year
SET @sql = @sql + N' AND [BAH].[Date]  IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
  AND  [date] < DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))'
END
ELSE IF(@operatordate = 'NOTEQUALS' OR @operatordate = 'NOTIN' OR @operatordate = 'DCONTAINS')
BEGIN
SET @sql = @sql + N' AND [BAH].[Date] NOT IN (
SELECT [Date]
FROM BatchH
WHERE  [date] >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)
  AND  [date] < DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) + 1, 0))'
END
END

	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Date] IN (CAST(GETDATE() AS DATE))'  
	        END 
	
	END
IF @andortotal = 'AND'      
  BEGIN      
    IF(@operatorTotal <> '')
		 BEGIN 
			 IF(@operatorTotal = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Value] IN ''(''+@andortotalvalue+'')'''
				END
			 ELSE IF(@operatorTotal = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Value] NOT IN ''(''+@andortotalvalue+'')'''
				END
			 ELSE IF(@operatorTotal = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Value] = @andortotalvalue'
				END
			 ELSE IF(@operatorTotal = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Value] <> @andortotalvalue'
				END
			 ELSE IF(@operatorTotal = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Value] NOT LIKE ''%'' +@andortotalvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Value] LIKE ''%'' +@andortotalvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Value] LIKE ''%'' +@andortotalvalue+''%'''   
	        END 
	END
IF @andormatter = 'AND'      
  BEGIN      
    IF(@operatorMatter <> '')
		 BEGIN 
			 IF(@operatorMatter = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Matter] IN ''(''+@andormattervalue+'')'''
				END
			 ELSE IF(@operatorMatter = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Matter] NOT IN ''(''+@andormattervalue+'')'''
				END
			 ELSE IF(@operatorMatter = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Matter] = @andormattervalue'
				END
			 ELSE IF(@operatorMatter = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Matter] <> @andormattervalue'
				END
			 ELSE IF(@operatorMatter = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Matter] NOT LIKE ''%'' +@andormattervalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Matter] LIKE ''%'' +@andormattervalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Matter] LIKE ''%'' +@andormattervalue+''%'''   
	        END
	END
IF @andorcode  = 'AND'      
  BEGIN      
    IF(@operatorCode <> '')
		 BEGIN 
			 IF(@operatorCode = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Code] IN ''(''+@andorcodevalue+'')'''
				END
			 ELSE IF(@operatorCode = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Code] NOT IN ''(''+@andorcodevalue+'')'''
				END
			 ELSE IF(@operatorCode = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Code] = @andorcodevalue'
				END
			 ELSE IF(@operatorCode = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Code] <> @andorcodevalue'
				END
			 ELSE IF(@operatorCode = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Code] NOT LIKE ''%'' +@andorcodevalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Code] LIKE ''%'' +@andorcodevalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Code] LIKE ''%'' +@andorcodevalue+''%'''   
	        END 
	END
IF @andorsupp  = 'AND'      
  BEGIN      
    IF(@operatorSupp <> '')
		 BEGIN 
			 IF(@operatorSupp = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Supp] IN ''(''+@andorsuppvalue+'')'''
				END
			 ELSE IF(@operatorSupp = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Supp] NOT IN ''(''+@andorsuppvalue+'')'''
				END
			 ELSE IF(@operatorSupp = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Supp] = @andorsuppvalue'
				END
			 ELSE IF(@operatorSupp = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Supp] <> @andorsuppvalue'
				END
			 ELSE IF(@operatorSupp = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Supp] NOT LIKE ''%'' +@andorsuppvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Supp] LIKE ''%'' +@andorsuppvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Supp] LIKE ''%'' +@andorsuppvalue+''%'''   
	        END  
	END
IF @andornarr = 'AND'      
  BEGIN      
    IF(@operatorNarr <> '')
		 BEGIN 
			 IF(@operatorNarr = 'IN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Narr] IN ''(''+@andornarrvalue+'')'''
				END
			 ELSE IF(@operatorNarr = 'NOTIN')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Narr] NOT IN ''(''+@andornarrvalue+'')'''
				END
			 ELSE IF(@operatorNarr = 'EQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Narr] = @andornarrvalue'
				END
			 ELSE IF(@operatorNarr = 'NOTEQUALS')
				BEGIN	  
				  SET @sql = @sql + N' AND [BAH].[Narr] <> @andornarrvalue'
				END
			 ELSE IF(@operatorNarr = 'DCONTAINS')
				BEGIN
				  SET @sql = @sql + N' AND  [BAH].[Narr] NOT LIKE ''%'' +@andornarrvalue+''%'''
			    END 
			 ELSE
	            BEGIN	 
	              SET @sql = @sql + N' AND [BAH].[Narr] LIKE ''%'' +@andornarrvalue+''%'''   
	            END 
	     END
	     ELSE
	        BEGIN    
	          SET @sql = @sql + N' AND [BAH].[Narr] LIKE ''%'' +@andornarrvalue+''%'''   
	        END 
	END
 
 
	   SET @sql = @sql + N') AS MyTemplateTable  
	   ORDER BY 
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Narr'' THEN Narr
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Narr'' THEN Narr
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Supp'' THEN Supp
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Supp'' THEN Supp
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Code'' THEN Code
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Code'' THEN Code
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Matter'' THEN Matter
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Matter'' THEN Matter
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Value'' THEN Value
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Value'' THEN Value
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Date'' THEN Date
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Date'' THEN Date
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Fee'' THEN Fee
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Fee'' THEN Fee
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Ref'' THEN Ref
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Ref'' THEN Ref
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Pref'' THEN Pref
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Pref'' THEN Pref
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''BatchNo'' THEN BatchNo
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''BatchNo'' THEN BatchNo
					END 
				END DESC,
				CASE WHEN @SortOrder = ''ASC'' THEN
					CASE @SortColumn
						WHEN ''Type'' THEN Type
					END 
				END,
				CASE WHEN @SortOrder = ''DESC'' THEN
					CASE @SortColumn
						WHEN ''Type'' THEN Type
					END 
				END DESC

		  SELECT *
			FROM #TEMP
		   WHERE
			(
				@StartRow IS NULL
				OR
				(
					[RowNumber] BETWEEN @StartRow AND @EndRow
				)
			)
			
			SELECT
			 COUNT([RowNumber]) AS TotalRecord
			  FROM #TEMP 
			'
	print @sql 

EXEC Sp_executesql @sql,
                      N'@SearchString VARCHAR(500),@Search NVARCHAR(MAX), @offset INT, @PageSize INT, @SortColumn VARCHAR(100), @SortOrder VARCHAR(100),@StartRow INT, @EndRow INT,
					  @andortypevalue VARCHAR(200),
					  @andorbatchnovalue VARCHAR(200),
					  @andorprefvalue VARCHAR(200),
					  @andorrefvalue VARCHAR(200),
					  @andorfeecodevalue VARCHAR(200),
					  @andordatevalue VARCHAR(200),
					  @andortotalvalue VARCHAR(200),
					  @andormattervalue VARCHAR(200),
					  @andorcodevalue VARCHAR(200),
					  @andorsuppvalue VARCHAR(200),
					  @andornarrvalue VARCHAR(200)',					  
                      @SearchString =@SearchString,
					   @Search = @Search,
                      @offset = @offset,
                      @PageSize = @PageSize,
                      @SortColumn = @SortColumn,
                      @SortOrder = @SortOrder,
					  @StartRow = @StartRow,
					  @EndRow  = @EndRow,
					  @andortypevalue = @andortypevalue,
					  @andorbatchnovalue = @andorbatchnovalue,
					  @andorprefvalue = @andorprefvalue,
					  @andorrefvalue = @andorrefvalue,
					  @andorfeecodevalue = @andorfeecodevalue,
					  @andordatevalue = @andordatevalue,
					  @andortotalvalue = @andortotalvalue,
					  @andormattervalue = @andormattervalue,
					  @andorcodevalue = @andorcodevalue,
					  @andorsuppvalue = @andorsuppvalue,
					  @andornarrvalue = @andornarrvalue

SET NOCOUNT OFF

END


GO




IF EXISTS
  (SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_GetReceiptsDetails'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetReceiptsDetails]
  END
GO
CREATE PROCEDURE [dbo].[KAAS_GetReceiptsDetails]  
   ( 
     @BatchNo     INT,
     @handlerCode VARCHAR(10) = NULL
   )

AS

/*******************************************************************************************************
* Fetches the receipts list of specific batch                                                            * 
*                                                                                                        *
* Stored Procedure Name : [dbo].[KAAS_GetReceiptsDetails]  											     *
*                                                                                                        *
* Modification History:                                                                                  *
* 2021-03-24    Revathy D        Created                                                                 *
* 2021-08-18    Balamurugan C    Modified - Added Payee Column                                           *
* 2021-08-23    Balamurugan C    Modified - Added THIRDPARTY,OnceOffPayment,PayClient,ClientCode Column  *
* 2021-08-23    Balamurugan C    Modified - Added Case Associate Column                                  *
* 2021-12-07    vinodhkumar M    Modified - Added Head Pref,Supp Column                                  *
* 2022-03-29    Vignesh M            Modified     POSTED, S13 Columns Added                              *
 *******************************************************************************************************/

BEGIN

 SET NOCOUNT ON 

	 SELECT [BTD].[BatchNo], 
			[BTD].[Type], 
			[BTD].[Code], 
			[BTD].[Pref], 
			[BTD].[Ref], 
			[dbo].KEYHM_FNConvertUTCDateToTargetTimeZone(BTD.[Date], @handlerCode)  AS [Date], 
			[BTD].[Fee], 
			[BTD].[Narr], 
			[BTD].[Matter], 
			[BTD].[Supp], 
			[BTD].[Value], 
			[BTD].[VatCode],
			[BTD].[VatVal],
			[BTD].[Outlay], 
			[BTD].[Year], 
			[BTD].[PerNo], 
			[BTD].[OutlayCode], 
			[BTD].[HeadBatch], 
			[BTD].[AllocBatch], 
			[BTD].[AllocPref], 
			[BTD].[KeyId] ,
			[BTD].[ClientYN],
			[BTD].[AllocRef],
			[BTD].[AllocValue],
			[BTD].[AllocWriteOff],
			[BTD].[Payee],
			[BTD].[Branch],
			[BTD].[ThirdParty],
			[BTD].[PayClient],
			[BTD].[OnceOffPayment],
			[BTD].[ClientCode],
			[BTD].[EFTEmailYorN],
			[BTD].[CaseAssCode],
			[BTD].[HeadPref],
			[BTD].[Supp],
			[BAH].[POSTED],
			[MAT].[S13]
	   FROM [dbo].[BatchDetails] [BTD] 
  LEFT JOIN [dbo].[BatchH] [BAH]  ON [BAH].[BATCHNO] = [BTD].[BATCHNO]
  LEFT JOIN [dbo].[matters] [MAT] ON [MAT].[Code] = [BTD].[MATTER] 
	  WHERE [BTD].[BATCHNO] = @BatchNo
   ORDER BY [BTD].[BATCHNO] ASC, 
		    [BTD].[PREF] ASC, 
		    [BTD].[KEYID] ASC
 
 SET NOCOUNT OFF 


 END
 GO





IF OBJECT_ID(N'KAAS_GetSAMAccruals', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetSAMAccruals]
END
GO
CREATE PROCEDURE 
	   [dbo].[KAAS_GetSAMAccruals]
AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSAMAccruals]                                                                          *
* Description: Used to fetch accruals list                                                             *					  
* Modification History:                                                                                *
* 2021-08-03   Revathy D        Created							                                       *
* 2022-05-16   Vignesh M        Modified Order by changed as per SAM                                   *
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON   
			SELECT [ACC].[NOMINALFROM]  AS [NominalAc], 
				   [ACC].[NOMINALTO]    AS [AccrualAc], 
				   [ACC].[DESCRIPTION]  AS [Description], 
                   [ACC].[VALUE]		AS [Value],
				   [ACC].[VALUEYTD]     AS [ValueYTD],  
                   [ACC].[RECORDID]		AS [RecordId]
              FROM dbo.[Accruals] ACC 
          ORDER BY  
				   [ACC].[NOMINALFROM] ASC, 
                   [ACC].[RECORDID] ASC
 SET NOCOUNT OFF
END 

GO

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

CREATE PROCEDURE 
	   [dbo].[KAAS_GetSAMAssociateTypes]
AS 
/*******************************************************************************************************
* Stored Procedure Name : [dbo].[KAAS_GetSAMAssociateTypes]						                       *
*																                                       *	
* Description: Get list of AssociateTypes							                                   *	
*																                                       *					  
* Modification History:                                                                                *
* 2021-09-02   Vinodhkumar M      Created															   *   
*******************************************************************************************************/
BEGIN 
		 SELECT  RTRIM([CODE])				AS [Code],
				 RTRIM([DESCRIPTION])       AS [Description] 
		  FROM
				[dbo].[AssociateTypes]
		  ORDER BY  
				[CODE] ASC
END 

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMBatchMatterBranch' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMBatchMatterBranch] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_GetSAMBatchMatterBranch] 
		(
			@BatchNo INT = 0
		)

AS

/*******************************************************************************************************
* To get Branch of Matter, Batch Header and Batch Details from view                                    * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMBatchMatterBranch]   			           	    		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-07    Balamurugan.C     Created					                                           *
 *******************************************************************************************************/

BEGIN
	SET NOCOUNT ON
		SELECT [BatchNo]					AS [BatchNo],
			   ISNULL([Matter],'')			AS [Matter],
			   ISNULL([MatterBranch],'')	AS [MatterBranch],
			   ISNULL([BatchDBranch],'')	AS [BatchDBranch],
			   ISNULL([BatchHBranch],'')	AS [BatchHBranch],
			   ISNULL([NominalBranch],'')	AS [NominalBranch]
		  FROM [dbo].[BatchMatterBranch]
		 WHERE [BatchNo]=@BatchNo
	SET NOCOUNT OFF
END

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMBatchMatterValidationDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMBatchMatterValidationDetails] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_GetSAMBatchMatterValidationDetails] 
		(
			@BatchNo INT = 0
		)

AS

/*******************************************************************************************************
* To check outlay budget,approved,closed status in batch header                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMBatchMatterValidationDetails]   			           	   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-07    Balamurugan.C     Created					                                           *
* 2021-09-08    Balamurugan.C     Modified-Added ClientCurBal,ClientDepBal Column					   *
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON

			SELECT [BAD].[BATCHNO]       AS [BatchNo],  
				   [BAD].[MATTER]        AS [Matter],  
				   [MAT].[Closed]        AS [MatterClosed],
				   [MAT].[ClientCode]    AS [ClientCode],
				   [MAT].[OutlayBud]     AS [OutlayBud],
				   [MAT].[OutlayBal]     AS [OutlayBal],
				   [BAD].[Value]         AS [Value],
				   [CON].[Approved]      AS [Approved],
				   [MAT].[ClientCurBal]	 AS [ClientCurBal],
				   [MAT].[ClientDepBal]	 AS [ClientDepBal]
			  FROM [dbo].[BatchDetails]  AS [BAD]  
		INNER JOIN [dbo].[BatchH]		 AS [BAH]  
				ON [BAD].[BATCHNO]	  = [BAH].[BATCHNO]	
		INNER JOIN [dbo].[matters]		 AS [MAT]  
				ON [BAD].[MATTER]	  = [MAT].[Code]
		INNER JOIN [dbo].[Contacts]		 AS [CON]
				ON [MAT].[ClientCode] = [CON].[Code]
			 WHERE [BAD].[BatchNo]    = @BatchNo 

	SET NOCOUNT OFF
END
GO


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

CREATE PROCEDURE
       [dbo].[KAAS_GetSamBillDetailsFeeEarnerList]
      (@BillNo     INT,
       @MatterCode VARCHAR(20))
AS
/********************************************************************************************************
 * Fetches the BillDetails and FeeEarnerList                                                            *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_GetSamBillDetailsFeeEarnerList]                                  *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-09-15    Vinodhkumar.M        Created                                                           *
 * 2024-04-23    Pino Carafa          Created SAM3 and SAM4 versions and ensure that this one calls     *
 *                                    the correct one.                                                  *
 *                                                                                                      *
 *                                                                                                      *
 *                                 ******************************************                           *
 *                                 *                                        *                           *
 * 2024-04-24    Pino Carafa       * THIS PROCEDURE IS OBSOLETE. DO NOT USE *                           *
 *                                 *                                        *                           *
 *                                 ******************************************                           *
 *                                                                                                      *
 ********************************************************************************************************/
BEGIN

IF [dbo].[ISSAM4]() = 0
  BEGIN
    EXEC sp_executesql N'[dbo].[KAAS_GetSamBillDetailsFeeEarnerListSAM3] @BillNo, @MatterCode', N'@BillNo INT, @MatterCode VARCHAR(20)', @BillNo = @BillNo, @MatterCode = @MatterCode
  END
ELSE
  BEGIN
    EXEC sp_executesql N'[dbo].[KAAS_GetSamBillDetailsFeeEarnerListSAM4] @BillNo, @MatterCode', N'@BillNo INT, @MatterCode VARCHAR(20)', @BillNo = @BillNo, @MatterCode = @MatterCode
  END
END

GO

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

/*******************************************************************************************************
* To get Branch List for dropdown                                                                      * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMBranchDropDownList]   			           	    		   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-08-13    Vinodhkumar        Created                                                             *
* 2021-08-17    Balamurugan.C      Modified-Include Right Trim                                         *
 *******************************************************************************************************/

BEGIN
	SELECT RTRIM([BRANCHCODE])	 AS [Code],
		   RTRIM([DESCRIPTION])  AS [Description]
	FROM   [dbo].[Branch]
END
GO



IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMCaseContactBankDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMCaseContactBankDetails] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_GetSAMCaseContactBankDetails]
	(
		@CaseCode VARCHAR(20) = ''
	)
AS
/*******************************************************************************************************
* This sp is used to get Case Associates Dropdown Details											   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetCaseContactBankDetails]									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-24    Balamurugan       Created                                                              *
* 2021-09-09    Balamurugan       Modified - Added EFT Email Address Column                            *
 *******************************************************************************************************/ 
BEGIN
	SET NOCOUNT ON

		  SELECT ROW_NUMBER() OVER (ORDER BY [CSC].[CaseCode] DESC) AS RowID,
				 [CSC].[CaseCode]									AS [CaseCode],
				 [CSC].[ConType]									AS [ConType],
				 [CSC].[ConNum]										AS [ConNum],
		         [CSC].[NameCode]									AS [NameCode],
			     [CSC].[SolCode]									AS [SolCode],
				 [CSC].[InsCode]									AS [InsCode],
				 [CSC].[AssignedContact]							AS [AssignedContact], 
				 [CAN].[Code]										AS [Code],
				 [CAN].[Type]										AS [Type],
				 [CAN].[Name]+'('+ [CAN].[Company]+')'				AS [NameAndCompany],
				 [CAN].[Name]										AS [Name],
				 [CAN].[Company]									AS [Company],
				 [CAN].[Address]									AS [Address],
				 [CAN].[Search]										AS [Search],
				 [CAN].[ContactNo]									AS [ContactNo],
				 [CAN].[BankName]									AS [BankName],
				 [CAN].[BankSortCode]								AS [BankSortCode],
				 [CAN].[BankAccNo]									AS [BankAccNo],
				 [CAN].[Iban]										AS [Iban], 
				 [CAN].[Bic]										AS [Bic], 
				 [AST].[Code]										AS [AssociateCode],
				 [AST].[Description]								AS [Description],
				 [CAN].[EFTEmailAddress]							AS [EFTEmailAddress]
			FROM [dbo].[CaseContacts] [CSC] 
 LEFT OUTER JOIN [dbo].[CaseAssociatesNames] [CAN] 
              ON [CSC].[NameCode]  = [CAN].[Code] 
 LEFT OUTER JOIN [dbo].[AssociateTypes] [AST] 
              ON [CSC].[ConType]   = [AST].CODE 
	       WHERE [CSC].[CaseCode]  = @CaseCode
	    ORDER BY [CSC].[CaseCode] ASC,
		         [CSC].[ConType] ASC,
				 [CSC].[ConNum] ASC

	SET NOCOUNT OFF
END


GO

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

CREATE PROCEDURE 
	   [dbo].[KAAS_GetSAMCaseContactDetails] 
	   (
			@MatterCode VARCHAR(20)
	   ) 
AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSAMCaseContactDetails] '000001/0000'                                                              *
* Description: Used to Case contact details for matter code                                            *					  
* Modification History:                                                                                *
* 2021-04-09   Natarajan S        Created															   *      
* 2021-04-09   Arun V             Implemented coding standards                                         *      
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON   
			SELECT  
				ROW_NUMBER() OVER(ORDER BY [CC].assignedcontact) AS ConNum,
				[CC].[CASECODE] [CaseCode], 
				[CC].[CONTYPE]  [ConType],
				[CC].[NAMECODE] [CaseContactsNameCode], 
				[CC].[SOLCODE] [CaseContactsSolCode], 
				[CC].[INSCODE] [CaseContactsInsCode], 
				[CC].[ASSIGNEDCONTACT] [AssignedContact], 
				[CA].[CODE] [CaseAssociateCode], 
				[CA].[TYPE] [CaseAssociateType], 
				[CA].[NAME]  + '(' + [CA].[COMPANY] + ')' AS [CaseAssociateName], 
				[CA].[COMPANY] [CaseAssociateCompany], 
				[CA].[ADDRESS] [CaseAssociateAddress], 
				[CA].[NAME] [CaseAssociateSearch], 
				[CA].[CONTACTNO] [CaseAssociateContactNo],
				[CA].[BANKNAME] [CaseAssociateBankName], 
				[CA].[BANKSORTCODE] [CaseAssociateBankSortCode], 
				[CA].[BANKACCNO] [CaseAssociateBankAccNo], 
				[CA].[IBAN] [CaseAssociateIBAN], 
				[CA].[BIC] [CaseAssociateBIC], 
				[AT].[CODE] [AssociateTypeCode], 
				[AT].[DESCRIPTION] [AssociateTypeDescription]
			FROM
				[dbo].[CaseContacts] CC
				LEFT OUTER JOIN [dbo].[CaseAssociatesNames] CA 
							 ON [CC].[NAMECODE]= [CA].[CODE] 
				LEFT OUTER JOIN [dbo].[AssociateTypes] AT 
							 ON  [CC].[CONTYPE]= AT.CODE  
			WHERE 
				[CC].[CASECODE] =@MatterCode
			ORDER BY
			    [CC].[CASECODE] ASC,
				[CC].[CONTYPE] ASC, 
				[CC].[CONNUM] ASC
			
SET NOCOUNT OFF
END 

GO



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

CREATE PROCEDURE 
	   [dbo].[KAAS_GetSAMChangeAssociateDetails] 
	   (@Code VARCHAR(20) = NULL) 
AS 
/*******************************************************************************************************
* Stored Procedure Name : [dbo].[KAAS_GetSAMChangeAssociateDetails]				                       *
*																                                       *	
* Description: Get details of Change associates party based on Code                                    *	
*																                                       *					  
* Modification History:                                                                                *
* 2021-09-02   Vinodhkumar M      Created															   *   
*******************************************************************************************************/
BEGIN 
		SELECT
			 [Type],
			 [Code],
			 [Name],
			 [Email],
			 [BankType],
			 [BankName],
			 [BankAddress],
			 [BankSortCode],
			 [BankAccNo],
			 [IBAN],
			 [BIC],
			 [EFTEmailAddress]
		FROM 
			[dbo].[CaseAssociatesNames]
		WHERE 
		   [CODE]=@Code
END 

GO

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

go 

CREATE PROCEDURE [dbo].KAAS_GetSAMClientAccountExpansion (@MatterCode VARCHAR(20)) 
AS 
  /******************************************************************************************************************
  *																										            *
  *Used to list the matter ledger																 				    *
  * Stored Procedure Name: [dbo].KAAS_GetSAMClientAccountExpansion	             				                	* 
  * Modification History:                                                                                           *
  * 2021-03-30			Natarajan S          Created			  										            *   
  * 2021-12-02			Vinodhkumar M        Modified - In where clause valuec should not be 0 condition addded and *
													    footer balance query is added							    *      
   ******************************************************************************************************************/
  BEGIN 

	EXEC [dbo].KAAS_GetSAMHeaderDetails	@MatterCode

	SELECT 
			[Date],
			[REF] AS Ref,
			[NARR] AS Narr,  
			[ValueC], 
			[ValueCC],
			[ValueCD],
			[DepositType],
			[PRef]
	FROM  dbo.MatterLedger 
	WHERE MATTER= @MatterCode AND 
	valuec <> 0

		  SELECT [MAT].[DebtBal]		   AS [DebtorBalance],
				 [MAT].[OutlayBal]		   AS [OutlayBalance],
				 [MAT].[ClientCurBal]	   AS [ClientCurrentBalance],
				 [MAT].[ClientDepBal]	   AS [ClientDeptBalance],
				 [MAT].[ClientBal]	       AS [ClientBalance]
		   FROM  [dbo].[Matters] [MAT]
		   WHERE [MAT].[Code] =  @MatterCode 
  END 

go 



IF OBJECT_ID(N'KAAS_GetSAMCommonSystemOptions',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetSAMCommonSystemOptions]
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_GetSAMCommonSystemOptions]
AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMCommonSystemOptions]  									   *
* Description: To Get common System Options		    												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-28    Vinodhkumar M        Created                                                           *
 *******************************************************************************************************/
BEGIN
		SELECT 
			   [CON].[Indicator22]		as [Branch],
			   [CON].[ForceFE]			as [ForceFE],
			   [CON].[PendingOutlay]    as [PendingOutlay]
		FROM   
			  [Control] [CON]
END
GO
IF OBJECT_ID(N'KAAS_GetSamCreateFillYear',N'P')IS NOT NULL
DROP PROCEDURE [dbo].[KAAS_GetSamCreateFillYear]
GO

CREATE PROCEDURE [dbo].[KAAS_GetSamCreateFillYear]
		(
			 @Code	    VARCHAR(10)  = NULL,
			 @Branch    VARCHAR(10)  = NULL,
			 @Year		INT          = 0,
			 @Budget    DECIMAL(9,2) = 0.00
		 )
AS

/*******************************************************************************************************
* Create Fill Year				                                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamCreateFillYear]        									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-06    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/

BEGIN
  BEGIN TRY
	BEGIN TRAN
			DECLARE @Count INT = 0;
			    SET @Count     = 1;

			WHILE(@Count <= 12)
			BEGIN

			  --INSERT INTO TABLE
					INSERT 
					  INTO [dbo].[NominalBudgets]
						(
						   [Code],
						   [Branch],
						   [Year],
						   [Period],
						   [Budget]
						)
					VALUES
					    (  @Code,
						   @Branch,
						   @Year,
						   @Count,
						   @Budget
						)
					  SET  @Count = @Count + 1
			END
    COMMIT TRAN

   END TRY
   BEGIN CATCH 
			DECLARE @ErrorMsg      NVARCHAR(4000), 
				    @ErrorSeverity INT,
				    @ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

	      RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
   END CATCH

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

CREATE PROCEDURE [dbo].[KAAS_GetSamCreateMemoriseTransaction]
		(
			 @BatchNumber	INT         = 0,
			 @Date		    DATE        = NULL,
			 @Handler       VARCHAR(30) = ''
		)
AS

/*******************************************************************************************************
* Create Memorise Batch and Details                                                                    * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamCreateMemoriseTransaction]        					       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-29    Vinodhkumar M        Created                                                           *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
* 2022-05-06    Vignesh M            Modified - GetDate replaced by Date                               *
* 2022-05-09    Vignesh M            Modified - UTC Conversion Removed                                 *
*******************************************************************************************************/

BEGIN
 BEGIN TRY
	BEGIN TRAN
		 DECLARE @LastBatch INT = 0,
		         @LastPref  INT = 0

		 (SELECT @LastBatch=(LASTBATCH+1),
				 @LastPref=(LASTPREF+1)
		    FROM [dbo].[control]) 

		--INSERT INTO HEADER TABLE
		  INSERT 
		    INTO [dbo].[BatchH]
		      (  [BATCHNO],
				 [POSTFWD],
				 [TYPE],
				 [CODE],
				 [BRANCH],
				 [PREF],
				 [REF],
				 [DATE],
				 [FEE],
				 [MATTER],
				 [SUPP],
				 [NARR],
				 [VALUE],
				 [SUBTOT],
				 [POSTED],
				 [CLIENTAC],
				 [PERNO],
				 [YEAR],
				 [PAYEE],
				 [OUTLAYTOT],
				 [VATTOT],
				 [FEETOT],
				 [INVCR],
				 [THIRDPARTY],
				 [USERCODE],
				 [ENTRYDATE],
				 [CLIENTBANK],
				 [CURRENCY],
				 [CURRENCYVALUE],
				 [CUROUTLAYTOT],
				 [CURVATTOT],
				 [CURFEETOT],
				 [RECNO],
				 [SINGLELINE],
				 [TEMPLATE],
				 [CHEQUEREQNO],
				 [WRITEDOWN],
				 [WRITEBACKHOURS],
				 [WRITEBACKVALUE],
				 [CORRECTCOPY],
				 [CREDITINVOICENO],
				 [DRAFTBILLNO],
				 [EFTSENT],
				 [EFTDATE],
				 [EFTFileNumber],
				 [EFTFileName],
				 [EFTYorN],
				 [ClientCode],
				 [PayClient],
				 [OnceOffPayment],
				 [CaseAssCode],
				 [EFTEmailYorN],
				 [HandlerCode],
				 [PaymentMethod],
				 [ClearedDate]
			  )

		  SELECT @LastBatch,
				 POSTFWD,
				 TYPE,
				 CODE,
				 BRANCH,
				 @LastPref,
				 '',
				 DATEADD(DAY, DATEDIFF(DAY, 0, [DATE]), 0),
				 FEE,
				 MATTER,
				 SUPP,
				 NARR,
				 VALUE,
				 SUBTOT,
				 POSTED,
				 CLIENTAC,
				 PERNO,
				 YEAR,
				 PAYEE,
				 OUTLAYTOT,
				 VATTOT,
				 FEETOT,
				 INVCR,
				 THIRDPARTY,
				 USERCODE,
				 ENTRYDATE,
				 CLIENTBANK,
				 CURRENCY,
				 CURRENCYVALUE,
				 CUROUTLAYTOT,
				 CURVATTOT,
				 CURFEETOT,
				 RECNO,
				 SINGLELINE,
				 '~~~MEMO~~~',
				 CHEQUEREQNO,
				 WRITEDOWN,
				 WRITEBACKHOURS,
				 WRITEBACKVALUE,
				 CORRECTCOPY,
				 CreditInvoiceNo,
				 DraftBillNo,
				 EFTSent,
				 EFTDate,
				 EFTFileNumber,
				 EFTFileName,
				 EFTYorN,
				 ClientCode,
				 PayClient,
				 OnceOffPayment,
				 CaseAssCode,
				 EFTEmailYorN,
				 HandlerCode,
				 PaymentMethod,
				 ClearedDate
	 	    FROM [dbo].[BatchH] WITH (NOLOCK)
		   WHERE [BatchNo] = @BatchNumber 

		  UPDATE [dbo].[control] 
		     SET LASTPREF=(@LastPref) 
		   WHERE NEXT_DOC_NO = 0
					   
		--INSERT INTO TEMP TABLE
		  SELECT @LastBatch AS [batch],
				 [TYPE],
				 [CODE],
				 @LastPref  AS [pref],
				 DATEADD(DAY, DATEDIFF(DAY, 0, [DATE]), 0) AS [batchDate],
				 [FEE],
				 [BRANCH],
				 [NARR],
				 [MATTER],
				 [SUPP],
				 [VALUE],
				 [VATCODE],
				 [VATVAL],
				 [CLIENTYN],
				 [OUTLAY],
				 [PENDING],
				 [YEAR],
				 [PERNO],
				 [ENTRYCURRENCY],
				 [CURRENCYVALUE],
				 [CURRENCYVAT],
				 [OUTLAYCODE],
				 [THIRDPARTY],
				 [PAYEE],
				 [HEADPREF],
				 [HEADBATCH],
				 [ALLOCBATCH],
				 [ALLOCPREF],
				 [ALLOCREF],
				 [ALLOCVALUE],
				 [ALLOCWRITEOFF],
				 [PSUPP],
				 [UNDETAKING],
				 [CaseAssCode],
				 [OnceOffPayment],
				 [PayClient],
				 [ClientCode],
				 [EFTEmailYorN],
				 [RegisteredPost],
				 [PreBilledOutlay],
				 ROW_NUMBER() OVER(ORDER BY @LastBatch) AS rowId 
		    INTO #tempTable
		    FROM [dbo].[BatchDetails] WITH (NOLOCK)
		   WHERE [BatchNo] = @BatchNumber 
		     AND NOT EXISTS (SELECT  1
                               FROM [dbo].[BatchDetails] [BAD]
                              WHERE [BAD].PREF = @LastPref)
		
	      DECLARE @Count           INT  = 0,
				  @TotalCount      INT = 0, 
				  @LastPrefDetails INT = 0;
              SET @TotalCount = (SELECT COUNT(*) FROM #tempTable);
		      SET @Count = 1;

	        WHILE(@Count <= @TotalCount)
	        BEGIN
	          SELECT @LastPrefDetails = (LASTPREF+1) FROM [dbo].[control]

				  --INSERT INTO DETAILS TABLE
				  INSERT 
				    INTO [dbo].[BatchDetails]
					  (  [BATCHNO],
						 [TYPE], 
						 [CODE], 
						 [PREF], 
						 [DATE],
						 [FEE],
						 [BRANCH],
						 [NARR], 
						 [MATTER], 
						 [SUPP], 
						 [VALUE], 
						 [VATCODE], 
						 [VATVAL], 
						 [CLIENTYN], 
						 [OUTLAY], 
						 [PENDING], 
						 [YEAR], 
						 [PERNO], 
						 [ENTRYCURRENCY], 
						 [CURRENCYVALUE], 
						 [CURRENCYVAT], 
						 [OUTLAYCODE], 
						 [THIRDPARTY], 
						 [PAYEE], 
						 [HEADPREF], 
						 [HEADBATCH], 
						 [ALLOCBATCH], 
						 [ALLOCPREF], 
						 [ALLOCREF], 
						 [ALLOCVALUE], 
						 [ALLOCWRITEOFF], 
						 [PSUPP], 
						 [UNDETAKING], 
						 [CaseAssCode], 
						 [OnceOffPayment], 
						 [PayClient], 
						 [ClientCode], 
						 [EFTEmailYorN], 
						 [RegisteredPost], 
						 [PreBilledOutlay]
					 )
 
			      SELECT @LastBatch,
						 [TYPE],
						 [CODE],
						 @LastPrefDetails,
						 [batchDate],
						 [FEE],
						 [BRANCH],
						 [NARR],
						 [MATTER],
						 [SUPP],
						 [VALUE],
						 [VATCODE],
						 [VATVAL],
						 [CLIENTYN],
						 [OUTLAY],
						 [PENDING],
						 [YEAR],
						 [PERNO],
						 [ENTRYCURRENCY],
						 [CURRENCYVALUE],
						 [CURRENCYVAT],
						 [OUTLAYCODE],
						 [THIRDPARTY],
						 [PAYEE],
						 [HEADPREF],
						 [HEADBATCH],
						 [ALLOCBATCH],
						 [ALLOCPREF],
						 [ALLOCREF],
						 [ALLOCVALUE],
						 [ALLOCWRITEOFF],
						 [PSUPP],
						 [UNDETAKING],
						 [CaseAssCode],
						 [OnceOffPayment],
						 [PayClient],
						 [ClientCode],
						 [EFTEmailYorN],
						 [RegisteredPost],
						 [PreBilledOutlay]
                    FROM #tempTable WITH (NOLOCK)
				   WHERE rowId = @count

                  UPDATE [dbo].[control] 
					 SET LASTPREF=(@LastPrefDetails) 
				   WHERE NEXT_DOC_NO=0 

					 SET @Count = @Count + 1
	END

				 UPDATE	dbo.control 
					SET	LASTBATCH=(@LastBatch) 
	   			  WHERE	NEXT_DOC_NO=0

			 DROP TABLE	#tempTable

			DELETE FROM	[dbo].[RBatchH]
				  WHERE	[BATCHNO] = @BatchNumber 
					AND	[DATE]    = CAST(@Date AS DATE)

			DELETE FROM	[dbo].[RBatchD]
				  WHERE	[BATCHNO] = @BatchNumber
					AND	[DATE]    = CAST(@Date AS DATE)

		COMMIT TRAN

	END TRY
	BEGIN CATCH 
		   DECLARE @ErrorMsg      NVARCHAR(4000), 
				   @ErrorSeverity INT,
				   @ErrorState    INT; 

			SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				   @ErrorSeverity = ERROR_SEVERITY(), 
				   @ErrorState    = ERROR_STATE()

		RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
				 IF @@TRANCOUNT > 0  
					BEGIN
						ROLLBACK TRANSACTION;
					END 
	END CATCH

END
GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSamCreateOutlayWriteOffJournal' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSamCreateOutlayWriteOffJournal] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_GetSamCreateOutlayWriteOffJournal]
		(
			@Branch			VARCHAR(1)  = '',
			@JournalAmount	DECIMAL     = 0 ,
			@AllocBatch  	INT         = 0,
			@AllocPref      INT         = 0,
			@AllocRef		VARCHAR(20) = '',
			@Matter			VARCHAR(20) = '',
			@Handler        VARCHAR(20) = '' 
		)
AS
/*******************************************************************************************************
* Create Jourunal Batch and Details                                                                    * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamCreateOutlayWriteOffJournal]        					   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-30    Balamurugan C        Created                                                           *
* 2021-10-06    Balamurugan C        Modified - Changes in case statement                              *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *   
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRAN
			DECLARE @LastBatch        INT         = 0,
					@LastPref         INT         = 0,
					@Year	          INT         = 0,
					@CurPer           INT         = 0,
					@DefaultDebtors   VARCHAR(15) = '',
					@DefaultOutlay	  VARCHAR(15) = '',
					@CurrentDate      DATE        = NULL;

			 (
			  SELECT @LastBatch       = (LastBatch + 1),
					 @LastPref        = (LastPref + 1),
					 @Year            = [Year],
					 @CurPer          = CurPer,
					 @DefaultDebtors  = Debtors,
					 @DefaultOutlay   = Outlay
			  FROM	 [dbo].[Control]
			 ) 

			     SET @CurrentDate = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](GETDATE(), @Handler)), 0)

		     INSERT 
		       INTO [dbo].[BatchH]
				(
					[Batchno],
					[Postfwd],
					[Type],
					[Code],
					[Branch],
					[Pref],
					[Ref],
					[Date],
					[Fee],
					[Matter],
					[Supp],
					[Narr],
					[Value],
					[Subtot],
					[Posted],
					[ClientAc],
					[PerNo],
					[Year],
					[Payee],
					[OutlayTot],
					[VatTot],
					[FeeTot],
					[Invcr],
					[ThirdParty],
					[UserCode],
					[EntryDate],
					[ClientBank],
					[Currency],
					[CurrencyValue],
					[CuroutlayTot],
					[CurVatTot],
					[CurFeeTot],
					[RecNo],
					[Singleline],
					[Template],
					[ChequeReqNo],
					[WriteDown],
					[WriteBackHours],
					[WriteBackValue],
					[CorrectCopy],
					[CreditInvoiceNo],
					[DraftBillNo],
					[EFTSent],
					[EFTDate],
					[EFTFileNumber],
					[EFTFileName],
					[EFTYorN],
					[ClientCode],
					[PayClient],
					[OnceOffPayment],
					[CaseAssCode],
					[EFTEmailYorN],
					[HandlerCode],
					[PaymentMethod],
					[ClearedDate]
				)
			 VALUES 
			    (	
					@LastBatch,												/*[Batchno]*/
					'',														/*[Postfwd]*/
					'J',													/*[Type]*/
					'',														/*[Code]*/
					@Branch,												/*[Branch]*/
					@LastPref,												/*[Pref]*/
					'Set-off',												/*[Ref]*/
					@CurrentDate,											/*[Date]*/
					'',														/*[Fee]*/
					'',														/*[Matter]*/
					'',														/*[Supp]*/
					'Journal to Set off billing against Outlay',			/*[Narr]*/
					 0.00,													/*[Value]*/
					 0.00,													/*[Subtot]*/
					 'N',													/*[Posted]*/
					 '',													/*[ClientAc]*/
					 @CurPer,												/*[PerNo]*/
					 @Year,													/*[Year]*/
					 '',													/*[Payee]*/
					 0.00,													/*[OutlayTot]*/
					 0.00,													/*[VatTot]*/
					 0.00,													/*[FeeTot]*/
					 '',													/*[Invcr]*/
					 '',													/*[ThirdParty]*/
					 'keyhouse',											/*[UserCode]*/
					 @CurrentDate,											/*[EntryDate]*/
					 '',													/*[ClientBank]*/
					 'E',													/*[Currency]*/
					 0.00,													/*[CurrencyValue]*/
					 0.00,													/*[CuroutlayTot]*/
					 0.00,													/*[CurVatTot]*/
					 0.00,													/*[CurFeeTot]*/
					 0,														/*[RecNo]*/
					 '',													/*[Singleline]*/
					 '',													/*[Template]*/
					 0,														/*[ChequeReqNo]*/
					 NULL,													/*[WriteDown]*/
					 0.00,													/*[WriteBackHours]*/
					 0.00,													/*[WriteBackValue]*/
					 '',													/*[CorrectCopy]*/
					 0,														/*[CreditInvoiceNo]*/
					 0,														/*[DraftBillNo]*/
					 'N',													/*[EFTSent]*/
					 NULL,													/*[EFTDate]*/
					 0,														/*[EFTFileNumber]*/
					 '',													/*[EFTFileName]*/
					 'N',													/*[EFTYorN]*/
					 '',													/*[ClientCode]*/
					 'N',													/*[PayClient]*/
					 'N',													/*[OnceOffPayment]*/
					 '',													/*[CaseAssCode]*/
					 'N',													/*[EFTEmailYorN]*/
					 '',													/*[HandlerCode]*/
					 0,														/*[PaymentMethod]*/
					 NULL 													/*[ClearedDate]*/
				) 

			 UPDATE [dbo].[Control] 
				SET [LASTPREF] = (@LastPref) 
			  WHERE [NEXT_DOC_NO] = 0

	/* INSERT INTO TEMP TABLE */
	IF OBJECT_ID('tempdb..#tempTable') IS NOT NULL 
	   DROP TABLE #tempTable

		  SELECT @LastBatch					                  AS BatchNo,
				 'J'					                      AS [Type],
				 ''				                              AS Code,
				 @LastPref					                  AS Pref,
				 'Set-off'				                      AS Ref,
				 @CurrentDate							      AS [Date],
				 ''							                  AS Fee,
				 'H'						                  AS Branch,
				 'Journal to Set off billing against Outlay'  AS Narr,
				 @Matter								      AS Matter,
				 ''					                          AS Supp,
				 @JournalAmount			                      AS [Value],
				 ''					                          AS VatCode,
				 0.00		                                  AS VatVal,
				 ''			                                  AS ClientYN,
				 ''		                                      AS Outlay,
				 ''			                                  AS Pending,
				 @Year		                                  AS [Year],
				 @CurPer			                          AS PerNo,
				 'E'		                                  AS EntryCurrency,
				 @JournalAmount	                              AS CurrencyValue,
				 0.00		                                  AS CurrencyVat,
				 ''			                                  AS OutlayCode,
				 ''			                                  AS ThirdParty,
				 ''			                                  AS Payee,
				 0			                                  AS HeadPref,
				 0			                                  AS HeadBatch,
				 @AllocBatch		                          AS AllocBatch,
				 @AllocPref		                              AS AllocPref,
				 @AllocRef		                              AS AllocRef,
				 @JournalAmount	                              AS AllocValue,
				 'N'		                                  AS Allocwriteoff,
				 ''			                                  AS Psupp,
				 0			                                  AS Undetaking,
				 ''			                                  AS CaseAssCode,
				 'N'		                                  AS OnceOffPayment,
				 'N'		                                  AS PayClient,
				 ''			                                  AS ClientCode,
				 'N'		                                  AS EFTEmailYorN,
				 0			                                  AS RegisteredPost,
				 0			                                  AS PreBilledOutlay
			INTO #tempTable


		 DECLARE @InsertNum		    INT,
				 @LastPrefIncrement INT = 0

	   SET @InsertNum = 2

	WHILE (@InsertNum <> 0 )
			BEGIN 
				SET @InsertNum         = @InsertNum - 1
			 SELECT	@LastPrefIncrement = (LASTPREF+1) FROM [dbo].[Control]

					INSERT 
					 INTO [dbo].[Batchdetails]
					  (         
						  [BatchNo],
						  [Type],
						  [Code],
						  [Pref],
						  [Ref],
						  [Date],
						  [Fee],
						  [Branch],
						  [Narr],
						  [Matter],
						  [Supp],
						  [Value],
						  [Vatcode],
						  [Vatval],
						  [Clientyn],
						  [Outlay],
						  [Pending],
						  [Year],
						  [Perno],
						  [Entrycurrency],
						  [Currencyvalue],
						  [Currencyvat],
						  [Outlaycode],
						  [Thirdparty],
						  [Payee],
						  [Headpref],
						  [Headbatch],
						  [Allocbatch],
						  [Allocpref],
						  [Allocref],
						  [Allocvalue],
						  [Allocwriteoff],
						  [Psupp],
						  [Undetaking],
						  [Caseasscode],
						  [Onceoffpayment],
						  [Payclient],
						  [ClientCode],
						  [EFTEmailYorN],
						  [RegisteredPost],
						  [PreBilledOutlay]
					  )
					  (	 
				   SELECT [BatchNo],
						  [Type],
						  CASE WHEN @InsertNum = 0 THEN @DefaultDebtors ELSE @DefaultOutlay END AS Code,
						  @LastPrefIncrement,
						  [Ref],
						  [Date],
						  [Fee],
						  [Branch],
						  [Narr],
						  [Matter],
						  [Supp],
						  CASE WHEN @InsertNum = 0 THEN  CASE WHEN [Value] < 0 THEN [Value] ELSE [Value]*-1 END ELSE ABS([Value]) END AS  [Value],
						  [VatCode],
						  [VatVal],
						  [ClientYN],
						  CASE WHEN @InsertNum = 0 THEN 'D' ELSE 'O' END AS [Outlay],
						  [Pending],
						  [Year],
						  [PerNo],
						  [EntryCurrency],
						  CASE WHEN @InsertNum = 0 THEN CASE WHEN [CurrencyValue] < 0 THEN [CurrencyValue] ELSE [CurrencyValue]*-1 END ELSE ABS([CurrencyValue]) END AS  [CurrencyValue],
						  [CurrencyVat],
						  [OutlayCode],
						  [ThirdParty],
						  [Payee],
						  [HeadPref],
						  [HeadBatch],
						  CASE WHEN @InsertNum = 0 THEN [AllocBatch] ELSE 0 END AS [AllocBatch],
						  CASE WHEN @InsertNum = 0 THEN [AllocPref] ELSE 0 END AS [AllocPref],
						  CASE WHEN @InsertNum = 0 THEN [AllocRef] ELSE '' END AS [AllocRef],
						  CASE WHEN @InsertNum = 0 THEN CASE WHEN [AllocValue] < 0 THEN [AllocValue] ELSE [AllocValue]*-1 END ELSE 0 END AS  [AllocValue],
						  [Allocwriteoff],
						  [Psupp],
						  [Undetaking],
						  [CaseAssCode],
						  [OnceOffPayment],
						  [PayClient],
						  [ClientCode],
						  [EFTEmailYorN],
						  [RegisteredPost],
						  [PreBilledOutlay]
					 FROM #tempTable  
					   )
				   UPDATE [dbo].[Control] 
					  SET [LASTPREF] = (@LastPrefIncrement) 
					WHERE [NEXT_DOC_NO] = 0  

		END 
				   UPDATE [dbo].[Control] 
					  SET [LASTBATCH] = (@LastBatch) 
	   			    WHERE [NEXT_DOC_NO] = 0


					SELECT @LastBatch 'LastBatch'

		COMMIT TRAN

	END TRY

	BEGIN CATCH
	   DECLARE @ErrorMsg      NVARCHAR(4000), 
   	   		   @ErrorSeverity INT,
   	   		   @ErrorState    INT; 
   	   
   	    SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
   	   		   @ErrorSeverity = ERROR_SEVERITY(), 
   	   		   @ErrorState    = ERROR_STATE()

   	 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
   	   	 IF @@TRANCOUNT > 0  
   	   		BEGIN
   	   			ROLLBACK TRANSACTION;
   	   		END 
	END CATCH

END
GO


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

GO

CREATE PROCEDURE 
        [dbo].[KAAS_GetSAMCurrentCaseDetails]
	    (@MatterCode         VARCHAR(30))
AS

/*******************************************************************************************************
* This stored procedure is used to Get SAM Current Case Details data associated with all the tabs in it*
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_GetSAMCurrentCaseDetails]							               *
*                                                                                                      *
* Modification History	:                                                                              *
* 2022-01-21    Vinodhkumar.M     Duplication from SP-> KAAS_GetSAMCurrentCaseDetails                  *
* 2022-01-21    Vinodhkumar.M     Added -> Check if matter is eligible to Closed	                   *
*******************************************************************************************************/
BEGIN
SET NOCOUNT ON
DECLARE @IsPaperlessColumn AS BIT
IF EXISTS(
	SELECT TOP 1 1
	  FROM SYS.COLUMNS
	 WHERE OBJECT_NAME(OBJECT_ID) = 'Matters' 
	 and [NAME] = 'Paperless')
BEGIN
	 EXEC ('SELECT 
         RTRIM(ISNULL(MAT.[ClientCode], ''''))                          AS [ClientCode],
         RTRIM(ISNULL(MAT.[Matter], ''''))                              AS [Matter],
         RTRIM(ISNULL(MAT.[Description], ''''))                         AS [Description] ,
         RTRIM(ISNULL(MAT.[FECode], ''''))                              AS [FeeEarner],
         RTRIM(ISNULL(MAT.[Partner], ''''))                             AS [Partner],
         RTRIM(ISNULL(MAT.[Secretary], ''''))                           AS [Secretary],
         RTRIM(ISNULL(MAT.[Dept], ''''))                                AS [Dept] ,
         RTRIM(ISNULL(MAT.[WType], ''''))                               AS [WType] ,
         RTRIM(ISNULL(MAT.[OldRef], ''''))                              AS [OldRef] ,
         RTRIM(ISNULL(MAT.[User1], ''''))                               AS [User1],
         RTRIM(ISNULL(MAT.[User2], ''''))                               AS [User2],
         RTRIM(ISNULL(MAT.[User3], ''''))                               AS [User3],
         RTRIM(ISNULL(MAT.[YourRef], ''''))                             AS [YourRef],
         CASE WHEN RTRIM(ISNULL(MAT.[Statements], '''')) = ''Y''
              THEN ''True''
              ELSE ''False'' END											AS [Statements],
         ISNULL(MAT.[Importance], 0)									AS [Importance],
         RTRIM(ISNULL(MAT.[Status], ''''))								AS [Status],
         RTRIM(ISNULL(MAT.[FileColour], ''''))							AS [FileColour],
         ISNULL(MAT.[Value], 0)											AS [ValueToClient],
         ISNULL(CONVERT(NVARCHAR(30),MAT.[Started],23),'''')				AS [Started],
         ISNULL(convert(NVARCHAR(30),MAT.[StatuteLimits],23),'''')		AS [StatuteLimits],
         RTRIM(ISNULL(MAT.[DepositName], ''''))							AS [DepositName],
         ISNULL(MAT.[EstFee], 0)										AS [EstFee],
         ISNULL(CONVERT(NVARCHAR(30),MAT.[ExpBillD],23),'''')				AS [ExpBillD],
         CASE WHEN RTRIM(ISNULL(MAT.[Section68], '''')) = ''Y''
              THEN ''True''
              ELSE ''False'' END											AS [EstimateGiven],
         CASE WHEN RTRIM(ISNULL(MAT.[S13], '''')) = ''Y''
              THEN ''True''
              ELSE ''False'' END											AS [S13],
         ISNULL(MAT.[OutlayBud], 0)										AS [OutlayBud],
         RTRIM(ISNULL(MAT.[DepositType], ''''))							AS [DepositType],
         RTRIM(ISNULL(MAT.[Comment], ''''))								AS [Comment],
         ISNULL(MAT.[ChargeLevel], 0)									AS [ChargeLevel],
         ISNULL(MAT.[DebtCollected], 0)									AS [DebtCollected],
         RTRIM(ISNULL(MAT.[ClientName], ''''))							AS [ClientName],
         RTRIM(ISNULL(MAT.[ClientAddress], ''''))							AS [ClientAddress],
         RTRIM(ISNULL(MAT.[ClientSalutation], ''''))						AS [ClientSalutation],
         RTRIM(ISNULL(MAT.[ChargeArrangement], ''''))						AS [ChargeArrangement],
         CASE WHEN RTRIM(ISNULL(MAT.[ChargeOutRateInd], '''')) = ''Y''
              THEN ''True''
          ELSE ''False'' END											AS [ChargeOutRateInd],
         RTRIM(ISNULL(MAT.[CompFrequency], ''''))							AS [BillingType],
         RTRIM(ISNULL(MAT.[BillingMethod], ''''))							AS [BillingMethod],
         CASE WHEN RTRIM(ISNULL(MAT.[Publish], '''')) = ''P''
              THEN ''True''
              ELSE ''False'' END											AS [Publish],
         RTRIM(ISNULL(CSM.[CSPREMISES], ''''))							AS [Premises],
         RTRIM(ISNULL(CSM.[CSWKTCODE], ''''))								AS [CasePlanType],
         ISNULL(MAT.[CollectingBalance], 0)								AS [CollectingBalance],
         RTRIM(ISNULL(MAT.[PCode], ''''))									AS [PCode],
         RTRIM(ISNULL(MAT.[PFECode], ''''))								AS [PFECode],
         RTRIM(ISNULL(CSM.[CSCLBENYN], ''''))								AS [CSCLBENYN],
         RTRIM(ISNULL(CSM.[CSCLEXEYN], ''''))								AS [CSCLEXEYN],
         ISNULL(CSM.[CSDATEACCEPT_DATE],'''')								AS [CSDATEACCEPT_DATE],
         ISNULL(MAT.[OriginalDebt], 0)									AS [CSORGDEBT], -- John 2015-11-12 This field is used more often (e.g. reports, case import)
         ISNULL(CSM.[CSBALDEBT], 0)										AS [CSBALDEBT],
         RTRIM(ISNULL(CSM.[CSIRTCODE], ''''))								AS [InterestCode],
         RTRIM(ISNULL(CSM.[CSPLAINTNO], ''''))							AS [RecordNo],
         RTRIM(ISNULL(MAT.[FixedFee], ''''))								AS [FixedFee],
         RTRIM(ISNULL(MAT.[ShowCommentInAlarm], ''''))					AS [ShowCommentInAlarm],
         RTRIM(ISNULL(MAT.[Closed], ''''))								AS [Closed],
         ISNULL(MAT.[OrgClosedDate],'''')									AS [OrgClosedDate],
         ISNULL(MAT.[CloseDate],'''')										AS [CloseDate],
         RTRIM(ISNULL(FCL.[COLOURDESC], ''''))							AS [FileColourDescription],
         ISNULL(FCL.[RGBColour], -1)									AS [FileColourRGB],
         RTRIM(ISNULL(MAT.[CompBillingMatter], ''''))						AS [CompBillingMatter],
         RTRIM(ISNULL(MAT.[Branch], ''''))								AS [Branch],
         ISNULL(MAT.[FileNum], 0)										AS [FileNum],
         ISNULL(MAT.[ClosingDate],'''')									AS [ClosingDate],
         RTRIM(ISNULL(MAT.[Location], ''''))								AS [Location],
         RTRIM(ISNULL(MAT.[ArchiveLocation], ''''))						AS [ArchiveLocation],
         RTRIM(ISNULL(MAT.[FileBarCodeNo], ''''))							AS [FileBarCodeNo],
         RTRIM(ISNULL(MAT.[BoxBarCodeNo], ''''))							AS [BoxBarCodeNo],
         RTRIM(ISNULL(MAT.[BoxNumber], ''''))								AS [BoxNumber],
         ISNULL(CONVERT(NVARCHAR(30),MAT.[DestroyDate],23),'''')			AS [DestroyDate],
         ISNULL(CONVERT(NVARCHAR(30),[ActualDestroyDate],23),'''')		AS [ActualDestroyDate],
         RTRIM(ISNULL(MAT.[DestroyedBy], ''''))							AS [DestroyedBy],
         REPLACE(ISNULL(S.Retired,''N''),'' '',''N'')							AS [Retired],
         REPLACE(ISNULL(FCL.Retired,''N''),'' '',''N'')						AS [FileColourRetired],
         REPLACE(ISNULL(FE.Retired,''N''),'' '',''N'')						AS [FeeEarnerRetired],
         REPLACE(ISNULL(D.RETIRED,''N''),'' '',''N'')							AS [DepartmentRetired],
         REPLACE(ISNULL(W.RETIRED,''N''),'' '',''N'')							AS [WorkTypeRetired],
         REPLACE(ISNULL(P.RETIRED,''N''),'' '',''N'')							AS [PartnerRetired],
         REPLACE(ISNULL(T.RETIRED,''N''),'' '',''N'')							AS [CasePlanRetired],
         RTRIM(ISNULL(MAT.[BillingFE], ''''))								AS [BillingFeeEarner],
         ISNULL(MAT.[Started],'''')										AS [Started1],
		 ISNULL(MAT.[Paperless],0)						  				AS [Paperless],
		 MAT.[FeeType],
         CASE WHEN 
                 ISNULL(MAT.NoWinNoFee,''N'') = ''Y'' 
              THEN ''True'' 
              ELSE ''False'' 
              END														AS [NoWinNoFee],
		1															AS [PaperlessColumnExist]

    FROM 
         [dbo].[matters] MAT
         LEFT JOIN [dbo].[CaseMaster] CSM ON CSM.[CSCODE] = MAT.[Code]
         LEFT OUTER JOIN [dbo].[FileColours] FCL ON FCL.[COLOURCODE] = MAT.[FileColour]
         LEFT JOIN StatusCodes S ON MAT.[Status] =  S.CODE
         LEFT JOIN FeeEarnerCodes FE ON RTRIM(MAT.FECode) = RTRIM(FE.Code)
         LEFT JOIN Departments D ON RTRIM(MAT.Dept) = RTRIM(D.CODE)
         LEFT JOIN WorkTypes W ON RTRIM(MAT.WType) = RTRIM(W.CODE)
         LEFT JOIN Partners P ON RTRIM(MAT.[Partner]) = RTRIM(P.CODE)
         LEFT JOIN Templates T ON RTRIM(CSM.CSWKTCODE) = RTRIM(T.WKCODE)
   WHERE 
         MAT.[Code] =''' + @MatterCode +'''')
END
ELSE
BEGIN
	--Matter Details
   SELECT 
         RTRIM(ISNULL(MAT.[ClientCode], ''))                          AS [ClientCode],
         RTRIM(ISNULL(MAT.[Matter], ''))                              AS [Matter],
         RTRIM(ISNULL(MAT.[Description], ''))                         AS [Description] ,
         RTRIM(ISNULL(MAT.[FECode], ''))                              AS [FeeEarner],
         RTRIM(ISNULL(MAT.[Partner], ''))                             AS [Partner],
         RTRIM(ISNULL(MAT.[Secretary], ''))                           AS [Secretary],
         RTRIM(ISNULL(MAT.[Dept], ''))                                AS [Dept] ,
         RTRIM(ISNULL(MAT.[WType], ''))                               AS [WType] ,
         RTRIM(ISNULL(MAT.[OldRef], ''))                              AS [OldRef] ,
         RTRIM(ISNULL(MAT.[User1], ''))                               AS [User1],
         RTRIM(ISNULL(MAT.[User2], ''))                               AS [User2],
         RTRIM(ISNULL(MAT.[User3], ''))                               AS [User3],
         RTRIM(ISNULL(MAT.[YourRef], ''))                             AS [YourRef],
         CASE WHEN RTRIM(ISNULL(MAT.[Statements], '')) = 'Y'
              THEN 'True'
              ELSE 'False' END											AS [Statements],
         ISNULL(MAT.[Importance], 0)									AS [Importance],
         RTRIM(ISNULL(MAT.[Status], ''))								AS [Status],
         RTRIM(ISNULL(MAT.[FileColour], ''))							AS [FileColour],
         ISNULL(MAT.[Value], 0)											AS [ValueToClient],
         ISNULL(CONVERT(NVARCHAR(30),MAT.[Started],23),'')				AS [Started],
         ISNULL(convert(NVARCHAR(30),MAT.[StatuteLimits],23),'')		AS [StatuteLimits],
         RTRIM(ISNULL(MAT.[DepositName], ''))							AS [DepositName],
         ISNULL(MAT.[EstFee], 0)										AS [EstFee],
         ISNULL(CONVERT(NVARCHAR(30),MAT.[ExpBillD],23),'')				AS [ExpBillD],
         CASE WHEN RTRIM(ISNULL(MAT.[Section68], '')) = 'Y'
              THEN 'True'
              ELSE 'False' END											AS [EstimateGiven],
         CASE WHEN RTRIM(ISNULL(MAT.[S13], '')) = 'Y'
              THEN 'True'
              ELSE 'False' END											AS [S13],
         ISNULL(MAT.[OutlayBud], 0)										AS [OutlayBud],
         RTRIM(ISNULL(MAT.[DepositType], ''))							AS [DepositType],
         RTRIM(ISNULL(MAT.[Comment], ''))								AS [Comment],
         ISNULL(MAT.[ChargeLevel], 0)									AS [ChargeLevel],
         ISNULL(MAT.[DebtCollected], 0)									AS [DebtCollected],
         RTRIM(ISNULL(MAT.[ClientName], ''))							AS [ClientName],
         RTRIM(ISNULL(MAT.[ClientAddress], ''))							AS [ClientAddress],
         RTRIM(ISNULL(MAT.[ClientSalutation], ''))						AS [ClientSalutation],
         RTRIM(ISNULL(MAT.[ChargeArrangement], ''))						AS [ChargeArrangement],
         CASE WHEN RTRIM(ISNULL(MAT.[ChargeOutRateInd], '')) = 'Y'
              THEN 'True'
              ELSE 'False' END											AS [ChargeOutRateInd],
         RTRIM(ISNULL(MAT.[CompFrequency], ''))							AS [BillingType],
         RTRIM(ISNULL(MAT.[BillingMethod], ''))							AS [BillingMethod],
         CASE WHEN RTRIM(ISNULL(MAT.[Publish], '')) = 'P'
              THEN 'True'
              ELSE 'False' END											AS [Publish],
         RTRIM(ISNULL(CSM.[CSPREMISES], ''))							AS [Premises],
         RTRIM(ISNULL(CSM.[CSWKTCODE], ''))								AS [CasePlanType],
         ISNULL(MAT.[CollectingBalance], 0)								AS [CollectingBalance],
         RTRIM(ISNULL(MAT.[PCode], ''))									AS [PCode],
         RTRIM(ISNULL(MAT.[PFECode], ''))								AS [PFECode],
         RTRIM(ISNULL(CSM.[CSCLBENYN], ''))								AS [CSCLBENYN],
         RTRIM(ISNULL(CSM.[CSCLEXEYN], ''))								AS [CSCLEXEYN],
         ISNULL(CSM.[CSDATEACCEPT_DATE],'')								AS [CSDATEACCEPT_DATE],
         ISNULL(MAT.[OriginalDebt], 0)									AS [CSORGDEBT], -- John 2015-11-12 This field is used more often (e.g. reports, case import)
         ISNULL(CSM.[CSBALDEBT], 0)										AS [CSBALDEBT],
         RTRIM(ISNULL(CSM.[CSIRTCODE], ''))								AS [InterestCode],
         RTRIM(ISNULL(CSM.[CSPLAINTNO], ''))							AS [RecordNo],
         RTRIM(ISNULL(MAT.[FixedFee], ''))								AS [FixedFee],
         RTRIM(ISNULL(MAT.[ShowCommentInAlarm], ''))					AS [ShowCommentInAlarm],
         RTRIM(ISNULL(MAT.[Closed], ''))								AS [Closed],
         ISNULL(MAT.[OrgClosedDate],'')									AS [OrgClosedDate],
         ISNULL(MAT.[CloseDate],'')										AS [CloseDate],
         RTRIM(ISNULL(FCL.[COLOURDESC], ''))							AS [FileColourDescription],
         ISNULL(FCL.[RGBColour], -1)									AS [FileColourRGB],
         RTRIM(ISNULL(MAT.[CompBillingMatter], ''))						AS [CompBillingMatter],
         RTRIM(ISNULL(MAT.[Branch], ''))								AS [Branch],
         ISNULL(MAT.[FileNum], 0)										AS [FileNum],
         ISNULL(MAT.[ClosingDate],'')									AS [ClosingDate],
         RTRIM(ISNULL(MAT.[Location], ''))								AS [Location],
         RTRIM(ISNULL(MAT.[ArchiveLocation], ''))						AS [ArchiveLocation],
         RTRIM(ISNULL(MAT.[FileBarCodeNo], ''))							AS [FileBarCodeNo],
         RTRIM(ISNULL(MAT.[BoxBarCodeNo], ''))							AS [BoxBarCodeNo],
         RTRIM(ISNULL(MAT.[BoxNumber], ''))								AS [BoxNumber],
         ISNULL(CONVERT(NVARCHAR(30),MAT.[DestroyDate],23),'')			AS [DestroyDate],
         ISNULL(CONVERT(NVARCHAR(30),[ActualDestroyDate],23),'')		AS [ActualDestroyDate],
         RTRIM(ISNULL(MAT.[DestroyedBy], ''))							AS [DestroyedBy],
         REPLACE(ISNULL(S.Retired,'N'),' ','N')							AS [Retired],
         REPLACE(ISNULL(FCL.Retired,'N'),' ','N')						AS [FileColourRetired],
         REPLACE(ISNULL(FE.Retired,'N'),' ','N')						AS [FeeEarnerRetired],
         REPLACE(ISNULL(D.RETIRED,'N'),' ','N')							AS [DepartmentRetired],
         REPLACE(ISNULL(W.RETIRED,'N'),' ','N')							AS [WorkTypeRetired],
         REPLACE(ISNULL(P.RETIRED,'N'),' ','N')							AS [PartnerRetired],
         REPLACE(ISNULL(T.RETIRED,'N'),' ','N')							AS [CasePlanRetired],
         RTRIM(ISNULL(MAT.[BillingFE], ''))								AS [BillingFeeEarner],
         ISNULL(MAT.[Started],'')										AS [Started1],
		 0												  				AS [Paperless],
		 MAT.[FeeType],
         CASE WHEN 
                 ISNULL(MAT.NoWinNoFee,'N') = 'Y' 
              THEN 'True' 
              ELSE 'False' 
              END														AS [NoWinNoFee],
		0														     AS [PaperlessColumnExist]
    FROM 
         [dbo].[matters] MAT
         LEFT JOIN [dbo].[CaseMaster] CSM ON CSM.[CSCODE] = MAT.[Code]
         LEFT OUTER JOIN [dbo].[FileColours] FCL ON FCL.[COLOURCODE] = MAT.[FileColour]
         LEFT JOIN StatusCodes S ON MAT.[Status] =  S.CODE
         LEFT JOIN FeeEarnerCodes FE ON RTRIM(MAT.FECode) = RTRIM(FE.Code)
         LEFT JOIN Departments D ON RTRIM(MAT.Dept) = RTRIM(D.CODE)
         LEFT JOIN WorkTypes W ON RTRIM(MAT.WType) = RTRIM(W.CODE)
         LEFT JOIN Partners P ON RTRIM(MAT.[Partner]) = RTRIM(P.CODE)
         LEFT JOIN Templates T ON RTRIM(CSM.CSWKTCODE) = RTRIM(T.WKCODE)
   WHERE 
         MAT.[Code] = @MatterCode
END
--Privileges
   EXEC KAAS_GetMatterPrivilegeGroups @MatterCode
--Udf Fields
   SELECT 
          RTRIM(ISNULL(UFC.[UDFCategory], ''))                       AS [UDFCategory],
          RTRIM(ISNULL(SUF.[PROMPT], ''))                            AS [Prompt],
          CASE RTRIM(ISNULL(SUF.[TYPE], ''))
               WHEN 'Text'
                    THEN CONVERT(VARCHAR(200), CUF.[TEXT1])
               WHEN 'Numeric'
                    THEN CONVERT(VARCHAR(50), CUF.[NumberValue])
               WHEN 'Date'
                    THEN CONVERT(VARCHAR, CUF.[DateValue], 106)
               ELSE CONVERT(VARCHAR(200), CUF.[TEXT1]) END           AS [Value],
          RTRIM(ISNULL(CUF.[CASECODE], ''))                          AS [CaseCode],
          RTRIM(ISNULL(CUF.[UDFFile], ''))                           AS [UDFFile],
          RTRIM(ISNULL(CUF.[UDFNAME], ''))                           AS [UDFName],
          ISNULL(CUF.[SEQNO], 0)                                     AS [SeqNo],
          RTRIM(ISNULL(CUF.[TEXT1], '-'))                            AS [Text1],
          RTRIM(ISNULL(SUF.[FILEPREFIX], ''))                        AS [FilePrefix],
          RTRIM(ISNULL(SUF.[FIELDNAME], ''))                         AS [FieldName],
          RTRIM(ISNULL(SUF.[FORMAT], ''))                            AS [Format],
          RTRIM(ISNULL(SUF.[ACTUALNAME], ''))                        AS [ActualName],
          ISNULL(CUF.[NumberValue], 0)                               AS [NumberValue],
          CUF.[DateValue]                                            AS [DateValue]
      FROM
          [dbo].[CaseUDFAnswers] CUF
          INNER JOIN [dbo].[SystemUserDefinedFields] SUF
                   ON SUF.[FILEPREFIX] = CUF.[UDFFile]
                   AND SUF.[FIELDNAME] = CUF.[UDFNAME]
           INNER JOIN [dbo].[UDFCategory] UFC
                   ON UFC.[ID] = SUF.[UDFCategory]
     WHERE 
          CUF.[CASECODE] = @MatterCode
     ORDER BY ISNULL(CUF.[SEQNO], 0)
--Case Associates
    SELECT
	       IDENTITY(INT, 1,1)                                         AS [Row_Number],
		   *
	INTO
		    #FoundTable
	FROM
	(SELECT
           RTRIM(ISNULL(CSC.[CASECODE], ''))                          AS [CaseCode],
           RTRIM(CSC.[CONTYPE])                                       AS [ConType],
           ISNULL(CSC.[CONNUM], 0)                                    AS [ConNum],
           RTRIM(ISNULL(CSC.[NAMECODE], ''))                          AS [ConNameCode],
           RTRIM(ISNULL(CSC.[SOLCODE], ''))                           AS [SolCode],
           RTRIM(ISNULL(CSC.[SOLREF], ''))                            AS [SolRef],
           RTRIM(ISNULL(CSC.[INSCODE], ''))                           AS [InsCode],
           ISNULL(CSC.[ASSIGNEDCONTACT], 0)                           AS [AssignedContact],
           RTRIM(ISNULL(CAC.[NAMECODE], ''))                          AS [AssociateNameCode],
           ISNULL(CAC.[KEYID], 0)                                     AS [KeyId],
           RTRIM(ISNULL(CAC.[NAME], ''))                              AS [ConName],
           RTRIM(ISNULL(CAC.[PHONE], ''))                             AS [Phone],
           RTRIM(ISNULL(CAC.[EMAIL], ''))                             AS [ConEmail],
           RTRIM(ISNULL(AST.[CODE], ''))                              AS [Code],
           RTRIM(ISNULL(AST.[DESCRIPTION], ''))                       AS [Description],
           RTRIM(ISNULL(CAN.[CODE], ''))                              AS [ConCode],
           RTRIM(ISNULL(CAN.[TYPE], ''))                              AS [Type],
           RTRIM(ISNULL(CAN.[NAME], ''))                              AS [AssociateName],
           RTRIM(ISNULL(CAN.[COMPANY], ''))							  AS [Company],
           RTRIM(ISNULL(CAN.[ADDRESS], ''))                           AS [Address],
           RTRIM(ISNULL(CAN.[PHONENO], ''))                           AS [PhoneNo],
           RTRIM(ISNULL(CAN.[MOBILENO], ''))                          AS [MobileNo],
           RTRIM(ISNULL(CAN.[EMAIL], ''))                             AS [AssociateEmail],
           RTRIM(ISNULL(CAN.[SEARCH], ''))                            AS [Search],
           ISNULL(CAN.[CONTACTNO], 0)                                 AS [ContactNo],
           RTRIM(ISNULL(CAN.[SALUTATION], ''))                        AS [Salutation],
           ISNULL(CSC.[CONNUM], 0)                                    AS [Seq],
           CASE WHEN RTRIM(ISNULL(CAN.[COMPANY], '')) <> ''
                     THEN LTRIM(  RTRIM(ISNULL(CAN.[NAME], ''))
                                + ' ('
                                + RTRIM(ISNULL(CAN.[COMPANY], ''))
                                + ')')
                ELSE RTRIM(ISNULL(CAN.[NAME], '')) END                AS [NameCompany],
           ISNULL(CSC.Retired,'N')                                    AS [Retired]
      FROM [dbo].[CaseContacts] CSC
           LEFT JOIN [dbo].[CaseAssociatesContacts] CAC
                   ON CAC.[KEYID] = CSC.[AssignedContact]
           LEFT JOIN [dbo].[AssociateTypes] AST
                   ON AST.[CODE] = CSC.[CONTYPE]
           LEFT JOIN [dbo].[CaseAssociatesNames] CAN
                   ON CAN.[CODE] = CSC.[NAMECODE]
                  AND CAN.[NAME] <> ''
                  AND CAN.[NAME] <> 'N/A'
                  AND CAN.[NAME] IS NOT NULL
     WHERE CSC.[CASECODE]  = @MatterCode
       AND CSC.[NAMECODE] <> ''
       AND CSC.[NAMECODE] <> 'N/A'
       AND CSC.[NAMECODE] IS NOT NULL) AS FoundTable
     ORDER BY [CASECODE],
              [CONTYPE],
              [CONNUM]

	 SELECT
		*
	 FROM
	  	#FoundTable
--ChargeOut Rate Indicator    
    SELECT MCOR.[RecordID]                                 AS [RecordId],
           RTRIM(MCOR.[FeCode])                            AS [FeCode],
           ISNULL(MCOR.[Rate], 0)                          AS [Rate],
           MCOR.[EffectiveDate]                            AS [EffectiveDate],
           COALESCE(HAN.[Name], HCG.[Name], MCOR.[FeCode]) AS [FeeEarnerName],
           CASE WHEN ISNULL(HAN.[Retired], 'N') = 'Y'
                     THEN ISNULL(HAN.[Retired], 'N')
                ELSE ISNULL(HCG.[Retired], 'N') END        AS [IsRetired]                
      FROM [dbo].[MatterChargeOutRates] AS MCOR
           LEFT OUTER JOIN [dbo].[Handlers] AS HAN
                        ON HAN.[Code] = MCOR.[FeCode]
           LEFT OUTER JOIN [dbo].[HandlerChargeGroups] AS HCG
                        ON HCG.[Code] = MCOR.[FeCode]
     WHERE MCOR.[MatterCode] = @MatterCode
       AND (ISNULL(HAN.[Retired], 'N') <> 'Y' 
         OR ISNULL(HCG.[Retired], 'N') <> 'Y')

--Linked Cases List
  SELECT 
        LMT.[RecordId]                                               AS [RecordId],
        MAT.[Code]                                                   AS [CaseCode],
        MAT.[FECode]                                                 AS [FeeEarner],
        CNT.[Name]                                                   AS [Name],
        MAT.[Description]                                            AS [Description],
        LMT.[RelationShip]                                           AS [Relationship]
   FROM [dbo].[LinkedMatters] LMT
         INNER JOIN [dbo].[matters] MAT
                 ON MAT.[Code] = LMT.[LinkedMatter]
         INNER JOIN [dbo].[Contacts] CNT
                 ON CNT.[Code] = MAT.[ClientCode]
   WHERE LMT.[PrimeMatter] = @MatterCode
--Revenue Module
  SELECT RTRIM(LTRIM(ISNULL(MCC.[CheckCharacter], '') ))   AS [CheckCharacter],
         RTRIM(LTRIM(ISNULL(MCC.[AddCheckCharacter], ''))) AS [AddCheckCharacter]
    FROM [dbo].[MatterCheckChars] AS MCC
   WHERE MCC.[MatterCode] = @MatterCode

--Locations
EXECUTE KAAS_ListItemLocations

--Outstanding Undertaking and Case diary
  SELECT COUNT(1) OutstandingUndertaking
    FROM [dbo].[Undertakings] UTS          
   WHERE [UTS].[Matter] = @MatterCode AND ISNULL([UTS].[DischargeDate],'') = ''
  SELECT COUNT(1)  OutstandingCaseDiary
    FROM [dbo].[Diary] DRY          
   WHERE [DRY].[casecode] = @MatterCode AND ISNULL([DRY].[Status],0) = 0

--Check Matter is eligible to closed
   EXEC KAAS_GetSAM_MatterClosable @MatterCode

SET NOCOUNT OFF
  

END

GO

IF OBJECT_ID(N'KAAS_GetSAMDashboardDetails',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetSAMDashboardDetails]
GO
CREATE PROCEDURE
       [dbo].[KAAS_GetSAMDashboardDetails]
	   (
		@HandlerCode VARCHAR(10)
	   )

AS
/*******************************************************************************************************
* This sp used to get dashboard details																   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_GetSAMDashboardDetails]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-08-25	Natarajan S     		Created                                                        *
* 2021-12-22	Balamurugan C     		Modified - Removed Where condition for RBatch Table            *
* 2022-05-09	Vignesh M       		Modified - Date filter added for RBatch Table                  *
* 2023-07-05	Aakif					Modified - Replaced 'Count(*)' with 'Count(1)				   *
* 2024-01-17	Balamurugan.C			Modified - Added Queries for Debtors,Unallocated Payments,	   *
										Unallocated Receipts,Debit Client A/c's,Office Credit A/c's	   *
										Draft Invoice Approval,Payment awaiting approval               *
* 2024-01-19	Balamurugan.C			Added logic to fetch recent matter details                     *
*******************************************************************************************************/ 

BEGIN    

-- Matter Count Details

     SELECT CASE Closed 
		WHEN 'N'
		THEN 'Opened' 
		ELSE 'Closed' END AS [MatterState],
			COUNT(1) AS [CountValue]
	   FROM [dbo].[matters] 
   GROUP BY [Closed]

    SELECT COUNT(1) AS Posted 
	  FROM batchh 
	 where posted = 'N'

	 --Unposted Batches Details
    SELECT [BatchNo],
           [Type],
   		   [Ref], 
   		   [Date],
   		   [Value], 
   		   [Narr] 
      FROM [dbo].[BatchH]  
     WHERE [Posted] = 'N' 
  ORDER BY [Posted] ASC,
           [EntryDate] ASC


--Memoried Details
    SELECT ROW_NUMBER() OVER ( ORDER BY Date ) OrderValue, 
	       [BatchNo],  
           [Type],
           [Date], 
           [Code],  
           [Value],  
           [Supp],
           [Matter], 
           [Narr]
      FROM [dbo].RBatchH A 
	 WHERE [DATE] <= CAST(GETDATE() AS DATE)
  ORDER BY [Date] ASC, 
           [BatchNo] ASC

--Event Details
   SELECT  [Date], 
           [User], 
		   [Event], 
           [RecordID]
	  FROM [dbo].[Log] 
 ORDER BY  [RecordID] ASC

	--Open Matters
	DECLARE @HowMany INT;

	SET @HowMany = (SELECT COUNT(1) FROM [dbo].[matters] WHERE [Closed] = 'N');

	DECLARE @Handler VARCHAR(20) = 'MK';

	DECLARE @XmlString NVARCHAR(MAX);
	SET @XmlString = '<search closed="" orderby="" order="ASC" howmany="' + CAST(@HowMany AS VARCHAR(10)) + '" which="2" search="" handler="' + @HandlerCode + '" />';

	EXEC [dbo].[KAAS_OffsetGetOpenMatterDetails] @XmlString, 1, @HowMany, '', '','','','Dashboard';

	--Closed Matter
    SELECT [UniqueId] [OrderValue],
	       [Code],
	       [Matter],
		   [Description],
		   [FECode],
		   [Dept] 
	  FROM [dbo].[matters] 
	 WHERE [Closed]='Y'

	 --Common Details
	SELECT [Name] [DBName],
	       [CurPer],
		   [Year],
	       dbo.KAAS_FN_GetDateFromClarion (PERIODEND) AS PeriodEnd,
		   dbo.KAAS_FN_GetDateFromClarion (LASTRECDATE) AS LastRecDate
	  FROM [dbo].[control]


	  -- Sum of outstanding debt
SELECT SUM([DTL].[OSVALUE]) AS [Debtors]
  FROM [dbo].[DebtorsLedger] AS [DTL]

-- Details of outstanding debt
SELECT ISNULL([DTL].[MATTER], '')  AS [Matter],
       [DTL].[DATE] AS [Date],
       ISNULL([DTL].[REF], '')     AS [Ref],
       ISNULL([DTL].[NARR], '')    AS [Narr],
       ISNULL([DTL].[ORIGINAL], 0) AS [Amount],
       ISNULL([DTL].[OSVALUE], 0)  AS [AmountOS],
       ISNULL([DTL].[BATCHNO], 0)  AS [BatchNo],
       ISNULL([DTL].[PREF], 0)     AS [PRef]
  FROM [dbo].[DebtorsLedger] AS [DTL]
 WHERE [DTL].[OSVALUE] <> 0

-- Count of unallocated payments
SELECT COUNT(1) AS [Unallocated Payments]
  FROM [dbo].[SupplierLedger] AS [SPL]
 WHERE [SPL].[TYPE] = 'P'
   AND [SPL].[OSVALUE] <> 0

-- Details of unallocated payments
SELECT COALESCE([SUP].[NAME], [SPL].[SUPP], '') AS [Supp],
       [SPL].[DATE] AS [Date],
       ISNULL([SPL].[REF], '')		AS [Ref],
       ISNULL([SPL].[NARR], '')		AS [Narr],
       ISNULL([SPL].[ORIGINAL], 0)	AS [Original],
       ISNULL([SPL].[OSVALUE], 0)	AS [OSValue],
       ISNULL([SPL].[SUPP], '')		AS [SupplierCode],
       ISNULL([SPL].[BATCHNO], 0)	AS [BatchNo],
       ISNULL([SPL].[PREF], 0)		AS [PRef]
  FROM [dbo].[SupplierLedger]		AS [SPL]
       LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
                    ON [SPL].[SUPP] = [SUP].[CODE]
 WHERE [SPL].[TYPE] = 'P'
   AND [SPL].[OSVALUE] <> 0

-- Count of unallocated receipts
SELECT COUNT(1) AS [Unallocated Receipts]
  FROM [dbo].[DebtorsLedger] AS [DTL]
 WHERE [DTL].[TYPE] = 'R'
   AND [DTL].[OSVALUE] <> 0

-- Details of unallocated receipts
SELECT COALESCE([CNT].[Name], [MAT].[ClientCode], '') AS [Client],
       ISNULL([MAT].[ClientCode], '') AS [ClientCode],
       [DTL].[DATE] AS [Date],
       ISNULL([DTL].[REF], '') AS [Ref],
       ISNULL([DTL].[BATCHNO], 0) AS [BatchNo],
       ISNULL([DTL].[PREF], 0) AS [PRef],
       ISNULL([DTL].[NARR], '') AS [Narr],
       ISNULL([DTL].[ORIGINAL], 0) AS [Original],
       ISNULL([DTL].[OSVALUE], 0) AS [OSValue]
  FROM [dbo].[DebtorsLedger] AS [DTL]
       LEFT OUTER JOIN [dbo].[matters] AS [MAT]
                    ON [MAT].[Code] = [DTL].[MATTER]
       LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
                    ON [CNT].[Code] = [MAT].[ClientCode]
 WHERE [DTL].[TYPE] = 'R'
   AND [DTL].[OSVALUE] <> 0

-- count matters with client debit balances
SELECT COUNT(1) AS [ClientDebitAccounts]
  FROM (
SELECT [MAT].[Code], ISNULL(SUM([MTL].[VALUEC]), 0) AS [ClientBalance]
  FROM [dbo].[matters] AS [MAT]
       INNER JOIN [dbo].[MatterLedger] AS [MTL]
               ON [MTL].[MATTER] = [MAT].[Code]
       GROUP BY [MAT].[Code]
HAVING ISNULL(SUM([MTL].[VALUEC]), 0) > 0) AS [DCA]

-- list matters with client debit balances
;WITH [ClientDebitAccounts] ([Code], [ClientBalance]) AS (
SELECT [MAT].[Code], ISNULL(SUM([MTL].[VALUEC]), 0) AS [ClientBalance]
  FROM [dbo].[matters] AS [MAT]
       INNER JOIN [dbo].[MatterLedger] AS [MTL]
               ON [MTL].[MATTER] = [MAT].[Code]
       GROUP BY [MAT].[Code]
HAVING ISNULL(SUM([MTL].[VALUEC]), 0) > 0)

SELECT COALESCE([CNT].[Name], [MAT].[ClientCode], '') AS [Client],
       ISNULL([MAT].[ClientCode], '') AS [ClientCode],
       [CDA].[Code] AS [Matter],
       ISNULL([MAT].[Description], '') AS [MatterDescription],
       [CDA].[ClientBalance]
  FROM [ClientDebitAccounts] AS [CDA]
       LEFT OUTER JOIN [dbo].[matters] AS [MAT]
                    ON [MAT].[Code] = [CDA].[Code]
       LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
                    ON [CNT].[COde] = [MAT].[ClientCode]

-- count matters with office credit balance
SELECT COUNT(1) AS [OfficeCreditBalances]
  FROM (
SELECT [MAT].[Code],
       ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) AS [OfficeBalance]
  FROM [dbo].[matters] AS [MAT]
       INNER JOIN [dbo].[MatterLedger] AS [MTL]
               ON [MAT].[Code] = [MTL].[MATTER]
       GROUP BY [MAT].[Code]
HAVING ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) < 0) AS [OCB]

-- list matters with office credit balances
;WITH [OfficeCreditAccounts] ([Code], [OfficeBalance]) AS (
SELECT [MAT].[Code],
       ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) AS [OfficeBalance]
  FROM [dbo].[matters] AS [MAT]
       INNER JOIN [dbo].[MatterLedger] AS [MTL]
               ON [MAT].[Code] = [MTL].[MATTER]
       GROUP BY [MAT].[Code]
HAVING ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) < 0)

SELECT COALESCE([CNT].[Name], [MAT].[ClientCode], '') AS [Client],
       ISNULL([MAT].[ClientCode], '') AS [ClientCode],
       [OCA].[Code] AS [Matter],
       ISNULL([MAT].[Description], '') AS [MatterDescription],
       [OCA].[OfficeBalance]
  FROM [OfficeCreditAccounts] AS [OCA]
       LEFT OUTER JOIN [dbo].[matters] AS [MAT]
                    ON [MAT].[Code] = [OCA].[Code]
       LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
                    ON [CNT].[COde] = [MAT].[ClientCode]

-- Draft invoices awaiting approval
SELECT COUNT(1) AS [DraftInvoicesAwaitingApproval]
  FROM [dbo].[BillHeader] AS [BH]
 WHERE [BH].[BILLNO] = 0
   AND [BH].[RELEASED] = 'Y'

-- Detail of Draft invoices awaiting approval
SELECT ISNULL([BH].[MATTER], '') AS [Matter],
       [BH].[DRAFTNO] AS [DraftNo],
       [BH].[DATE] AS [Date],
       [BH].[ADDRESSEE] AS [Addressee],
       ISNULL([BH].[TOTAL], 0) AS [Total],
       ISNULL([BH].[FEES], 0) AS [Fees],
       ISNULL([BH].[OUTLAY], 0) AS [Outlay],
       ISNULL([BH].[TOTALVAT], 0) AS [VAT]
  FROM [dbo].[BillHeader] AS [BH]
 WHERE [BH].[BILLNO] = 0
   AND [BH].[RELEASED] = 'Y'

-- Payments awaiting approval
SELECT COUNT(1) AS [PaymentsAwaitingApproval]
  FROM [dbo].[ChequeRequisitionHeader] AS [CRH]
 WHERE ISNULL([CRH].[STATUS], 0) = 1

-- Detail of Payments awaiting approval
SELECT [CRH].[REQNO] AS [ReqNo],
       [CRH].[DATE] AS [Date],
       COALESCE([NOM].[DESC], [CRH].[BANK], '') AS [Bank],
       ISNULL([CRH].[PAYEE], '') AS [Payee],
       ISNULL([CRH].[NARRATIVE], '') AS [Narr],
       ISNULL([CRH].[VALUE], 0) AS [Value]
  FROM [dbo].[ChequeRequisitionHeader] AS [CRH]
       LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                    ON [NOM].[CODE] = [CRH].[BANK]
 WHERE ISNULL([CRH].[STATUS], 0) = 1
 --WHERE [CRH].[STATUS] = 1

END




GO





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

CREATE PROCEDURE 
[dbo].[KAAS_GetSamDebtLodgeClientList]
AS

/*******************************************************************************************************
* Get Debt Lodgement Client List                                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamDebtLodgeClientList]        						       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-04    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/

BEGIN
			SELECT		[CONT].[CODE]				AS	[Code], 
						[CONT].[NAME]				AS	[Name], 
						[CONT].[ADDRESS]			AS	[Address], 
						[CONT].[FE]					AS	[FE], 
						[CONT].[CLIENT]				AS	[Client],
						[CONT].[CLIENTGROUP]		AS	[ClientGroup],
						[CONT].[OTHERREF]			AS	[OtherRef], 
						[CONT].[OPSISREF]			AS	[OpSisRef], 
						[CONT].[CONTACTNO]			AS	[ContactNo],
						[CONT].[COMPBILLONOFF]		AS	[CompBillOnOff], 
						[CONT].[TAXTYPE]			AS	[TaxType]
			FROM		[dbo].[contacts] [CONT]
			WHERE		[CONT].[CLIENT] = 'Y'
			ORDER BY	[CONT].[CODE] ASC

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

CREATE PROCEDURE 
[dbo].[KAAS_GetSamDebtLodgementList]
(@MatterCode	VARCHAR(20) = '')
AS

/*******************************************************************************************************
* Get Debt Lodgement List                                                                              * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamDebtLodgementList]        							       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-04    Vinodhkumar M        Created                                                           *
* 2021-10-13    Vinodhkumar M        Modified - Payment method parameter is removed and				   *
												MatterDescription,Branch is added                      *
*******************************************************************************************************/

BEGIN
		SELECT      [DEBT].[MATTERCODE]					AS	[MatterCode], 
					[DEBT].[DATE]						AS	[Date],
					[DEBT].[REFERENCE]					AS	[Reference],
					[DEBT].[DESCRIPTION]				AS	[Description],
					[DEBT].[TYPE]						AS	[Type], 
					[DEBT].[VALUE]						AS	[Value],
					[DEBT].[INTEREST]					AS	[Interest],
					[DEBT].[REMITTANCENO]				AS	[RemittanceNo],
					[DEBT].[POSTINGREF]					AS	[PostingRef],
					[DEBT].[PAYMENTMETHOD]				AS	[PaymentMethod],
					[DEBT].[EFFECTIVEDATE]				AS	[EffectiveDate],
					[MAT].[Description]					AS  [MatterDescription],
					[MAT].[Branch]						AS	[Branch]
		FROM	    [dbo].[DebtCostingLedger] [DEBT]
		LEFT JOIN   [dbo].[matters] [MAT] ON [MAT].[Code] = [DEBT].[MATTERCODE]
		WHERE	    [DEBT].[xnid]          = -1 
		AND			[DEBT].[Type]		   = 'Receipt' 
		AND			[DEBT].[MatterCode] Like (@MatterCode+'%')
		ORDER BY    [DEBT].[POSTINGREF] DESC
		 
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_GetSamDeleteDebtLodgement]
	(
		@PostingRef  INT =  0
	)
AS

/*******************************************************************************************************
* Delete Debt Lodgement		                                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamDeleteDebtLodgement]        						       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-01    Vinodhkumar M        Created                                                           *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/

BEGIN
 SET NOCOUNT ON   
    BEGIN TRY
	  BEGIN TRAN
		 UPDATE	 [dbo].[DebtCostingLedger] 
			SET	 XnId = 0 
		  WHERE  POSTINGREF = @PostingRef
	COMMIT TRAN

	END TRY
		BEGIN CATCH 
			   DECLARE @ErrorMsg      NVARCHAR(4000), 
					   @ErrorSeverity INT,
					   @ErrorState    INT; 

				SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					   @ErrorSeverity = ERROR_SEVERITY(), 
					   @ErrorState    = ERROR_STATE()

			RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
					 IF @@TRANCOUNT > 0  
						BEGIN
							ROLLBACK TRANSACTION;
						END 
		END CATCH
 SET NOCOUNT OFF

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

CREATE PROCEDURE [dbo].[KAAS_GetSAMDraftBillsList]
    (
        @FilterMode VARCHAR(20) = ''
    )
AS

/*******************************************************************************************************
* Get Draft bills List                                                                                 * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMDraftBillsList]        								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-10    Vinodhkumar M        Created                                                           *
* 2021-09-16    Vinodhkumar M        Modifed - Added columns                                           *
* 2021-10-27    Balamurugan C        Modifed - Added Description,FeCode Column and                     *
                                               added where conditions                                  *
* 2022-04-12    Vignesh M            Modifed - Unused Parameters are removed                           *
* 2024-05-07    Balamurugan C        Modified - Data based on grid filters                             *
*******************************************************************************************************/

BEGIN

    SELECT [BH].[MATTER]                   AS [Matter],
           [BH].[DRAFTNO]                  AS [DraftNo],
           [BH].[DATE]                     AS [Date],
           [BH].[USER]                     AS [User],
           RTRIM([BH].[ADDRESSEE])         AS [Address], 
           [BH].[INVCR]                    AS [Invcr],
           [BH].[BILLNO]                   AS [BillNo],
           [BH].[TOTAL]                    AS [Total],
           [BH].[FEES]                     AS [Fees],
           [BH].[OUTLAY]                   AS [Outlay],
           [BH].[TOTALVAT]                 AS [TotalVat],
           [BH].[RELEASED]				   AS [Released], 
           [BH].[ACTIONID]                 AS [ActionId],
           [BH].[OPENINVOICE]			   AS [OpenInvoice],
           [BH].[BATCHNO]                  AS [BatchNo],
           [BH].[OURREF]                   AS [OurRef],
           [BH].[YOURREF]                  AS [YourRef],
           [BH].[BillSent]				   AS [BillSent],
           [BH].[TRANSFER]				   AS [TransferPay],
           [BH].[FEMISCTOTAL]              AS [FeMiscTotal],
           [BH].[WRITEDOWN]                AS [WriteDownDate],
           RTRIM([BH].[RETURNREASON])      AS [Message],
           RTRIM([BH].[MATTERDESCRIPTION]) AS [Description],
           [BH].[FeCode]				   AS [FECode]
    FROM [dbo].[BillHeader] [BH]
    WHERE 
        (
            (@FilterMode = 'Released' AND [BH].[RELEASED] = 'Y' AND ([BH].[BILLNO] = 0 OR [BH].[BILLNO] IS NULL))
            OR
            (@FilterMode = 'Draft' AND ([BH].[RELEASED] <> 'Y' OR [BH].[RELEASED] IS NULL) AND ([BH].[BILLNO] = 0 OR [BH].[BILLNO] IS NULL))
            OR
            (@FilterMode = 'Approved' AND [BH].[BILLNO] <> 0)
            OR
            (@FilterMode NOT IN ('Released', 'Draft', 'Approved'))
        )
    ORDER BY [BH].[DRAFTNO] DESC

END

GO

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

CREATE PROCEDURE 
	   [dbo].[KAAS_GetSAMFeeEarnerCodes]  
AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSAMFeeEarnerCodes]								                                      *
* Description: Get basic details to insert into diary information.                                    *					  
* Modification History:                                                                               *
* 2021-04-10   Natarajan S        Created															  *   
* 2021-08-26   Vinodhkumar M      Modified - Branch is added      									  *
* 2022-01-10   Balamurugan C      Modified - Nominal Details Added      							  *      
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON   

			SELECT [Code],
				   [Name],
				   [Branch],
				   [Nominal]
			  FROM [dbo].[FeeEarnerCodes] [FEE] 
			 WHERE [FEE].[Retired] <> 'Y' 
		  ORDER BY [FEE].[Code] ASC

			SELECT [RECORDID] AS [RecordId],
				   [STATUSDESC] AS [Status] 
			  FROM [dbo].[UndertakingStatus]
		  ORDER BY [STATUSDESC] ASC


 SET NOCOUNT OFF
END 

GO

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

go 

CREATE PROCEDURE [dbo].KAAS_GetSAMFNLDetails (@MatterCode VARCHAR(20)) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to Get FNL Details                                                                               *
  * Stored Procedure Name: [dbo].KAAS_GetSAMFNLDetails	'000001/0000'									 * 
  * Modification History:                                                                                *
  * 2021-03-30 Natarajan S        Created																 *
  * 2021-07-28 Vinodhkumar M      Added null check for FNL Date											 *      
   *******************************************************************************************************/
  BEGIN 
    
SELECT 
  OM.[Code] as [Code], 
   C.[Code] as [ClientCode], 
   C.[Name] as [ClientName], 
  OM.[Matter] AS [MatterCode], 
  OM.[Description] as [MatterName], 
   C.[Address] AS [ClientAddress], 
  OM.[FECode] AS [FECode], 
  ISNULL(OM.[FNL_DATE],GETUTCDATE()) AS [FNLDate], 
  OM.[FNL_NAME] AS [FNLName], 
  OM.[FNL_ADDRESS] AS [FNLAddress], 
  OM.[FNL_FEES] AS [FNLFees], 
  OM.[FNL_OUTLAY] AS [FNLOutlay], 
  OM.[FNL_VAT] AS [FNLVat], 
  OM.[FNL_TOTAL] AS [FNLTotal] 
FROM 
  dbo.OpenMattersONLY OM 
  INNER JOIN Contacts C ON OM.ClientCode = C.Code 
WHERE 
  OM.CODE = @MatterCode

  END 

GO 


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

go 

CREATE PROCEDURE [dbo].KAAS_GetSAMHeaderDetails (@MatterCode VARCHAR(20)) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].KAAS_GetSAMHeaderDetails	'000001/0000'											 * 
  * Modification History:                                                                                *
  * 2021-03-30 Natarajan S        Created																 *      
   *******************************************************************************************************/
  BEGIN 
  select   
  OM.[Code] as [Code], 
   C.[Code] as [ClientCode], 
   C.[Name] as [ClientName], 
  OM.[Matter] AS [MatterCode], 
  OM.[Description] as [MatterName]

FROM 
  dbo.OpenMattersONLY OM 
  INNER JOIN Contacts C ON OM.ClientCode = C.Code 
WHERE 
  OM.CODE = @MatterCode



  END 

go 


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

CREATE PROCEDURE [dbo].[KAAS_GetSAMInsertBillDesc]
	(
		 @Desc     VARCHAR(MAX)  = '',
		 @Search   CHAR(20)      = '',
		 @Retired  VARCHAR(1)    = ''
	)
AS

/*******************************************************************************************************
* Insert Bill Description							                                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMInsertBillDesc]			  							       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-17    Vinodhkumar M        Created                                                           *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
 *******************************************************************************************************/

BEGIN
  BEGIN TRY
	BEGIN TRANSACTION
			INSERT 
			  INTO [dbo].[BillDescriptions] 
			    (  [BILLDESCRIPTIONS],
				   [SEARCHFIELD],
				   [Retired]
				) 
			VALUES  
			    (  @Desc,
			       @Search,
				   @Retired
				)
    COMMIT TRANSACTION
 END TRY
 BEGIN CATCH
	   DECLARE @ErrorMsg      NVARCHAR(4000), 
  			   @ErrorSeverity INT,
  			   @ErrorState    INT; 
  
		SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
  			   @ErrorSeverity = ERROR_SEVERITY(), 
  			   @ErrorState    = ERROR_STATE()

	RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
  			 IF @@TRANCOUNT > 0  
  				BEGIN
  					ROLLBACK TRANSACTION;
  				END 
 END CATCH
 END
 GO



IF  EXISTS 
(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KAAS_GetSAMJournalBatches]') AND type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[KAAS_GetSAMJournalBatches]
END	
GO
  
 CREATE PROCEDURE [dbo].[KAAS_GetSAMJournalBatches]
AS
/*******************************************************************************************************
* Fetches the journal batch details                                                                    * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMJournalBatches] 										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-05-10    Revathy D        Created                                                               *
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON


SELECT  
	BAH.[BATCHNO]     AS [BatchNo], 
	BAH.[TYPE]        AS [Type],
	BAH.[CODE]        AS [Code],
	BAH.[REF]         AS [Ref],
	BAH.[DATE]        AS [Date],
	BAH.[MATTER]      AS [Matter], 
	BAH.[SUPP]        AS [Supp],
	BAH.[NARR]        AS [Narr],
	BAH.[POSTED]      AS [Posted],
	BAH.[CLIENTAC]    AS [ClientAc],
	BAH.[PERNO]       AS [PerNo],
	BAH.[YEAR]        AS [Year],
	BAH.[ENTRYDATE]   AS [EntryDate],
	BAH.[RECNO]       AS [RecNo],
	BAH.[CHEQUEREQNO] AS [ChequeReqNo]
FROM dbo.BatchH BAH 
WHERE (  
	BAH.[TYPE] = 'J' 
AND BAH.[POSTED] = 'N' 
) 
 
ORDER BY  
	BAH.[POSTED] ASC, 
	BAH.[ENTRYDATE] ASC
SET NOCOUNT OFF

END

GO



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

GO 

CREATE PROCEDURE 
       [dbo].[KAAS_GetSAMMatterLedger] 
	   (
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Date',
			@SortOrder     VARCHAR(100) = 'ASC',
			@MatterCode    VARCHAR(20)
	   ) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].[KAAS_GetSAMMatterLedger]	'KEY001/0001'								 * 
  * Modification History:                                                                                *
  * 2021-03-11 Natarajan S        Created																 *      
  * 2021-03-11 Prabhu V           Modified -- Added BatchH table in left join to verify the type of Batch*      
  * 2021-03-11 Prabhu V           Modified -- Handling Row color from UI instead of fetching value		 *
											  using like search in BD script							 *  
  * 2021-05-19 Prabhu V           Modified -- Fetching ValueO as Outlay for matter Ledger page           * 
  * 2021-07-08 Natarajan S        Modified -- Formatting Added.											 * 
  * 2021-11-25 Vinodhkumar M      Modified -- Balance Query and Cleared Balance Query added	             * 
  * 2022-03-02 Vignesh.M          Modified -- Cleared Date column added	   
  * 2022-07-18 Ghayathri.S.V      Modified -- Modified to implement dynamic sql query to fetch sort
								              and search datas                                           * 
  * 2024-01-31 Revathy.D          Modified -- Included Office and client balance                         * 
   *******************************************************************************************************/
  BEGIN 
	DECLARE		   @sql        NVARCHAR(max)
	DECLARE		   @search	   NVARCHAR(500) = ''
	DECLARE		   @offset	   INT = @PageSize * (@PageNumber -1)
	SET NOCOUNT ON   
	SET	  @sql =  'SELECT		[MTL].[Matter]		AS [Matter], 
								[MTL].[BatchNo]		AS [BatchNo], 
								[MTL].[PRef]		AS [PRef], 
								[MTL].[Date]		AS [Date], 
								[MTL].[Ref]         AS [Ref], 
								[MTL].[Narr]        AS [Narr], 
								[MTL].[ValueD]      AS [ValueD], 
								[MTL].[ValueO]      AS [Outlay], 
								[MTL].[Fee]         AS [Fee], 
								[MTL].[EntryDate]   AS [EntryDate], 
								[MTL].[Client]      AS [Client], 
								[MTL].[ValueCC]     AS [ValueCC], 
								[MTL].[ValueCD]     AS [ValueCD], 
								[MTL].[LRef]        AS [LRef], 
								[MTL].[Billed]      AS [Billed],
								[MAT].[Undertaking] AS [Undertaking],
								[BTH].[Type]        AS [Type],
								[MTL].[ClearedDate]  AS [ClearedDate]
					FROM	    [dbo].[MatterLedger] [MTL]  
			  INNER JOIN        [dbo].[Matters]   [MAT] 
			          ON        [MTL].[Matter]  = [MAT].[Code] 
	           LEFT JOIN        [dbo].[BatchH]    [BTH] 
			          ON        [MTL].[BatchNo] = [BTH].[BatchNo]
	               WHERE        [MTL].[Matter] =  ''' + @MatterCode  + '''' +  
		           'AND         ( 
									[MTL].[Matter]    LIKE' + '''%'  + @SearchString + '%' + '''' +	
									'OR
									[MTL].[Date]      LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[MTL].[Ref]      LIKE ' + '''%'  + @SearchString + '%' + '''' +
									'OR
									[MTL].[Narr]      LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[MTL].[PRef]      LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[MTL].[BatchNo]   LIKE ' + '''%' + @SearchString + '%' + '''' +
								')
		        ORDER BY '      +    @SortColumn + ' '  + @SortOrder + ' ' +
	             'OFFSET '      +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
			 'FETCH NEXT '      +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

      EXEC Sp_executesql @sql

				SELECT      COUNT(*)  'TotalRecord'
				  FROM      [dbo].[MatterLedger] [MTL]  
			INNER JOIN      [dbo].[Matters]   [MAT] 
			        ON      [MTL].[Matter]  = [MAT].[Code] 
	         LEFT JOIN      [dbo].[BatchH]    [BTH] 
			        ON      [MTL].[BatchNo] = [BTH].[BatchNo]
	             WHERE      [MTL].[Matter] =   @MatterCode
			       AND		( 
						      [MTL].[Matter]   LIKE '%' + @SearchString + '%'  
							  OR
							  [MTL].[Date]     LIKE '%' + @SearchString + '%'
							  OR
							  [MTL].[Ref]      LIKE '%' + @SearchString + '%'
							  OR
							  [MTL].[Narr]     LIKE '%' + @SearchString + '%'
							  OR
							  [MTL].[PRef]     LIKE '%' + @SearchString + '%'
							  OR
							  [MTL].[BatchNo]  LIKE '%' + @SearchString + '%'

							) 

		        SELECT      [CLIENTMIN]
				  FROM      [dbo].[OpenMattersOnly]
				 WHERE      [Code] = @MatterCode 

				SELECT      ISNULL(SUM([MTL].[ValueD]),0)	 AS [DebtorBalance],
	                        ISNULL(SUM([MTL].[ValueO]),0)	 AS [OutlayBalance],
	                        ISNULL(SUM([MTL].[ValueC]),0)	 AS [ClientBalance],
	                        ISNULL(SUM([MTL].[ValueCC]),0)	 AS [ClientCurrentBalance],
	                        ISNULL(SUM([MTL].[ValueCD]),0)	 AS [ClientDeptBalance],
							(ISNULL(SUM([MTL].[ValueD]),0) +
							ISNULL(SUM([MTL].[ValueO]),0))	 AS [OfficeBalance]
                  FROM      [dbo].[Matters] [MAT]
       LEFT OUTER JOIN      [dbo].[MatterLedger] AS [MTL]
				    ON      [MAT].Code = MTL.Matter
			  GROUP BY      [Mat].[Code] 
			    HAVING      [MAT].[Code] = @MatterCode

				SELECT		SUM(ISNULL([MTL].[VALUED], 0))  AS [DebtorClearedBalance],                                                                
						    SUM(ISNULL([MTL].[VALUEO], 0))  AS [OutlayClearedBalance],                                                                
						    SUM(ISNULL([MTL].[VALUECC], 0)) AS [ClientCurrentClearedBalance],                                                              
							SUM(ISNULL([MTL].[VALUECD], 0)) AS [ClientDepositClearedBalance]                                                               
				 FROM		[dbo].[matters] AS [MAT]                                                                                   
	  LEFT OUTER JOIN		[dbo].[MatterLedger] AS [MTL]                                                              
				   ON       [MAT].[Code] = [MTL].[MATTER]                                                              
				  AND       ISNULL([MTL].[ClearedDate], [MTL].[DATE]) <= DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)  
		        WHERE       [MAT].[Code] = @MatterCode


	SET NOCOUNT OFF
  END 
  GO

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

go 

CREATE PROCEDURE [dbo].[KAAS_GetSAMMatterLedgerComment] (@MatterCode VARCHAR(20)) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].[KAAS_GetSAMMatterLedgerComment]	'KEY001/0001'							 * 
  * Modification History:                                                                                *
  * 2021-03-11 Natarajan S        Created																 *      
  * 2022-03-07 Vignesh.M          Modified Narrative changed											 *
   *******************************************************************************************************/
  BEGIN 
     IF EXISTS (SELECT TOP 1 1  
				  FROM [dbo].[MatterLedger] AS [MTL]
				 WHERE [MTL].[MATTER] = @MatterCode
				   AND [MTL].[BATCHNO] = 0
				   AND [MTL].[NARR] LIKE 'RESERVE%'
				   AND [MTL].[PREF] = 0)
	 BEGIN
				SELECT [NARR] 
				  FROM [dbo].[MatterLedger] AS [MTL] 
				 WHERE [MTL].[MATTER] = @MatterCode
				   AND [MTL].[BATCHNO] = 0
				   AND [MTL].[NARR] LIKE 'RESERVE%'
				   AND [MTL].[PREF] = 0
			  ORDER BY [MTL].[DATE] DESC
	 END
	 ELSE
	 BEGIN
				SELECT '' [NARR]
	 END
  END 

GO
 
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMMattersWithPossibleOutlayTransfers' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMMattersWithPossibleOutlayTransfers] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_GetSAMMattersWithPossibleOutlayTransfers]
AS 
/*******************************************************************************************************************
*                                                                                                                  *
* Stored Procedure Name : [dbo].[KAAS_GetSAMMattersWithPossibleOutlayTransfers]       						       *
* Description: To Fetch Matters with possible outlay Transfers              		    						   *
*                                                                                                                  *
* Modification History:                                                                                            *
* 2021-09-30    Balamurugan        Created                                                                         *
 *******************************************************************************************************************/
BEGIN
	SET NOCOUNT ON
				  SELECT [MAT].[Code] AS [Matter],
						 [CON].[Name],
						 [MAT].[Description],
						 [MAT].[DebtBal],
						 [MAT].[OutlayBal],
						 [MAT].[ClientBal],
						 0 AS [TransferValue],
						 [MAT].[Branch]
					FROM [dbo].Matters [MAT]  WITH (NOLOCK)
		 LEFT OUTER JOIN [dbo].[Contacts] [CON] WITH (NOLOCK)
					  ON [MAT].[ClientCode] = [CON].[Code]
				   WHERE [MAT].[OutlayBal] < 0 AND
						 [MAT].[OutlayBal] + [MAT].[DebtBal] >= 0 
				ORDER BY [MAT].[Code] ASC
	SET NOCOUNT OFF
END

GO


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

CREATE PROCEDURE 
[dbo].[KAAS_GetSamMemorizeTransList]
AS

/*******************************************************************************************************
* Get Memorize Transaction List                                                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamMemorizeTransList]        							       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-28    Vinodhkumar M        Created                                                           *
* 2021-09-28    Vinodhkumar M        Modified - Added row number                                       *
*******************************************************************************************************/

BEGIN
		SELECT       ROW_NUMBER() OVER(ORDER BY [BAT].[BATCHNO] DESC) AS		[Id],
			         [BAT].[BATCHNO]								  AS		[BatchNo],
					 [BAT].[TYPE]									  AS		[Type], 
					 [BAT].[CODE]									  AS		[Code], 
					 [BAT].[DATE]									  AS		[Date], 
					 [BAT].[MATTER]								      AS		[Matter],
					 [BAT].[SUPP]								      AS		[Supp],
					 [BAT].[NARR]								      AS		[Narr],
					 [BAT].[VALUE]								      AS		[Value]
		FROM		 
					 [dbo].[RBatchH] [BAT]
		ORDER BY    
					 [BAT].[DATE]    ASC,
					 [BAT].[BATCHNO] ASC
END
GO
IF OBJECT_ID(N'KAAS_GetSamMoveMatterList',N'P')IS NOT NULL
DROP PROCEDURE [dbo].[KAAS_GetSamMoveMatterList]
GO

CREATE PROCEDURE [dbo].[KAAS_GetSamMoveMatterList]
	(
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'CODE',
			@SortOrder     VARCHAR(100) = 'ASC'
	)
AS

/*******************************************************************************************************
* Get move matter List                                                                                 * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamMoveMatterList]        								       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-27    Vinodhkumar M        Created   
* 2022-07-22    Ghayathri.S.V		 Modified - To implement dynamic sql query to fetch scroll,sort
									            and search datas                                       *
*******************************************************************************************************/

BEGIN
	SET NOCOUNT ON

	DECLARE @sql       NVARCHAR(max)
	DECLARE @search	NVARCHAR(500) = ''
	DECLARE @offset	INT = @PageSize * (@PageNumber -1)
	    SET	@sql ='SELECT [MAT].CODE	      AS   [Code],
				          [MAT].CLIENTCODE	  AS   [ClientCode],
				          [MAT].DESCRIPTION	  AS   [Description],
				          [MAT].FECODE		  AS	 [FeCode], 
				          [MAT].DEPT		  AS	 [Dept],
				          [MAT].WTYPE		  AS	 [WType],
				          [MAT].BRANCH		  AS	 [Branch],
				          [MAT].COMMENT		  AS	 [Comment], 
				          [MAT].DEBTBAL		  AS   [DebtBal], 
				          [MAT].OUTLAYBAL     AS	 [OutlayBal], 
				          [MAT].CLIENTBAL	  AS	 [ClientBal],
				          [MAT].FILENUM		  AS	 [FileNum],
				          [MAT].THIRDPART	  AS	 [ThirdParty], 
				          [MAT].THPARTSOL	  AS   [ThirdSol], 
				          [MAT].OLDREF	      AS	 [OldRef], 
				          [MAT].PCODE		  AS	 [Pcode], 
				          [MAT].PFECODE		  AS	 [PFeCode], 
				          [MAT].USER1		  AS	 [User1],
				          [MAT].USER2		  AS	 [User2],
				          [MAT].USER3		  AS	 [User3], 
				          [MAT].FILECOLOUR	  AS   [FileColour], 
				          [MAT].OUTFILENO	  AS   [OutFileNo],
				          [MAT].CLOSED		  AS	 [Closed], 
				          [CON].NAME		  AS   [Name], 
				          [CON].FE			  AS   [FE], 
				          [CON].CLIENT		  AS   [Client], 
				          [CON].CLIENTGROUP	  AS	 [ClientGroup], 
				          [CON].OTHERREF	  AS   [OtherRef], 
				          [CON].OPSISREF	  AS	 [OpSisRef], 
				          [CON].CONTACTNO	  AS	 [ContactNo], 
				          [CON].COMPBILLONOFF AS	 [CompBillOnOff], 
				          [CON].TAXTYPE		  AS	 [TaxType]
	                 FROM [dbo].[Matters] [MAT]
		  LEFT OUTER JOIN [dbo].[Contacts] [CON] ON  [MAT].[CLIENTCODE]= [CON].[CODE] 
					WHERE [MAT].CLOSED <> ''Y''' +
					 'AND  ( 
							[MAT].CODE        LIKE' + '''%'  + @SearchString + '%' + '''' +	
							'OR
							[MAT].DESCRIPTION LIKE ' + '''%' + @SearchString + '%' + '''' +
							'OR
							[MAT].FECODE	  LIKE ' + '''%' + @SearchString + '%' + '''' +
							'OR
							[CON].NAME        LIKE ' + '''%' + @SearchString + '%' + '''' +
							'OR
							[MAT].COMMENT	  LIKE ' + '''%' + @SearchString + '%' + '''' +
						 ')
		      ORDER BY '  +  @SortColumn + ' '  + @SortOrder + ' ' +
	           'OFFSET ' +  CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
	       'FETCH NEXT ' +  CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

		   EXEC Sp_executesql @sql

		         SELECT COUNT(*)  'TotalRecord'
				   FROM [dbo].[Matters] [MAT]
		LEFT OUTER JOIN [dbo].[Contacts] [CON] ON  [MAT].[CLIENTCODE]= [CON].[CODE] 
		          WHERE [MAT].CLOSED <> 'Y'
				    AND (
						  [MAT].[CODE]   LIKE '%' + @SearchString + '%'  
						  OR
						  [MAT].[DESCRIPTION]  LIKE '%' + @SearchString + '%'  
						  OR
						  [MAT].[FECODE]   LIKE '%' + @SearchString + '%'  
						  OR
						  [CON].[NAME]   LIKE '%' + @SearchString + '%'  
						  OR
						  [MAT].[COMMENT]   LIKE '%' + @SearchString + '%'  
						 )
  SET NOCOUNT OFF
END
GO



IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMMultipleChequeGridDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMMultipleChequeGridDetails] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_GetSAMMultipleChequeGridDetails]
	(
		@handlerCode VARCHAR(10) = NULL
	)
AS 
/*******************************************************************************************************************
*                                                                                                                  *
* Stored Procedure Name : [dbo].[[AAS_GetSAMMultipleChequeGridDetails]       						               *
* Description: To Get Multiple Cheque Grid Details              		    						               *
*                                                                                                                  *
* Modification History:                                                                                            *
* 2021-08-16    Balamurugan        Created                                                                         *
* 2021-08-19    Balamurugan        Modified -Added UTC Conversion for Date and Entry Date                          *
 *******************************************************************************************************************/
BEGIN
		SELECT [BAT].[BATCHNO]			                                                       AS [BatchNo],
			   [BAT].[TYPE]			                                                           AS [Type],
			   [BAT].[CODE]			                                                           AS [Code],
			   [BAT].[REF]				                                                       AS [Ref],
			   [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[Date], @handlerCode)      AS [Date],
			   [BAT].[MATTER]			                                                       AS [Matter],
			   [BAT].[SUBTOT]			                                                       AS [SubTotal],
			   [BAT].[SUPP]			                                                           AS [Supp],
			   [BAT].[NARR]			                                                           AS [Narr],
			   [BAT].[VALUE]			                                                       AS [Value],
			   [BAT].[POSTED]			                                                       AS [Posted],
			   [BAT].[PERNO]			                                                       AS [PerNo],
			   [BAT].[YEAR]			                                                           AS [Year],
			   [dbo].[KEYHM_FNConvertUTCDateToTargetTimeZone]([BAT].[ENTRYDATE], @handlerCode) AS [EntryDate],
			   [BAT].[RECNO]			                                                       AS [RecNo],
			   [BAT].[USERCODE]		                                                           AS [UserCode],
			   [BAT].[CLIENTBANK]		                                                       AS [ClientBank],
			   [BAT].[CHEQUEREQNO]		                                                       AS [ChequeReqNo]
		  FROM [dbo].[BatchH] [BAT] 
		 WHERE [BAT].[TYPE] = 'M'
END

GO

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

CREATE PROCEDURE 
	   [dbo].[KAAS_GetSAMPendingClientACDetails] 
	   (
			@MatterCode VARCHAR(20)
	   ) 
AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSAMPendingClientACDetails]   '000001/0000'                                                         *
* Description: Used to list the matter ledger                                                          *					  
* Modification History:                                                                                *
* 2021-04-09   Natarajan S        Created															   *      
* 2021-04-09   Arun V             Implemented coding standards                                         *      
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON   
	SELECT 
		[BAD].[KEYID]	AS [PRef],
		[BAD].[REF]     AS [Ref],
		[BAD].[DATE]    AS [Date],
		[BAD].[NARR]    AS [Narr],
		[BAD].[VALUE]   AS [ValueC],
		[BAD].[BATCHNO] AS [BatchNo]
	FROM		
		[dbo].[BatchDetails] [BAD] 
	    LEFT OUTER JOIN [dbo].[BatchH] [BAH] 
	                 ON [BAD].[BATCHNO] = [BAH].[BATCHNO] 
	WHERE	
		([BAD].[MATTER] = @MatterCode  AND 
		 [BAH].[POSTED] = 'N'          AND 
			( [BAD].[OUTLAY]     = 'C'  OR  
			  [BAD].[TYPE]       = 'R'  AND  
			  [BAH].[THIRDPARTY] = 'Y'  OR  
			  [BAD].[TYPE]       = 'T'  AND  
			  [BAH].[CLIENTAC]   = 'Y') 
            )  
	ORDER BY 
		[BAD].[MATTER] ASC, 
		[BAD].[KEYID] ASC

	SELECT 
		SUM([VALUECC]) AS [ClientAccountTotal] 
	FROM 
		[dbo].[MatterLedger] 
	WHERE 
		[MATTER] = @MatterCode

 SET NOCOUNT OFF
END 

GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMPostedBatches' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMPostedBatches] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_GetSAMPostedBatches] 
		(
			@PageNumber    INT,
			@PageSize	   INT,
			@Type          VARCHAR(10) = '',
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'BATCHNO',
			@SortOrder     VARCHAR(100) = 'ASC'
	    )
AS
/*******************************************************************************************************
* Fetches the posted batches                                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMPostedBatches]   										   *
*                                                                                                      *
* Modification History:                                                                                *
* 19 Oct  2021    Ghayathri.S.V        Created                                                         *
* 06 Nov  2023    Ghayathri.S.V        Modified to add date column in search parameter                 *
* 25 Mar  2024    Vignesh M            Modified - Date filter is added				                   *
*******************************************************************************************************/

BEGIN
 SET NOCOUNT ON
	
 DECLARE @sql				NVARCHAR(max)
 DECLARE @SelectClause      NVARCHAR(max)
 DECLARE @ConditionalClause NVARCHAR(max)
 DECLARE @SearchText		NVARCHAR(max)
 DECLARE @OrderByClause     NVARCHAR(max)
 DECLARE @TotalRecord       NVARCHAR(max)
 DECLARE @offset	        INT = @PageSize * (@PageNumber -1)

 DECLARE @isDateFilter      NVARCHAR(max) = '0'
 DECLARE @Day               NVARCHAR(max) = '00'
 DECLARE @Month             NVARCHAR(max) = '00'
 DECLARE @Year              NVARCHAR(max) = '1900'
 DECLARE @DateFilter        NVARCHAR(max) = ''
 SET @DateFilter = [dbo].[KAAS_FN_DateFilter](@SearchString)
 IF @DateFilter != ''
 BEGIN
	SET @Day   = SUBSTRING(@DateFilter,1,2)
	SET @Month = SUBSTRING(@DateFilter,4,2)
	SET @Year  = SUBSTRING(@DateFilter,7,4)
	IF @Day != '00' OR @Month != '00' OR @Year != '1900'
	BEGIN
		SET @isDateFilter = '1'
	END
 END

	SET @SelectClause = 'SELECT 
					CASE WHEN [Type] = ''P''
							THEN ''Payment''
						WHEN [Type] = ''B''
							THEN ''Bill''
						WHEN [Type] = ''T''
							THEN ''Transfer''
						WHEN [Type] = ''I''
							THEN ''Invoice'' 
						WHEN [Type] = ''R''
							THEN ''Receipt''
						WHEN [Type] = ''J''
							THEN ''Journal'' ELSE '''' 
						END AS  Type,
						[BatchNo],
						[Pref],
						[Ref],
						[Date],
						[Value],
						[Matter],
						[Code],
						[Supp],
						[Narr],
						[Fee]
			    FROM    [dbo].[BatchH]'		


	IF(@Type = '')
		SET @ConditionalClause = N'
			WHERE   [POSTED] = ''Y'''
	ELSE
		SET @ConditionalClause =  N'
			WHERE   [POSTED] = ''Y''
		    AND [Type] = @Type';
	SET @SearchText = N' '

	IF @isDateFilter != '0'
	BEGIN

		IF @Day != '00'
		BEGIN
			SET @SearchText += N' 
						AND 
						( 
								DAY([Date])	      =  ' + ''+ @Day +'' +
					  ')'
		END
		IF @Month != '00'
		BEGIN
			SET @SearchText += N' 
						AND 
						( 
								MONTH([Date])	  =  ' + ''+ @Month +'' +
					  ')'
		END
		IF @Year != '1900'
		BEGIN
			SET @SearchText += N' 
						AND 
						( 
								YEAR([Date])	  =  ' + ''+ @Year +'' +
					  ')'
		END

	END
	ELSE
	BEGIN
		
		SET @SearchText += N' 
					AND 
					( 
							[BatchNo] LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[Date]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[PREF]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[REF]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[VALUE]   LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[MATTER]  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[CODE]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[SUPP]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[NARR]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
							'OR
							[FEE]	  LIKE' + '''%'  + @SearchString + '%' + '''' +
				  ')'
	END

    SET @OrderByClause  = N' ORDER BY ' + CAST(@SortColumn AS VARCHAR(100)) + ' ' + CAST(@SortOrder AS VARCHAR(100)) +'
	        OFFSET @offset   ROWS
	    FETCH NEXT @PageSize ROWS ONLY;'

	SET @TotalRecord = N'
		SELECT COUNT(*)  ''TotalRecord''
			   FROM [dbo].[BatchH] ' + @ConditionalClause + @SearchText

	SET @sql = @SelectClause + @ConditionalClause + @SearchText + @OrderByClause + @TotalRecord
			EXEC Sp_executesql @sql,
				N' @Type VARCHAR(10) ,
				@SearchString VARCHAR(500),
				@SortColumn VARCHAR(100),
				@SortOrder VARCHAR(100),
				@offset INT,
				@PageSize INT',
				@Type = @Type,
				@SearchString = @SearchString,
				@SortColumn = @SortColumn,
				@SortOrder = @SortOrder,
				@offset = @offset,
				@PageSize = @PageSize

 SET NOCOUNT OFF
END

GO
IF OBJECT_ID(N'KAAS_GetSAMPurchaseList',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_GetSAMPurchaseList]
GO
CREATE PROCEDURE 
	 [dbo].[KAAS_GetSAMPurchaseList]
	 (@Type varchar(4) = '',
	  @Handler VARCHAR(10) = NULL)
AS 
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMPurchaseList]       									   *
* Description: To Get list based Type			    												   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-07-28    Vinodhkumar M        Created                                                           *
* 2021-08-09    Vinodhkumar M        Type parameter is added                                           *
* 2021-08-11    Vinodhkumar M        new column is added                                               *
* 2021-08-11    Vinodhkumar M        Modified : change time zone for date,Entry date                   *
 *******************************************************************************************************/
BEGIN
		SELECT    [BAT].[BATCHNO]		AS [BatchNo],
			      [BAT].[TYPE]			AS [Type],
			      [BAT].[CODE]			AS [Code],
			      [BAT].[REF]			AS [Ref],
			      [dbo].KEYHM_FNConvertUTCDateToTargetTimeZone([BAT].[DATE], @Handler)  AS [Date], 
			      [BAT].[MATTER]		AS [Matter],
				  [BAT].[SUBTOT]		AS [SubTotal],
			      [BAT].[SUPP]			AS [Supp],
			      [BAT].[NARR]			AS [Narr],
			      [BAT].[VALUE]			AS [Value],
			      [BAT].[POSTED]		AS [Posted],
			      [BAT].[PERNO]			AS [PerNo],
				  [BAT].[YEAR]			AS [Year],
				  [BAT].[ENTRYDATE]		AS [EntryDate],
				  [dbo].KEYHM_FNConvertUTCDateToTargetTimeZone([BAT].[ENTRYDATE], @Handler)  AS [EntryDate], 
				  [BAT].[RECNO]			AS [RecNo],
				  [BAT].[USERCODE]      AS [UserCode],
				  [BAT].[CLIENTBANK]    AS [ClientBank],
				  [BAT].[CHEQUEREQNO]	As [ChequeReqNo]
		FROM 
				 [dbo].[BatchH] [BAT] 
		WHERE 
				([BAT].[TYPE] = @Type AND 
				 [BAT].[POSTED] = 'N')  
		ORDER BY  
				[BAT].[POSTED] ASC,
				[BAT].[ENTRYDATE] ASC
END
GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMRequestedTransferCost' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMRequestedTransferCost] 
  END 
GO 

CREATE PROCEDURE [dbo].[KAAS_GetSAMRequestedTransferCost]
      (
			@Mode      VARCHAR(10)  = 'VIEW',
			@RecordId  DECIMAL(9)
      ) 
AS
/*******************************************************************************************************
* Fetches the Waiting Costs Transfer Details                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMRequestedTransferCost]   							       *
*                                                                                                      *
* Modification History:                                                                                *
* 16 Mar  2022    Vignesh M          Created
* 18 Oct  2022    Ghayathri.S.V      Modified - Handled Delete logic with modes,
												TCL Statements   and formatting.                       *                                     
 *******************************************************************************************************/
BEGIN
SET NOCOUNT ON
	 BEGIN TRY
        BEGIN TRAN
			IF( @Mode = 'VIEW' )
				BEGIN
					 SELECT [CTG].[Ref], 
							[CTG].[Date], 
							[CTG].[Matter], 
							[CTG].[Value], 
							[CTG].[RecordId], 
							[MTR].[Code], 
							[MTR].[ClientCode], 
							[MTR].[Description], 
							[MTR].[FeCode], 
							[MTR].[Dept], 
							[MTR].[WType], 
							[MTR].[Branch], 
							[MTR].[FileNum], 
							[MTR].[ThirdPart], 
							[MTR].[ThpartSol], 
							[MTR].[OldRef], 
							[MTR].[PCode], 
							[MTR].[PfeCode], 
							[MTR].[User1], 
							[MTR].[User2], 
							[MTR].[User3], 
							[MTR].[FileColour], 
							[MTR].[OutFileNo], 
							[MTR].[Closed], 
							[CON].[Name], 
							[CON].[Fe], 
							[CON].[Client], 
							[CON].[ClientGroup], 
							[CON].[OtherRef], 
							[CON].[OpsisRef], 
							[CON].[ContactNo], 
							[CON].[CompBillOnOff], 
							[CON].[TaxType]
					 FROM   [dbo].[CostTransGathering] AS [CTG] 
          LEFT OUTER JOIN   [dbo].[Matters]            AS [MTR] ON  [CTG].MATTER     = [MTR].CODE 
          LEFT OUTER JOIN   [dbo].[contacts]           AS [CON] ON  [MTR].CLIENTCODE = [CON].CODE
	             ORDER BY   [CTG].MATTER   ASC, [CTG].RECORDID ASC
		        END

	        ELSE IF (@Mode = 'DELETE')
				BEGIN
					DELETE FROM  [dbo].[CostTransGathering]
					WHERE  RECORDID = @RecordId
				END
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	END CATCH
SET NOCOUNT OFF
END
	
GO  


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

CREATE PROCEDURE 
[dbo].[KAAS_GetSamSelectContactList]
AS

/*******************************************************************************************************
* Get move matter List                                                                                 * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamSelectContactList]        							       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-27    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/

BEGIN
		SELECT		[CONT].[CODE]			AS		[Code],
					[CONT].[Name]			AS		[Name], 
					[CONT].[Address]		AS		[Address], 
					[CONT].PRINCIPAL		AS		[Principal], 
					[CONT].FE				AS		[FE], 
					[CONT].CLIENT			AS		[Client],
					[CONT].CLIENTGROUP		AS		[ClientGroup], 
					[CONT].OTHERREF			AS		[OtherRef],
					[CONT].OPSISREF			AS		[OpSisRef], 
					[CONT].CONTACTNO		AS		[ContactNo],
					[CONT].COMPBILLONOFF	AS		[CompBillOnOff],
					[CONT].TAXTYPE			AS		[TaxType]
		FROM		
					[dbo].[contacts] [CONT]
		ORDER BY	
					[CONT].CODE ASC
END
GO



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

CREATE PROCEDURE 
	[dbo].[KAAS_GetSAMSelectedBillDetails]
	(@KeyId   INT = NULL,
	 @DraftNo INT = NULL)
AS

/*******************************************************************************************************
* Get bill details based on keyId					                                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMSelectedBillDetails]			  	     			       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-17    Vinodhkumar M        Created                                                           *
 *******************************************************************************************************/

BEGIN
			SELECT [MATTER]				AS [Matter],
				   [DRAFTNO]			AS [DraftNo],
				   [BILLNO]				AS [BillNo],
				   [TYPE]				AS [Type],
				   [FEEEARNER]			AS [FeeEarner],
				   [NOMINAL]			AS [Nominal],
				   [NARRATIVE]			AS [Narrative],
				   [NET]				AS [Net],
				   [VATCODE]			AS [VatCode],
				   [VATRATE]			AS [VatRate],
				   [VATVALUE]			AS [VatValue],
				   [LINENO]				AS [LineNo],
				   [KEYID]				AS [KeyId],
				   [OVERRIDDENVAT]		AS [OverriddenVat],
				   [PREBILLEDOUTLAY]	AS [PreBillingOutlay]
			FROM	
				   [dbo].[BillDetails]
			WHERE 
				   [KEYID]   = @KeyId
			AND    [DRAFTNO] = @DraftNo
 END
 GO



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

CREATE PROCEDURE 
	[dbo].[KAAS_GetSAMSelectedMatterWithContact]
	(@Code VARCHAR(50) ='')
AS

/*******************************************************************************************************
* Get Matter and Contacts details based on Matter Code                                                 * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMSelectedMatterWithContact]        	     			       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-16    Vinodhkumar M        Created                                                           *
 *******************************************************************************************************/

BEGIN
		SELECT    
				  [MAT].[CODE]				AS	[Code],
			      [MAT].[CLIENTCODE]		AS	[ClientCode],
			      [MAT].[MATTER]			AS	[Matter],
			      [MAT].[DESCRIPTION]		AS	[Description],
			      [MAT].[DEBTBAL]			AS	[DebtBal],
			      [MAT].[OUTLAYBAL]			AS	[OutlayBal],
			      [MAT].[CLIENTBAL]			AS	[ClientBal],
			      [MAT].[CHARGEBAL]			AS	[ChargeBal],
				  [dbo].[ky_TimeFromMinutes]([MAT].[TimeBal]) AS [TimeBal],
				  [CON].[NAME]				AS	[Name],
				  [CON].[ADDRESS]			AS	[Address]
		FROM 
				  [dbo].[MATTERS] [MAT] 
	   INNER JOIN 
				  [dbo].[CONTACTS] [CON] ON [CON].[CODE] = [MAT].[CLIENTCODE]
	   WHERE	  
				  [MAT].[CODE] = @Code
 END
 GO



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

AS

/*******************************************************************************************************
* Fetches the System Options Dropdown List                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSystemOptionsDetails]      							       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-08-02    Balamurugan.C        Created                                                           *
* 2021-09-07    Balamurugan.C        Updated- Include Allow Forward Posting Flag                       *
* 2021-09-20    Balamurugan.C        Modified- Removed Year End Date from control table and used       *
									           srettings table year end date                           *
* 2021-10-13    Vinodhkumar.M        Updated- Include EFT_EFTDebt				                       *
* 2021-11-18    Vinodhkumar.M        Updated- Include IEConvert,EICONVERT,BaseCurrency                 *
* 2022-03-23    Vinodhkumar.M        Updated- Include Code configuration Labels name				   *
* 2022-03-24    Vinodhkumar.M        Updated- Include Request File configuration Config				   *
* 2022-04-06    Vinodhkumar.M        Updated- Handled code configuration  empty values    			   *
* 2022-04-07    Vinodhkumar.M        Updated- Handled IS NULL forcode configuration null     	       *
* 2022-11-24    Ghayathri.S.V        Updated- Included code config columns to fetchfrom settings table *
* 2024-01-23    Ghayathri.S.V        Updated- Included DefaultPrebilledOutlay columns to 
										      fetchfrom settings table                                 *
* 2024-02-28    Sadiq				 Updated- Added Azure Container dynamic values					   *
* 2024-03-25    Ghayathri.S.V		 Updated- Added EFT Default values					   			   *
 *******************************************************************************************************/

BEGIN

	SET NOCOUNT ON

		SELECT 
			  RTRIM([Name])				                       AS [Name],
			  RTRIM([Debtors])		                           AS [DebtorsControlAc],
			  RTRIM([Creditor])		                           AS [CreditorControlAc],
			  RTRIM([VatNo])			                       AS [VatNo],
			  RTRIM([Outlay])			                       AS [OutlayControlAc],
			  RTRIM([Vat])				                       AS [VatAc],
			  RTRIM([Pl])				                       AS [ProfitLossAc],
			  RTRIM([Client])		                           AS [ClientLedgerControl],
			  RTRIM([FeesWriteOff])		                       AS [FeesWriteOffAc],
			  RTRIM([OutlayWriteOff])	                       AS [OutlayWriteOffAc],
			  RTRIM([BillsWriteOff])	                       AS [BillsWriteOffAc],
			  RTRIM([DefaultOfficeAc])	                       AS [DefaultOfficeAc],
			  RTRIM([DefaultClientAc])	                       AS [DefaultClientAc],
			  RTRIM([DefaultClientDep])	                       AS [DefaultClientDepositAc],
			  RTRIM([MiscOutlay])		                       AS [MiscOutlay],
			  RTRIM([PettyCash])		                       AS [DefaultPettyCash],
			  RTRIM([withTax])			                       AS [WithHoldingTax],
			  [Year]				                           AS [Year],
			  [CurPer]				                           AS [CurrentPeriod],
			  [OutlayBudget]		                           AS [StdOutlayBudget],
			  [LastBill]			                           AS [LastBillNo], 
			  RTRIM([VatExclude])		                       AS [VatExclusionCode],
			  RTRIM([DefaultVat])		                       AS [DefaultVat],
			  RTRIM([FeeExclude])		                       AS [FeeExclusionCode],
			  RTRIM([MiscFE])			                       AS [DefaultMiscOutlayFeeEarner],
			  RTRIM([EnableFNL])		                       AS [EnableFNL],
			  [EnableCDB]				                       AS [EnableClientDB],
			  [UK]						                       AS [UK],
			  [EnableDW]				                       AS [EnableDeedsWills],
			  [YearEndCompleted]		                       AS [YearEndCompleted],
			  [EnableFM]				                       AS [EnableFM],
			  [UseOutlayType]			                       AS [UseOutlayType],
			  [PendingOutlay]			                       AS [PendingOutlay],
			  [RecInstalled]                                   AS [EnableBankRec],
			  [Indicator18]				                       AS [BillPrinting],
			  [Indicator19]				                       AS [UniqueMatterNumbering],
			  [Indicator20]				                       AS [IntrestCalculator],
			  [Indicator22]				                       AS [UseBranches],
			  [Indicator23]				                       AS [TaggedBatches],
			  [Indicator24]				                       AS [Indicator24],
			  [Indicator25]				                       AS [Indicator25],
			  [Indicator26]				                       AS [Indicator26],
			  [Indicator27]				                       AS [Indicator27],
			  [Indicator28]				                       AS [Indicator28],
			  [Indicator29]				                       AS [Indicator29],
			  [Indicator30]				                       AS [Indicator30],
			  [WordPerfect]				                       AS [WordPerfect],
			  [DemoExpire]				                       AS [DemoExpire],
			  [MaxNumberofMatters]                             AS [MaxMatter],
			  [OpSisLink]                                      AS [CaseMgrLink],
			  [TimeCosting]                                    AS [TimeCostingInstalled],
			  [ForceFE]					                       AS [ForceFeeEarnerCode],
			  [LabelPrinter]			                       AS [LabelPrinter],
			  [FeesRepSeq]				                       AS [FeesReportingSeq],
			  [NoBar]					                       AS [OverdrawnClientAc],
			  RTRIM([Solicitor])	                           AS [SolicitorCategory],
			  RTRIM([OthParty])                                AS [OtherPartyCategory],
			  RTRIM([SupplierCategory])                        AS [SupplierCategory],
			  RTRIM([DefaultCategory])                         AS [SystemCategoryType],
			  [AutoNumber]                                     AS [AutoNumberClients],
			  [AutoAlphaClientNumbering]                       AS [AutoAlphaClientNumbering],
			  [ThirdPartyLimit]                                AS [ThirdPartyLimit],
			  [EiConvert]                                      AS [ConversionRate],
			  [DateFutValidation]                              AS [DateFutureValidation],
			  [DatePastValidation]                             AS [DatePastValidation],
			  RTRIM([USerPrompt1])		                       AS [PromptRef1],
			  RTRIM([USerPrompt2])		                       AS [PromptRef2],
			  RTRIM([USerPrompt3])		                       AS [PromptRef3],
			  [NextFile]                                       AS [NextFile],
			  [ClosedFileNo]			                       AS [ClosedFileNumber],
			  RTRIM([ChequePrinting])                          AS [ChequeType],
			  [EnableCP]                                       AS [EnableChequePrinting],
			  [IECONVERT]                                      AS [CurrencyConvertValue],
			  [EICONVERT]									   AS [EIConvertValue],
			  [BaseCurrency]								   AS [BaseCurrency],
			  [dbo].[KAAS_FN_GetDateFromClarion]([PeriodEnd])  AS [NextPeriodEnd]
		 FROM [dbo].[Control]

	   SELECT
			  MAX(CASE WHEN [STI].[KeyName] = 'TimeBarred' THEN OutputValue END)                                   AS [TimeBarred],
			  MAX(CASE WHEN [STI].[KeyName] = 'SupplierRemittance_On' THEN OutputValue END)                        AS [SupplierRemittanceOn],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFTDefaultON' THEN OutputValue END)                                 AS [EFTDefaultON],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFTEmailToSend' THEN OutputValue END)                               AS [EFTEmailToSend],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFTTransactionLimit' THEN OutputValue END)                          AS [EFTTransactionLimit],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFTNoOfTransactionLimit' THEN OutputValue END)                      AS [EFTNoOfTransactionLimit],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFTEmailSubject' THEN OutputValue END)                              AS [EFTEmailSubject],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFTEmailMessage' THEN OutputValue END)                              AS [EFTEmailMessage],
			  MAX(CASE WHEN [STI].[KeyName] = 'DefaultPrebilledOutlay' THEN OutputValue END)                       AS [DefaultPrebilledOutlay],
			  MAX(CASE WHEN [STI].[KeyName] = 'MatterOutlayBudgetCheckON' THEN OutputValue END)                    AS [MatterOutlayBudgetCheckON],
			  MAX(CASE WHEN [STI].[KeyName] = 'CASE_LabelNo' THEN RTRIM(OutputValue) END)                          AS [CaseLabelNo],
			  MAX(CASE WHEN [STI].[KeyName] = 'InvoiceApprover' THEN RTRIM(OutputValue) END)                       AS [InvoiceApprover],
			  MAX(CASE WHEN [STI].[KeyName] = 'ChequeApprover' THEN RTRIM(OutputValue) END)                        AS [ChequeApprover],
			  MAX(CASE WHEN [STI].[KeyName] = 'NotifyReleasedInv' THEN OutputValue END)                            AS [NotifyReleasedInv],
			  MAX(CASE WHEN [STI].[KeyName] = 'NotifyApprovedInv' THEN OutputValue END)                            AS [NotifyApprovedInv],
			  MAX(CASE WHEN [STI].[KeyName] = 'NotifyReleasedChq' THEN OutputValue END)                            AS [NotifyReleasedChq],
			  MAX(CASE WHEN [STI].[KeyName] = 'NotifyApprovedChq' THEN OutputValue END)                            AS [NotifyApprovedChq],
			  MAX(CASE WHEN [STI].[KeyName] = 'EMailServer' THEN OutputValue END)                                  AS [SMTPMailServer],
			  MAX(CASE WHEN [STI].[KeyName] = 'Money Laundering_MoneyLaunderingCheck' THEN OutputValue END)        AS [MoneyLaunderingCheck],
			  MAX(CASE WHEN [STI].[KeyName] = 'Money Laundering_Dept' THEN RTRIM(OutputValue) END)                 AS [MoneyLaunderingDept],
			  MAX(CASE WHEN [STI].[KeyName] = 'Money Laundering_FeeEarner' THEN RTRIM(OutputValue) END)            AS [MoneyLaunderingFeeEarner],
			  MAX(CASE WHEN [STI].[KeyName] = 'Money Laundering_WorkType' THEN RTRIM(OutputValue) END)             AS [MoneyLaunderingWorkType],
			  MAX(CASE WHEN [STI].[KeyName] = 'Options_Conversion' THEN RTRIM(OutputValue) END)                    AS [ShowLedgerButton],
			  MAX(CASE WHEN [STI].[KeyName] = 'CompositeBilling' THEN RTRIM(OutputValue) END)                      AS [CompositeBilling],
			  MAX(CASE WHEN [STI].[KeyName] = 'AllowFwPostingJournals' THEN RTRIM(OutputValue) END)                AS [AllowFwPostingJournals],
			  MAX(CASE WHEN [STI].[KeyName] = 'YearEndDate' THEN TRY_PARSE(OutputValue as date USING 'AR-LB') END) AS [YearEndDate],
			  MAX(CASE WHEN [STI].[KeyName] = 'EFT_EFTDebt' THEN RTRIM(OutputValue) END)						   AS [EFTDebt],
			  MAX(CASE WHEN [STI].[KeyName] = 'RequestFileExpiryTime' THEN RTRIM(OutputValue) END)				   AS [RequestFileExpiryTime],
			  MAX(CASE WHEN [STI].[KeyName] = 'MaxClCode' THEN RTRIM(OutputValue) END)				               AS [MaxClCode],
			  MAX(CASE WHEN [STI].[KeyName] = 'ManualClientCode' THEN RTRIM(OutputValue) END)					   AS [ManualClientCode],
			  MAX(CASE WHEN [STI].[KeyName] = 'MaxMatNum' THEN RTRIM(OutputValue) END)				               AS [MaxMatNum],
			  MAX(CASE WHEN [STI].[KeyName] = 'ShowMatterCode' THEN RTRIM(OutputValue) END)				           AS [ShowMatterCode],
			  MAX(CASE WHEN [STI].[KeyName] = 'AutoNumberIfBlank' THEN RTRIM(OutputValue) END)				       AS [AutoNumberIfBlank],

			  --Code configuration Labels name
			  ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'ClientLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Client' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Client')				AS [ClientLabel],

			 ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'ContactLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Contact' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Contact')				AS [ContactLabel],

			 ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'MatterLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Matter' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Matter')				AS [MatterLabel],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'CaseLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Case' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Case')					AS [CaseLabel],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'CaseMatterLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Case Or Matter' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Case Or Matter')		AS [CaseMatterLabel],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'FeeEarnerLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Fee Earner' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Fee Earner')			AS [FeeEarnerLabel],
					   
			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'PartnerLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Partner' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Partner')				AS [PartnerLabel],
					   
			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'AssociateLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Associate' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Associate')				AS [AssociateLabel],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'BranchLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Branch' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),	'Branch')				AS [BranchLabel],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'PostalCodeLabel' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Postal Code' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Postal Code' )			AS [PostalCodeLabel],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'AzureBlobStorageClientFolder' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Azure Blob Storage Client Folder' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Azure Blob Storage Client Folder' )			AS [AzureBlobStorageClientFolder],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'AzureBlobStorageClientVersionsFolder' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Azure Blob Storage Client Versions Folder' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Azure Blob Storage Client Versions Folder' )			AS [AzureBlobStorageClientVersionsFolder],

			ISNULL(MAX(CASE WHEN [STI].[KeyName] = 'AzureBlobStorageTemplatesFolder' THEN 
				  CASE WHEN RTRIM(OutputValue) ='' THEN 'Azure Blob Storage Templates Folder' 
				       WHEN RTRIM(OutputValue) !='' THEN  RTRIM(OutputValue)  END END),'Azure Blob Storage Templates Folder' )			AS [AzureBlobStorageTemplatesFolder]


		 FROM [dbo].[Settings] STI 
  CROSS APPLY
            (
	   VALUES ([KeyValue])
            ) 
			   CPV(OutputValue)
	    WHERE [STI].[KeyName] 
		   IN (
		        'TimeBarred',
				'SupplierRemittance_On',
				'EFTDefaultON',
				'EFTEmailToSend',
				'EFTTransactionLimit',
				'EFTNoOfTransactionLimit',
				'EFTEmailSubject',
				'EFTEmailMessage',
				'DefaultPrebilledOutlay',
				'MatterOutlayBudgetCheckON',
				'CASE_LabelNo',
				'InvoiceApprover',
				'ChequeApprover',
				'NotifyReleasedInv',
				'NotifyApprovedInv',
				'NotifyReleasedChq',
				'NotifyApprovedChq',
				'Money Laundering_MoneyLaunderingCheck',
				'Money Laundering_Dept',
				'Money Laundering_FeeEarner',
				'Money Laundering_WorkType',
				'EMailServer',
				'Options_Conversion',
				'CompositeBilling',
				'AllowFwPostingJournals',
				'YearEndDate',
				'EFT_EFTDebt',
				'RequestFileExpiryTime',
				'MaxClCode',
				'ManualClientCode',
				'MaxMatNum',
				'ShowMatterCode',
				'AutoNumberIfBlank',


				'ClientLabel',
				'ContactLabel',
				'MatterLabel',
				'CaseLabel',
				'CaseMatterLabel',
				'FeeEarnerLabel',
				'PartnerLabel',
				'AssociateLabel',
				'BranchLabel',
				'PostalCodeLabel',
				'AzureBlobStorageClientFolder',
				'AzureBlobStorageClientVersionsFolder',
				'AzureBlobStorageTemplatesFolder'

			  )



	SET NOCOUNT OFF

END




GO

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

AS

/*******************************************************************************************************
* Fetches the System Options Dropdown List                                                             * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMSystemOptionsDropDownList]      						   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-08-01    Balamurugan.C        Created                                                           *
 *******************************************************************************************************/

BEGIN

	SET NOCOUNT ON

				SELECT 
					   [Code],
					   [Desc],
					   [Type],
					   [Retired]
				  FROM [dbo].[Nominal] 
			  ORDER BY [Code] ASC

				SELECT 
					   [Code],
					   [Name],
					   [Nominal],
					   [Retired]
				  FROM [dbo].[FeeEarnerCodes] 
			  ORDER BY [Code] ASC

				SELECT 
					   [Code],
					   [Rate]
				  FROM [dbo].[VATCodes] 
			  ORDER BY [Code] ASC

				SELECT 
					   [Code],
					   [Desc],
					   [Pb] 
				  FROM [dbo].[NominalReportSeq]
				 WHERE [Pb] = ' '  
			  ORDER BY [Pb] DESC,
					   [Code] DESC

				SELECT  
					   RTRIM([CatType])      AS [CatType],
					   RTRIM([Code])         AS [Code],
					   RTRIM([Desc$])        AS [Description],
					   RTRIM([CategoryType]) AS [CategoryType]
				  FROM [dbo].[Category] 
       LEFT OUTER JOIN [dbo].[CategoryType]
				    ON [CatType]=[CategoryType]
				 WHERE [CatType]= (SELECT [DefaultCategory] FROM [dbo].[control])
			  ORDER BY [CatType] DESC,
					   [Code] DESC

				SELECT 
		               RTRIM([CategoryType]) AS [CategoryType],
		               RTRIM([Description])  AS [Description] 
		          FROM [dbo].[CategoryType]
			  ORDER BY [CategoryType] ASC

				SELECT 
					   RTRIM([Code])         AS [Code],
					   RTRIM([Description])  AS [Description]
				  FROM [dbo].[Departments]
				 WHERE ISNULL([Retired],'') <> 'Y'  
			  ORDER BY [Code] ASC

				SELECT 
					   RTRIM([Code])         AS [Code],
					   RTRIM([Description])  AS [Description]
				  FROM [dbo].[WorkTypes]
				 WHERE ISNULL([Retired],'') <> 'Y'   
			  ORDER BY [Code] ASC

	SET NOCOUNT OFF


END

GO

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


CREATE PROCEDURE [dbo].[KAAS_GetSAMUndertakingBaseDetails](
		         @MatterCode VARCHAR(20),
		         @FECode VARCHAR(10),
		         @Handler VARCHAR(10)
	             )         
              AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSAMUndertakingBaseDetails] '000001/0000','ADM','ADM'                                  *
* Description: Get basic undertaking details to insert undertakings                                    *					  
* Modification History:                                                                                *
* 2021-04-10   Natarajan S        Created															   *      
*******************************************************************************************************/
BEGIN 
  SET NOCOUNT ON   

		  SELECT [RecordId]                                                      AS [RecordId],
			     [MATTER]                                                        AS [MATTER],
			     [SEQ]                                                           AS [SEQ],
			     [DISCHARGEDATE]                                                 AS [DischargeDate],
			     [TYPE]                                                          AS [TYPE],
			     [DESCRIPTION]                                                   AS [DESCRIPTION],
			     [WHO]                                                           AS [WHO],
			     [ACTIONID]                                                      AS [ACTIONID],
			     [GIVENORRECEIVED]                                               AS [GivenOrReceived],
			     [NOTIFIED]                                                      AS [Notified],
			     [DISCHARGEDESCRIPTION]                                          AS [DischargeDescription],
			     [DISCHARGEDBY]                                                  AS [DischargedBy],
			     [DEALINGNUMBER]                                                 AS [DealingNumber],
			     [NOTES]                                                         AS [Notes],
			     [COMMERCIALORNON]                                               AS [CommercialOrNon],
			     [STATUS]                                                        AS [STATUS],
			     [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([DATE],@Handler)    AS [Date],
			     [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([UNDDATE],@Handler) AS [UndDate],
			     [VALUE]                                                         AS [VALUE],
			     [UNDVALUE]                                                      AS [UndValue],
			     [AUTHORISEDBYFE]                                                AS [AUTHORISEDBYFE],
			     [HANDLER]                                                       AS [Handler],
			     [UNDERTAKINGTO]                                                 AS [UndertakingTo],
			     [CASECONTACT]                                                   AS [CaseContact],
			     [ENTRYDATE]                                                     AS [EntryDate],
			     [CATEGORY]                                                      AS [Category],
			     [ISCONDITIONAL]                                                 AS [IsConditional],
			     [CONDITION]                                                     AS [Condition],
			     [NEEDSATTENTION]                                                AS [NeedsAttention]
		    FROM [dbo].[Undertakings] 
		   WHERE ([MATTER] = @MatterCode  AND (MATTER < @MatterCode
		  OR
			([SEQ] <= 99 AND ([SEQ] < 99 OR ([DATE] <= null AND ([DATE] < NULL OR ([RECORDID] <= 0 )))))))
		ORDER BY 
			[MATTER] DESC,
			[SEQ] DESC,
			[DATE] DESC,
			[RECORDID] DESC

		SELECT 
			[CODE] AS [Code],
			[BRANCH] AS [Branch],
			[NAME] AS [Name],
			[NOMINAL] AS [Nominal],
			[RETIRED] AS [Retired]
		FROM
			[dbo].[FeeEarnerCodes] WHERE [CODE] = @FECode
 SET NOCOUNT OFF
END 

GO

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

go 

CREATE PROCEDURE [dbo].[KAAS_GetSAMUndertakingDetails] (@MatterCode VARCHAR(20),@Handler VARCHAR(10)) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to Get Undertaking details																		 *
  * Stored Procedure Name: [dbo].KAAS_GetSAMUndertakingDetails '000003/0008','ADM'					     * 
  * Modification History:                                                                                *
  * 2021-03-30 Natarajan S        Created																 *
  * 2021-06-01 Balamurugan        Modified--Commented the type column case when							 *      
   *******************************************************************************************************/
  BEGIN 

EXEC [dbo].KAAS_GetSAMHeaderDetails	@MatterCode  

	SELECT 
	 [UND].[RecordID], 
	 [UND].[Matter], 
	 [UND].[Seq], 
	 [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([UND].[DischargeDate],@Handler) AS [DischargeDate],
 	 [UND].[Type],
         [UND].[Description], 
         [UND].[Who], 
         [UND].[ActionID], 
         [UND].[Status], 
         [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([UND].[Date],@Handler) AS [Date],
         [UND].[Value], 
         [UND].[AuthorisedByFE] 
	FROM 
		 [dbo].[Undertakings] [UND] 
	WHERE 
		 [UND].[MATTER] = @MatterCode 
	ORDER BY 
		[UND].[MATTER] ASC, 
		[UND].[SEQ] ASC, 
		[UND].[DATE] ASC, 
		[UND].[RECORDID]

  END 

GO

IF EXISTS(SELECT
             TOP 1 1
            FROM sys.[objects] SO
           WHERE SO.[name] = N'KAAS_GetSAMUndertakingDetailsForEdit'
             AND SO.[type] = 'P'
		  ) 
BEGIN 
 DROP PROCEDURE [dbo].[KAAS_GetSAMUndertakingDetailsForEdit] 
END
GO
CREATE PROCEDURE [dbo].[KAAS_GetSAMUndertakingDetailsForEdit] (
                 @RecordId INT,
				 @Handler  VARCHAR(10) = ''
				 ) 
AS 
 /*******************************************************************************************************
 *                                                                                                       *
 *Used to Get Undertaking details	for edit															 *
 * Stored Procedure Name: [dbo].KAAS_GetSAMUndertakingDetailsForEdit  166,'ADM'					         * 
 * Modification History:                                                                                 *
 * 2021-03-30 Natarajan S        Created																 *
 * 2021-10-04 Balamurugan.c		 Modified - Change DATE to Date											 *
  *******************************************************************************************************/
 BEGIN 
  SELECT [UDK].[RecordId]                                                            AS [RecordId],
		 [UDK].[Matter]                                                              AS [Matter],
		 [UDK].[Seq]                                                                 AS [Seq],
		 [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([UDK].[DISCHARGEDATE],@Handler) AS [DischargeDate],
		 [UDK].[Type]                                                                AS [Type],
		 [UDK].[Description]                                                         AS [Description],
		 [UDK].[Who]                                                                 AS [Who],
		 [UDK].[ActionId]                                                            AS [ActionId],
		 [UDK].[GivenOrReceived]                                                     AS [GivenOrReceived],
		 [UDK].[DischargeDescription]                                                AS [DisDescription],
		 [UDK].[DischargedBy]                                                        AS [DischargedBy],
		 [UDK].[DealingNumber]                                                       AS [DealingNumber],
		 [UDK].[Notes]                                                               AS [Notes],
		 [UDK].[CommercialOrNon]                                                     AS [CommercialOrNon],
		 [UDK].[Status]                                                            	 AS [Status],
		 [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([UDK].[DATE],@Handler)          AS [Date],
		 [UDK].[Value]                                                               AS [Value],
		 [UDK].[AuthorisedByFe]                                                      AS [AuthorisedByFe],
		 [UDK].[Handler]                                                             AS [Handler],
		 [UDK].[UndertakingTo]                                                       AS [UndertakingTo],
		 [UDK].[CaseContact]                                                         AS [CaseContact],
		 [UDK].[EntryDate]                                                           AS [EntryDate],
		 [UDK].[Category]                                                            AS [Category],
		 [UDK].[IsConditional]                                                       AS [IsConditional],
		 [UDK].[Condition]                                                           AS [Condition],
		 [UDK].[NeedsAttention]                                                      AS [NeedsAttention],
		 [UDK].[AddCommentLedger]                                                    AS [AddCommentLedger],
		 [dbo].KAAS_FNConvertUTCDateToTargetTimeZone([DIA].[DATE],@Handler)          AS [DueDate],
		 [DIA].[TeamCode]                                                            AS [TeamCode],
		 [DIA].[FNCode]                                                              AS [FNCode],
		 [DIA].[Text1]                                                               AS [Text1]      
	FROM [dbo].[Undertakings] [UDK] INNER JOIN 
	     [dbo].[diary] [DIA]
      ON [UDK].[ActionId]=[DIA].[ActionId]
   WHERE [RecordId]=@RecordId

  END 
 

GO 



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


CREATE PROCEDURE [dbo].[KAAS_GetSAMUndertakingDiaryDetails] (
			     @ActionCode VARCHAR(20),
			     @FECode     VARCHAR(10)
	             ) 
AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSAMUndertakingDiaryDetails]															*
* Description: Get basic details to insert into diary information.                                      *					  
* Modification History:                                                                                 *
* 10 APR 2021   Natarajan S        Created															    *   
* 14 JUL 2021   Natarajan S        Modified - SP Formatted											    *      
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON   
  SELECT CASE [Priority]  WHEN 'High' 
                          THEN 'H'
                          ELSE 'N' 
                          END				
                          AS [Priority],
		 [Highlighted]	  AS [Highlighted],
		 [Publisher]	  AS [Publish],
		 [ActionCode]	  AS [ActionCode],
		 [Status]		  AS [ActionStatus],
		 [ActionCategory] AS [ActionType],
		 [ProcessType]	  AS [ProcessType],
		 [Desc]			  AS [ActionCodeDescription],
		 [Code]			  AS [FNCode],
		 [Team]			  AS[TeamCode]
    FROM [dbo].[TemplateActions],
		 [dbo].[Handlers]
   WHERE [Code]       = @FECode  
     AND [ActionCode] = @ActionCode

 SET NOCOUNT OFF
END 

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_GetSAMUnpostedBatches' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_GetSAMUnpostedBatches] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_GetSAMUnpostedBatches] 
		(
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Posted',
			@SortOrder     VARCHAR(100) = 'ASC'
	    )
AS
/*******************************************************************************************************
* Fetches the unposted batches                                                                         * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMUnpostedBatches]   										   *
*                                                                                                      *
* Modification History:                                                                                *
* 09 Sep  2021    Balamurugan C        Created														   *                                     
* 16 Mar  2022    Vignesh M            Modified   Added Requested Transfer Count
* 21 Jul  2022    Ghayathri.S.V		   Modified - To implement dynamic sql query to fetch sort
									              and search datas and fetch debtor ledger balances    *
* 09 Aug  2022    Ghayathri.S.V		   Modified - To add value column for server side pagination search *
*******************************************************************************************************/
BEGIN
 SET NOCOUNT ON

 DECLARE @sql       NVARCHAR(max)
 DECLARE @search	NVARCHAR(500) = ''
 DECLARE @offset	INT = @PageSize * (@PageNumber -1)

    SET	 @sql ='SELECT [BatchNo],
					  [Type],
					  [Code],
					  [Ref],
					  [Date],
       				  [Fee],
       				  [Matter],
       				  [Supp],
       				  [Narr],
       				  [Value],
       				  [Posted],
       				  [PerNo],
       				  [Year],
       				  [EntryDate],
       				  [RecNo],
					  [ChequeReqNo]
				 FROM [dbo].[BatchH] 
				WHERE [Posted]=''N''' +
				 'AND ( 
						[BatchNo] LIKE' + '''%'  + @SearchString + '%' + '''' +	
						'OR
						[Code]	  LIKE ' + '''%' + @SearchString + '%' + '''' +
						'OR
						[Ref]	  LIKE ' + '''%' + @SearchString + '%' + '''' +
						'OR
						[Matter]  LIKE ' + '''%' + @SearchString + '%' + '''' +
						'OR
						[Supp]	  LIKE ' + '''%' + @SearchString + '%' + '''' +
						'OR
						[Narr]	  LIKE ' + '''%' + @SearchString + '%' + '''' +	
						'OR
						[Date]	  LIKE ' + '''%' + @SearchString + '%' + '''' +
						'OR
						[Fee]	  LIKE ' + '''%' + @SearchString + '%' + '''' +
						'OR
						[Value]	  LIKE ' + '''%' + @SearchString + '%' + '''' +
					 ')
		   ORDER BY ' +  @SortColumn + ' '  + @SortOrder + ' ' +
	        'OFFSET ' +  CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
	    'FETCH NEXT ' +  CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

		EXEC Sp_executesql @sql

		     SELECT COUNT(*)  'TotalRecord'
			   FROM [dbo].[BatchH] 
			  WHERE [Posted]='N' 	
			   AND  ( 
					  [BatchNo]   LIKE '%' + @SearchString + '%'  
					  OR
					  [Code]	  LIKE '%' + @SearchString + '%' 
					  OR
					  [Ref]	      LIKE '%' + @SearchString + '%' 
					  OR
					  [Matter]	  LIKE '%' + @SearchString + '%' 
					  OR
					  [Supp]	  LIKE '%' + @SearchString + '%' 
					  OR
					  [Narr]	  LIKE '%' + @SearchString + '%' 
					  OR
					  [Date]	  LIKE '%' + @SearchString + '%'
					  OR
					  [Fee]	  LIKE '%' + @SearchString + '%'
					  OR
					  [Value]	  LIKE '%' + @SearchString + '%')

			 SELECT COUNT([CTG].RECORDID) [RequestedTransfer]
			   FROM [dbo].[CostTransGathering] AS [CTG] 
    LEFT OUTER JOIN [dbo].[Matters]            AS [MTR] ON  [CTG].MATTER     = [MTR].CODE 
	LEFT OUTER JOIN [dbo].[contacts]           AS [CON] ON  [MTR].CLIENTCODE = [CON].CODE

 SET NOCOUNT OFF
END

GO

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

CREATE PROCEDURE [dbo].[KAAS_GetSAMUpdateApproveBillHeader]
	(
		 @Code			 VARCHAR(50) = '',
		 @DraftNo		 INT,
		 @BillSentOrNot  CHAR(1) = '',
		 @Date		     DATE,
		 @Message	     VARCHAR(100) = '',
		 @BillTo	     VARCHAR(100) = ''
	 )
AS

/*******************************************************************************************************
* Update Bill Header								                                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSAMUpdateApproveBillHeader]		   	     			       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-16    Vinodhkumar M        Created                                                           *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
 *******************************************************************************************************/

BEGIN
  BEGIN TRY
	BEGIN TRANSACTION

			 UPDATE [dbo].[BillHeader] 
				SET [BILLSENT]		=  @BillSentOrNot,
					[DATE]			=  @Date,
					[RETURNREASON]  =  @Message,
					[ADDRESSEE]		=  @BillTo
			  WHERE [MATTER]        =  @Code	 
				AND [DRAFTNO]       =  @DraftNo

  	  COMMIT TRANSACTION
 END TRY
 BEGIN CATCH
   DECLARE @ErrorMsg      NVARCHAR(4000), 
  		   @ErrorSeverity INT,
  		   @ErrorState    INT; 
  
    SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
  		   @ErrorSeverity = ERROR_SEVERITY(), 
  		   @ErrorState    = ERROR_STATE()

RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
  		 IF @@TRANCOUNT > 0  
  			BEGIN
  				ROLLBACK TRANSACTION;
  			END 
 END CATCH
 END
 GO



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

CREATE PROCEDURE [dbo].[KAAS_GetSamUpdateDebtLodgement]
	(
		@PostingRef   INT = 0,
		@LastBatch    INT = 0
	)
AS

/*******************************************************************************************************
* Update Debt Lodgement		                                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamUpdateDebtLodgement]        						       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-01    Vinodhkumar M        Created                                                           *
* 2021-10-18    Vinodhkumar M        Modified - removed insert query								   *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/

BEGIN
 BEGIN TRY
	BEGIN TRAN
			
	 UPDATE	 [dbo].[DebtCostingLedger] 
	    SET	 XnId = @LastBatch 
	  WHERE  POSTINGREF = @PostingRef

	COMMIT TRAN
	END TRY
		BEGIN CATCH 
			   DECLARE @ErrorMsg      NVARCHAR(4000), 
					   @ErrorSeverity INT,
					   @ErrorState    INT; 

				SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					   @ErrorSeverity = ERROR_SEVERITY(), 
					   @ErrorState    = ERROR_STATE()

			RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
					 IF @@TRANCOUNT > 0  
						BEGIN
							ROLLBACK TRANSACTION;
						END 
		END CATCH
END

GO
IF OBJECT_ID(N'KAAS_GetSamUpdateMatterClientCode',N'P')IS NOT NULL
DROP PROCEDURE [dbo].[KAAS_GetSamUpdateMatterClientCode]
GO
CREATE PROCEDURE [dbo].[KAAS_GetSamUpdateMatterClientCode]
	(
		@Code				VARCHAR(11) = '',
		@ClientCode			VARCHAR(8)  = '',
		@PreviousClientCode VARCHAR(8)  = ''
	)
AS

/*******************************************************************************************************
* Update Matter and Client Code                                                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamUpdateMatterClientCode]        						       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-01    Vinodhkumar M        Created                                                           *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/

BEGIN
  BEGIN TRY
	BEGIN TRAN

		DECLARE @FormatNewMaterCode			VARCHAR(4) = '',
				@NewClientMatterCode        VARCHAR(11) = '',
				@oldClientCode				VARCHAR(11) = '';

		--UPDATE LAST MATTER COUNTS FOR NEW CLIENT
	     UPDATE [dbo].[Contacts]
		    SET [LastMatter]   = (LastMatter + 1)
		  WHERE [Code]  = @ClientCode

		 SELECT @oldClientCode      = Code,
			    @FormatNewMaterCode = RIGHT('000'+CAST(ISNULL(LastMatter,0) AS VARCHAR),4) 
		   FROM [dbo].[Contacts] 
		  WHERE [Code]  = @ClientCode

		    SET @NewClientMatterCode = (@oldClientCode+'/'+@FormatNewMaterCode)

  --INSERT NEW RECORD IN MATTER TABLE
  INSERT INTO  [dbo].[matters]
			  ([Code]
			  ,[ClientCode]
			  ,[Matter]
			  ,[Description]
			  ,[FECode]
			  ,[Partner]
			  ,[Secretary]
			  ,[Dept]
			  ,[Started]
			  ,[WType]
			  ,[Branch]
			  ,[EstFee]
			  ,[OutlayBud]
			  ,[ExpBillD]
			  ,[ExpPayD]
			  ,[S13]
			  ,[Comment]
			  ,[DebtBal]
			  ,[OutlayBal]
			  ,[ClientBal]
			  ,[ClientCurBal]
			  ,[ClientDepBal]
			  ,[DebtBalFwd]
			  ,[OutlayBalFwd]
			  ,[ClientBalFwd]
			  ,[ClientCurBalFwd]
			  ,[ClientDepBalFwd]
			  ,[PendingBal]
			  ,[ClientMin]
			  ,[FileNum]
			  ,[ThirdPart]
			  ,[ThPartSol]
			  ,[Value]
			  ,[Undertaking]
			  ,[LastAct]
			  ,[LastActType]
			  ,[LastActWho]
			  ,[StatuteLimits]
			  ,[Status]
			  ,[Section68]
			  ,[FNL_Date]
			  ,[FNL_Name]
			  ,[FNL_Address]
			  ,[FNL_Fees]
			  ,[FNL_Outlay]
			  ,[FNL_VAT]
			  ,[FNL_Total]
			  ,[OldRef]
			  ,[PCODE]
			  ,[PFECODE]
			  ,[User1]
			  ,[User2]
			  ,[User3]
			  ,[DepositName]
			  ,[DepositType]
			  ,[TimeBal]
			  ,[ChargeBal]
			  ,[YourRef]
			  ,[CurDebtBal]
			  ,[CurOutlayBal]
			  ,[CurClientBal]
			  ,[CurClientCBal]
			  ,[CurClientDBal]
			  ,[CurDebtBalFwd]
			  ,[CurOutlayBalFwd]
			  ,[CurClientBalFwd]
			  ,[CurClientCBalFwd]
			  ,[CurClientDBalFwd]
			  ,[CurPendingBal]
			  ,[Unallocated]
			  ,[Statements]
			  ,[ChargeLevel]
			  ,[FileColour]
			  ,[OpenInvoiceNo]
			  ,[Password]
			  ,[CompBillOnOff]
			  ,[CompFrequency]
			  ,[CompOutlayLimit]
			  ,[CompFeesLimit]
			  ,[CompTotalLimit]
			  ,[CompBillingMatter]
			  ,[CompBilling]
			  ,[ClientName]
			  ,[ClientAddress]
			  ,[ClientSalutation]
			  ,[ChargeArrangement]
			  ,[Importance]
			  ,[OriginalDebt]
			  ,[DebtCollected]
			  ,[RecoverableCosts]
			  ,[DebtInterest]
			  ,[BillingMethod]
			  ,[CollectingBalance]
			  ,[Publish]
			  ,[Permissions]
			  ,[ChargeOutRateInd]
			  ,[OUTFileNo]
			  ,[OrgClosedDate]
			  ,[ReOpenedDate]
			  ,[FixedFee]
			  ,[ShowCommentInAlarm]
			  ,[OtherRef]
			  ,[Location]
			  ,[DestroyDate]
			  ,[Closed]
			  ,[ClosingDate]
			  ,[CloseDate]
			  ,[DepositAC1]
			  ,[DepositAC2]
			  ,[DepositAC3]
			  ,[ArchiveDate]
			  ,[ArchiveLocation]
			  ,[SetupYear]
			  ,[SetupPeriod]
			  ,[OldNew]
			  ,[ClientBankAc]
			  ,[OfficeBankAc]
			  ,[FileManagerFileNumber]
			  ,[ItemCode]
			  ,[BoxNumber]
			  ,[BillingFE]
			  ,[EstFeeIndicator]
			  ,[DestroyedBy]
			  ,[FileBarCodeNo]
			  ,[BoxBarCodeNo]
			  ,[ActualDestroyDate]
			  ,[NoWinNoFee]
			  ,[FeeType])	

SELECT		   @NewClientMatterCode AS [Code]
			  ,@ClientCode
			  ,@FormatNewMaterCode  AS [Matter]
			  ,[Description]
			  ,[FECode]
			  ,[Partner]
			  ,[Secretary]
			  ,[Dept]
			  ,[Started]
			  ,[WType]
			  ,[Branch]
			  ,[EstFee]
			  ,[OutlayBud]
			  ,[ExpBillD]
			  ,[ExpPayD]
			  ,[S13]
			  ,[Comment]
			  ,[DebtBal]
			  ,[OutlayBal]
			  ,[ClientBal]
			  ,[ClientCurBal]
			  ,[ClientDepBal]
			  ,[DebtBalFwd]
			  ,[OutlayBalFwd]
			  ,[ClientBalFwd]
			  ,[ClientCurBalFwd]
			  ,[ClientDepBalFwd]
			  ,[PendingBal]
			  ,[ClientMin]
			  ,[FileNum]
			  ,[ThirdPart]
			  ,[ThPartSol]
			  ,[Value]
			  ,[Undertaking]
			  ,[LastAct]
			  ,[LastActType]
			  ,[LastActWho]
			  ,[StatuteLimits]
			  ,[Status]
			  ,[Section68]
			  ,[FNL_Date]
			  ,[FNL_Name]
			  ,[FNL_Address]
			  ,[FNL_Fees]
			  ,[FNL_Outlay]
			  ,[FNL_VAT]
			  ,[FNL_Total]
			  ,[OldRef]
			  ,@NewClientMatterCode AS [PCODE]
			  ,[PFECODE]
			  ,[User1]
			  ,[User2]
			  ,[User3]
			  ,[DepositName]
			  ,[DepositType]
			  ,[TimeBal]
			  ,[ChargeBal]
			  ,[YourRef]
			  ,[CurDebtBal]
			  ,[CurOutlayBal]
			  ,[CurClientBal]
			  ,[CurClientCBal]
			  ,[CurClientDBal]
			  ,[CurDebtBalFwd]
			  ,[CurOutlayBalFwd]
			  ,[CurClientBalFwd]
			  ,[CurClientCBalFwd]
			  ,[CurClientDBalFwd]
			  ,[CurPendingBal]
			  ,[Unallocated]
			  ,[Statements]
			  ,[ChargeLevel]
			  ,[FileColour]
			  ,[OpenInvoiceNo]
			  ,[Password]
			  ,[CompBillOnOff]
			  ,[CompFrequency]
			  ,[CompOutlayLimit]
			  ,[CompFeesLimit]
			  ,[CompTotalLimit]
			  ,[CompBillingMatter]
			  ,[CompBilling]
			  ,[ClientName]
			  ,[ClientAddress]
			  ,[ClientSalutation]
			  ,[ChargeArrangement]
			  ,[Importance]
			  ,[OriginalDebt]
			  ,[DebtCollected]
			  ,[RecoverableCosts]
			  ,[DebtInterest]
			  ,[BillingMethod]
			  ,[CollectingBalance]
			  ,[Publish]
			  ,[Permissions]
			  ,[ChargeOutRateInd]
			  ,[OUTFileNo]
			  ,[OrgClosedDate]
			  ,[ReOpenedDate]
			  ,[FixedFee]
			  ,[ShowCommentInAlarm]
			  ,[OtherRef]
			  ,[Location]
			  ,[DestroyDate]
			  ,'N'				AS [Closed]
			  ,NULL				AS [ClosingDate]
			  ,NULL				AS [CloseDate]
			  ,[DepositAC1]
			  ,[DepositAC2]
			  ,[DepositAC3]
			  ,[ArchiveDate]
			  ,[ArchiveLocation]
			  ,[SetupYear]
			  ,[SetupPeriod]
			  ,[OldNew]
			  ,[ClientBankAc]
			  ,[OfficeBankAc]
			  ,[FileManagerFileNumber]
			  ,[ItemCode]
			  ,[BoxNumber]
			  ,[BillingFE]
			  ,[EstFeeIndicator]
			  ,[DestroyedBy]
			  ,[FileBarCodeNo]
			  ,[BoxBarCodeNo]
			  ,[ActualDestroyDate]
			  ,[NoWinNoFee]
			  ,[FeeType]

		FROM  
			   [dbo].[matters] 
		WHERE  
			   [Code]=@Code

	   --CLOSE EXISTING CLIENT MATTER CODE 
	   UPDATE   [dbo].[matters]
		  SET	
				[Description] = ('Moved to NEW Matter: '+@NewClientMatterCode),
				[Comment]	    = ([Comment] +'Moved to NEW Matter: '+@NewClientMatterCode),
				[Closed]		= 'Y',
				[ClosingDate] = GETUTCDATE(),
				[CloseDate]   = GETUTCDATE()
		WHERE
				[Code]=@Code	


		--UPDATE OPEN MATTER COUNTS FOR PREVIOUS CLIENT
	   UPDATE	[dbo].[Contacts]
		  SET 
				[OpenMatters]  = (SELECT COUNT(1)
								  FROM   [dbo].[matters] 
								  WHERE  [ClientCode]=@PreviousClientCode 
								  AND    [Closed]='N')
		WHERE   
				[Code]  = @PreviousClientCode

		--UPDATE OPEN MATTER COUNTS FOR NEW CLIENT
	   UPDATE	[dbo].[Contacts]
		  SET 
				[OpenMatters]  = (SELECT COUNT(1) 
								  FROM	 [dbo].[matters] 
								  WHERE  [ClientCode]=@ClientCode 
								  AND    [Closed]='N')
		WHERE   
				[Code]  = @ClientCode

COMMIT TRAN

END TRY
	BEGIN CATCH 
		   DECLARE @ErrorMsg      NVARCHAR(4000), 
				   @ErrorSeverity INT,
				   @ErrorState    INT; 

			SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				   @ErrorSeverity = ERROR_SEVERITY(), 
				   @ErrorState    = ERROR_STATE()

		RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
				 IF @@TRANCOUNT > 0  
					BEGIN
						ROLLBACK TRANSACTION;
					END 
	END CATCH
END
GO

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

CREATE PROCEDURE 
[dbo].[KAAS_GetSamUpdateMatterClientCode]
(@Code				VARCHAR(11) = '',
@ClientCode			VARCHAR(8)  = '',
@PreviousClientCode VARCHAR(8)  = '')
AS

/*******************************************************************************************************
* Update Matter and Client Code                                                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetSamUpdateMatterClientCode]        						       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-01    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/

BEGIN
BEGIN TRY
BEGIN TRAN

		DECLARE @FormatNewMaterCode			VARCHAR(4) = '',
				@NewClientMatterCode        VARCHAR(11) = '',
				@oldClientCode				VARCHAR(11) = '';

		--UPDATE LAST MATTER COUNTS FOR NEW CLIENT
	   UPDATE	[dbo].[Contacts]
		  SET 
				[LastMatter]   = (LastMatter + 1)
		WHERE   
				[Code]  = @ClientCode


	   SELECT   @oldClientCode      = Code,
				@FormatNewMaterCode = RIGHT('000'+CAST(ISNULL(LastMatter,0) AS VARCHAR),4) 
		 FROM   
				[dbo].[Contacts] 
		WHERE   
				[Code]  = @ClientCode

		  SET   @NewClientMatterCode = (@oldClientCode+'/'+@FormatNewMaterCode)

  --INSERT NEW RECORD IN MATTER TABLE
  INSERT INTO  [dbo].[matters]
			  ([Code]
			  ,[ClientCode]
			  ,[Matter]
			  ,[Description]
			  ,[FECode]
			  ,[Partner]
			  ,[Secretary]
			  ,[Dept]
			  ,[Started]
			  ,[WType]
			  ,[Branch]
			  ,[EstFee]
			  ,[OutlayBud]
			  ,[ExpBillD]
			  ,[ExpPayD]
			  ,[S13]
			  ,[Comment]
			  ,[DebtBal]
			  ,[OutlayBal]
			  ,[ClientBal]
			  ,[ClientCurBal]
			  ,[ClientDepBal]
			  ,[DebtBalFwd]
			  ,[OutlayBalFwd]
			  ,[ClientBalFwd]
			  ,[ClientCurBalFwd]
			  ,[ClientDepBalFwd]
			  ,[PendingBal]
			  ,[ClientMin]
			  ,[FileNum]
			  ,[ThirdPart]
			  ,[ThPartSol]
			  ,[Value]
			  ,[Undertaking]
			  ,[LastAct]
			  ,[LastActType]
			  ,[LastActWho]
			  ,[StatuteLimits]
			  ,[Status]
			  ,[Section68]
			  ,[FNL_Date]
			  ,[FNL_Name]
			  ,[FNL_Address]
			  ,[FNL_Fees]
			  ,[FNL_Outlay]
			  ,[FNL_VAT]
			  ,[FNL_Total]
			  ,[OldRef]
			  ,[PCODE]
			  ,[PFECODE]
			  ,[User1]
			  ,[User2]
			  ,[User3]
			  ,[DepositName]
			  ,[DepositType]
			  ,[TimeBal]
			  ,[ChargeBal]
			  ,[YourRef]
			  ,[CurDebtBal]
			  ,[CurOutlayBal]
			  ,[CurClientBal]
			  ,[CurClientCBal]
			  ,[CurClientDBal]
			  ,[CurDebtBalFwd]
			  ,[CurOutlayBalFwd]
			  ,[CurClientBalFwd]
			  ,[CurClientCBalFwd]
			  ,[CurClientDBalFwd]
			  ,[CurPendingBal]
			  ,[Unallocated]
			  ,[Statements]
			  ,[ChargeLevel]
			  ,[FileColour]
			  ,[OpenInvoiceNo]
			  ,[Password]
			  ,[CompBillOnOff]
			  ,[CompFrequency]
			  ,[CompOutlayLimit]
			  ,[CompFeesLimit]
			  ,[CompTotalLimit]
			  ,[CompBillingMatter]
			  ,[CompBilling]
			  ,[ClientName]
			  ,[ClientAddress]
			  ,[ClientSalutation]
			  ,[ChargeArrangement]
			  ,[Importance]
			  ,[OriginalDebt]
			  ,[DebtCollected]
			  ,[RecoverableCosts]
			  ,[DebtInterest]
			  ,[BillingMethod]
			  ,[CollectingBalance]
			  ,[Publish]
			  ,[Permissions]
			  ,[ChargeOutRateInd]
			  ,[OUTFileNo]
			  ,[OrgClosedDate]
			  ,[ReOpenedDate]
			  ,[FixedFee]
			  ,[ShowCommentInAlarm]
			  ,[OtherRef]
			  ,[Location]
			  ,[DestroyDate]
			  ,[Closed]
			  ,[ClosingDate]
			  ,[CloseDate]
			  ,[DepositAC1]
			  ,[DepositAC2]
			  ,[DepositAC3]
			  ,[ArchiveDate]
			  ,[ArchiveLocation]
			  ,[SetupYear]
			  ,[SetupPeriod]
			  ,[OldNew]
			  ,[ClientBankAc]
			  ,[OfficeBankAc]
			  ,[FileManagerFileNumber]
			  ,[ItemCode]
			  ,[BoxNumber]
			  ,[BillingFE]
			  ,[EstFeeIndicator]
			  ,[DestroyedBy]
			  ,[FileBarCodeNo]
			  ,[BoxBarCodeNo]
			  ,[ActualDestroyDate]
			  ,[NoWinNoFee]
			  ,[FeeType])	

SELECT		   @NewClientMatterCode AS [Code]
			  ,@ClientCode
			  ,@FormatNewMaterCode  AS [Matter]
			  ,[Description]
			  ,[FECode]
			  ,[Partner]
			  ,[Secretary]
			  ,[Dept]
			  ,[Started]
			  ,[WType]
			  ,[Branch]
			  ,[EstFee]
			  ,[OutlayBud]
			  ,[ExpBillD]
			  ,[ExpPayD]
			  ,[S13]
			  ,[Comment]
			  ,[DebtBal]
			  ,[OutlayBal]
			  ,[ClientBal]
			  ,[ClientCurBal]
			  ,[ClientDepBal]
			  ,[DebtBalFwd]
			  ,[OutlayBalFwd]
			  ,[ClientBalFwd]
			  ,[ClientCurBalFwd]
			  ,[ClientDepBalFwd]
			  ,[PendingBal]
			  ,[ClientMin]
			  ,[FileNum]
			  ,[ThirdPart]
			  ,[ThPartSol]
			  ,[Value]
			  ,[Undertaking]
			  ,[LastAct]
			  ,[LastActType]
			  ,[LastActWho]
			  ,[StatuteLimits]
			  ,[Status]
			  ,[Section68]
			  ,[FNL_Date]
			  ,[FNL_Name]
			  ,[FNL_Address]
			  ,[FNL_Fees]
			  ,[FNL_Outlay]
			  ,[FNL_VAT]
			  ,[FNL_Total]
			  ,[OldRef]
			  ,@NewClientMatterCode AS [PCODE]
			  ,[PFECODE]
			  ,[User1]
			  ,[User2]
			  ,[User3]
			  ,[DepositName]
			  ,[DepositType]
			  ,[TimeBal]
			  ,[ChargeBal]
			  ,[YourRef]
			  ,[CurDebtBal]
			  ,[CurOutlayBal]
			  ,[CurClientBal]
			  ,[CurClientCBal]
			  ,[CurClientDBal]
			  ,[CurDebtBalFwd]
			  ,[CurOutlayBalFwd]
			  ,[CurClientBalFwd]
			  ,[CurClientCBalFwd]
			  ,[CurClientDBalFwd]
			  ,[CurPendingBal]
			  ,[Unallocated]
			  ,[Statements]
			  ,[ChargeLevel]
			  ,[FileColour]
			  ,[OpenInvoiceNo]
			  ,[Password]
			  ,[CompBillOnOff]
			  ,[CompFrequency]
			  ,[CompOutlayLimit]
			  ,[CompFeesLimit]
			  ,[CompTotalLimit]
			  ,[CompBillingMatter]
			  ,[CompBilling]
			  ,[ClientName]
			  ,[ClientAddress]
			  ,[ClientSalutation]
			  ,[ChargeArrangement]
			  ,[Importance]
			  ,[OriginalDebt]
			  ,[DebtCollected]
			  ,[RecoverableCosts]
			  ,[DebtInterest]
			  ,[BillingMethod]
			  ,[CollectingBalance]
			  ,[Publish]
			  ,[Permissions]
			  ,[ChargeOutRateInd]
			  ,[OUTFileNo]
			  ,[OrgClosedDate]
			  ,[ReOpenedDate]
			  ,[FixedFee]
			  ,[ShowCommentInAlarm]
			  ,[OtherRef]
			  ,[Location]
			  ,[DestroyDate]
			  ,'N'				AS [Closed]
			  ,NULL				AS [ClosingDate]
			  ,NULL				AS [CloseDate]
			  ,[DepositAC1]
			  ,[DepositAC2]
			  ,[DepositAC3]
			  ,[ArchiveDate]
			  ,[ArchiveLocation]
			  ,[SetupYear]
			  ,[SetupPeriod]
			  ,[OldNew]
			  ,[ClientBankAc]
			  ,[OfficeBankAc]
			  ,[FileManagerFileNumber]
			  ,[ItemCode]
			  ,[BoxNumber]
			  ,[BillingFE]
			  ,[EstFeeIndicator]
			  ,[DestroyedBy]
			  ,[FileBarCodeNo]
			  ,[BoxBarCodeNo]
			  ,[ActualDestroyDate]
			  ,[NoWinNoFee]
			  ,[FeeType]

		FROM  
			   [dbo].[matters] 
		WHERE  
			   [Code]=@Code

	   --CLOSE EXISTING CLIENT MATTER CODE 
	   UPDATE   [dbo].[matters]
		  SET	
				[Description] = ('Moved to NEW Matter: '+@NewClientMatterCode),
				[Comment]	    = ([Comment] +'Moved to NEW Matter: '+@NewClientMatterCode),
				[Closed]		= 'Y',
				[ClosingDate] = GETUTCDATE(),
				[CloseDate]   = GETUTCDATE()
		WHERE
				[Code]=@Code	


		--UPDATE OPEN MATTER COUNTS FOR PREVIOUS CLIENT
	   UPDATE	[dbo].[Contacts]
		  SET 
				[OpenMatters]  = (SELECT COUNT(1)
								  FROM   [dbo].[matters] 
								  WHERE  [ClientCode]=@PreviousClientCode 
								  AND    [Closed]='N')
		WHERE   
				[Code]  = @PreviousClientCode

		--UPDATE OPEN MATTER COUNTS FOR NEW CLIENT
	   UPDATE	[dbo].[Contacts]
		  SET 
				[OpenMatters]  = (SELECT COUNT(1) 
								  FROM	 [dbo].[matters] 
								  WHERE  [ClientCode]=@ClientCode 
								  AND    [Closed]='N')
		WHERE   
				[Code]  = @ClientCode

COMMIT TRAN

END TRY
BEGIN CATCH 
ROLLBACK TRAN
END CATCH


END
GO



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

GO

CREATE PROCEDURE 
        [dbo].[KAAS_GetSAM_MatterClosable]
        (@MATTER VARCHAR(20))
AS

/*******************************************************************************************************
* check SAM Matter closable or not																	   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_GetSAM_MatterClosable]							               *
*                                                                                                      *
* Modification History	:                                                                              *
* 2022-01-21    Vinodhkumar.M     Duplication from SP-> ky_NETPMatterClosable		                   *
*******************************************************************************************************/
BEGIN

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

DECLARE @HasUnallocatedReceipts BIT
DECLARE @CheckUnallocatedReceipts BIT

DECLARE @HasDraftBills BIT
DECLARE @CheckDraftBillsClosingMatter BIT

DECLARE @IsSAM4 bit

SELECT @CheckDraftBillsClosingMatter = CASE WHEN [SET].[KeyName] = 'CheckDraftBillsClosingMatter'
                                             AND [SET].[KeyValue] = 'True'
                                                 THEN 1
                                            ELSE ISNULL(@CheckDraftBillsClosingMatter, 0) END,
       @CheckUnallocatedReceipts     = CASE WHEN [SET].[KeyName] = 'CheckUnallocatedReceipts'
                                             AND [SET].[KeyValue] = 'True'
                                                 THEN 1
                                            ELSE ISNULL(@CheckUnallocatedReceipts, 0) END
  FROM [dbo].[Settings] AS [SET]
 WHERE [SET].[KeyName] IN ('CheckDraftBillsClosingMatter', 'CheckUnallocatedReceipts')

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

-- Please see also: ky_NETCaseSummaryPageLoad. If you change any of these calculations,
--                                             ensure the ones in there are changed as well.
--                  ky_NETTLFetchTimeEntry. If you change any of these calculations,
--                                          ensure the ones in there are changed as well.
DECLARE @TimeBal      INT
DECLARE @ChargeBal    DECIMAL(19, 2)
DECLARE @TotalCharge  Decimal(19, 2)
DECLARE @TotalTime    INT
DECLARE @TimeEntryTotalCharge         DECIMAL(19, 2)
DECLARE @TimeEntryTotalTime           INT

SELECT @TimeEntryTotalCharge = ISNULL(SUM(ISNULL(TIE.[Charge], 0)), 0),
       @TimeEntryTotalTime = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0),
       @TotalCharge = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                      THEN 0
                                 ELSE ISNULL(TIE.[Charge], 0) END), 0),
       @ChargeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                         THEN 0
                                    WHEN [TIE].[IncludeInBill] = 2
                                         THEN 0
                                    WHEN @IsSAM4 = 1
                                     AND ISNULL(TIE.[InvoiceNo], 0) <> 0
                                         THEN 0
                                    WHEN @IsSAM4 = 1
                                         THEN ISNULL(TIE.[Charge], 0)
                                    ELSE ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0) END), 0),
       @TimeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                       THEN 0
                                  WHEN [TIE].[IncludeInBill] = 2
                                       THEN 0
                                  WHEN @IsSAM4 = 1
                                   AND ISNULL(TIE.[InvoiceNo], 0) <> 0
                                       THEN 0
                                  WHEN @IsSAM4 = 0
                                       THEN CASE WHEN TIE.[Charge] = 0
                                                      THEN 0
                                                 ELSE CONVERT(INT,
                                                              FLOOR(CONVERT(DECIMAL(18, 2), TIE.[TIME])
                                                                    * (  (TIE.[Charge] - TIE.[BilledAmount])
                                                                       /
                                                                       TIE.[Charge]))) END
                                  ELSE ISNULL(TIE.[Time], 0) END), 0),
       @TotalTime = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                         THEN 0
                                    ELSE ISNULL(TIE.[Time], 0) END), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[Matter] = @MATTER
   AND (   (TIE.[TimeOrCharge] = 'T')
        OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun

DECLARE @DebtBal        DECIMAL(19, 2)
DECLARE @OutlayBal      DECIMAL(19, 2)
DECLARE @DebtBalDate    DATETIME
DECLARE @OutlayBalDate  DATETIME
DECLARE @ClientCurrent  DECIMAL(19, 2)
DECLARE @ClientDeposit  DECIMAL(19, 2)

DECLARE @NCOMMAND NVARCHAR(MAX)
-- To ensure SAM3 will retrieve these from [dbo].[matters]
SET @DebtBal = 0 
SET @OutlayBal = 0
SET @ClientCurrent = 0
SET @ClientDeposit = 0
IF @IsSAM4 = 1
  BEGIN
    SET @NCOMMAND = N'
SELECT @DebtBal = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[DebtorsValue], 0)), 0)),
       @DebtBalDate = MAX(CASE WHEN ISNULL(TRN.[DebtorsValue], 0) = 0 THEN NULL ELSE TRN.[TransDate] END),
       @OutlayBal = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[OutlayValue], 0)), 0)),
       @OutlayBalDate = MAX(CASE WHEN ISNULL(TRN.[OutlayValue], 0) = 0 THEN NULL ELSE TRN.[TransDate] END),
       @ClientCurrent = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[ClientCurrent], 0)), 0)),
       @ClientDeposit = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[ClientDeposit], 0)), 0))
  FROM [dbo].[Transactions] TRN 
 WHERE TRN.[MatterCode] = @MATTER
   AND TRN.[Posted] = ''Y''
   AND TRN.[RecType] <> ''V''
   AND TRN.[CorrectionInd] = ''L'''
EXECUTE sp_executesql @NCOMMAND, 
                      N'@MATTER VARCHAR(20),
                        @DebtBal DECIMAL(19, 2) OUTPUT,
                        @DebtBalDate DATETIME OUTPUT,
                        @OutlayBal DECIMAL(19, 2) OUTPUT,
                        @OutlayBalDate DATETIME OUTPUT,
                        @ClientCurrent DECIMAL(19, 2) OUTPUT,
                        @ClientDeposit DECIMAL(19, 2) OUTPUT',
                      @MATTER        = @MATTER,
                      @DebtBal       = @DebtBal OUTPUT,
                      @DebtBalDate   = @DebtBalDate OUTPUT,
                      @OutlayBal     = @OutlayBal OUTPUT,
                      @OutlayBalDate = @OutlayBalDate OUTPUT,
                      @ClientCurrent = @ClientCurrent OUTPUT,
                      @ClientDeposit = @ClientDeposit OUTPUT
  END

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

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

DECLARE @YEAR INT

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = N'SELECT @YEAR = ISNULL(CTL.[YEAR], DATEPART(YEAR, GetDate()))
  FROM [dbo].[Control] CTL

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

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

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

  END

EXEC sp_executesql @NCOMMAND, N'@YEAR INT OUTPUT', @YEAR OUTPUT

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

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

  END

EXEC sp_executesql @NCOMMAND, N'@MATTER VARCHAR(20), @YEAR INT, @HasOutstandingRec INT OUTPUT', @MATTER, @YEAR, @HasOutstandingRec OUTPUT

IF @CheckUnallocatedReceipts = 1
  BEGIN
    IF @IsSAM4 = 0
      BEGIN
        SET @NCOMMAND = N'SELECT @HasUnallocatedReceipts = 
       CASE WHEN COUNT(1) = 0
                 THEN CONVERT(BIT, 0)
            ELSE CONVERT(BIT, 1) END
  FROM [dbo].[DebtorsLedger] [DL]
 WHERE [DL].[MATTER] = @MATTER
   AND [DL].[TYPE] = ''R''
   AND [DL].[OSVALUE] <> 0'
      END
    ELSE
      BEGIN
        SET @NCOMMAND = N'SELECT @HasUnallocatedReceipts =
       CASE WHEN COUNT(1) = 0
                 THEN CONVERT(BIT, 0)
            ELSE CONVERT(BIT, 1) END
  FROM [dbo].[DebtorsLedger] [DL]
 WHERE [DL].[MatterCode] = @MATTER
   AND [DL].[RecType] = ''R''
   AND [DL].[OSValue] <> 0'
      END

    EXEC sp_executesql @NCOMMAND, N'@MATTER VARCHAR(20), @HasUnallocatedReceipts INT OUTPUT', @MATTER, @HasUnallocatedReceipts OUTPUT
  END
ELSE
  BEGIN
    SET @HasUnallocatedReceipts = 0
  END

IF @CheckDraftBillsClosingMatter = 1
BEGIN
    IF @IsSAM4 = 0
    BEGIN
        SET @NCOMMAND = N'SELECT @HasDraftBills = CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END
                            FROM [dbo].[BillHeader] AS [BH]
                           WHERE [BH].[MATTER] = @MATTER
                             AND [BH].[BILLNO] = 0'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = N'SELECT @HasDraftBills = CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END
                            FROM [dbo].[Billhead] AS [BH]
                           WHERE [BH].[MatterCode] = @MATTER
                             AND [BH].[InvoiceNo] = 0'
    END

    EXEC sp_executesql @NCOMMAND, N'@MATTER VARCHAR(20), @HasDraftBills BIT OUTPUT', @MATTER, @HasDraftBills OUTPUT
END
ELSE
BEGIN
    SET @HasDraftBills = 0
END

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

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

SELECT @AlreadyClosed                       AS [AlreadyClosed],
       @HasOutstandingBal                   AS [HasOutstandingBal],
       @HasOutstandingTimeBal               AS [HasOutstandingTimeBal],
       @HasOutstandingChargeBal             AS [HasOutstandingChargeBal],
       @HasOutstandingRec                   AS [HasOutstandingRec],
       @HasOutstandingDiary                 AS [HasOutstandingDiary],
       @HasOutstandingUndertakings          AS [HasOutstandingUndertakings],
       @HasUnallocatedReceipts              AS [HasUnallocatedReceipts],
       @HasDraftBills                       AS [HasDraftBills]

END

GO


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

CREATE PROCEDURE [dbo].[KAAS_GetSettingsDetails] 
	   (
			@mode    VARCHAR(6)  = ''
	   ) 
AS 
/*******************************************************************************************************
* [dbo].[KAAS_GetSettingsDetails]						                                               *
* Description: Used to get EFT status from system options                                              *					  
* Modification History:                                                                                *
* 2021-05-19   Natarajan S        Created															   *
* 2021-05-26   Balamurugan C	  Modified-Added EFT Alert Details 									   *         
* 2022-02-28   Balamurugan.C      Modified - Handled TCL Statements									   *
* 2022-11-04   Ghayathri.S.V      Modified - Removed select statement to fetch EFT Default On 		   *
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON 
   	  BEGIN TRY
		 BEGIN TRAN
			IF(@mode='SELECT')
			BEGIN 

			/*EFT Alert Setting*/
				SELECT [EFTYN] 
				  FROM [dbo].[EFTDetails]
			END

			IF(@mode='UPDATE')
			BEGIN

			/*UPDATE EFT ALERT STATUS*/

				UPDATE [dbo].[EFTDetails] 
				   SET [EFTYN]='Y'

			END
				COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH		
 SET NOCOUNT OFF


END 

GO

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

CREATE PROCEDURE [dbo].[KAAS_GetSupplierLedgerAllocations] (@RecordID INT)
AS
/********************************************************************************************************
 * Returns a list of allocations for the specified supplier ledger record                               *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_GetSupplierLedgerAllocations]                                    *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-07-05   Natarajan S     Created                                                                 *
 * 2021-07-07   Natarajan S     Modified  Added record id                                               *
 * 2021-07-09   Natarajan S     Modified  changed column record id to KeyId,added PRef                  *
 * 2022-01-07   Vinodhkumar.M   Modified  Pref,Against Date Added as a Param,Allocation Table           *
 *                                        inner join with supplier ledger is removed                    *
 * 2024-02-15   John Ginnane    #17689 - Refactored and renamed the procedure                           *
 ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON
    
    SELECT ISNULL(LTRIM(RTRIM([SUP].[CODE])), '')   AS [SupplierCode],
           ISNULL(LTRIM(RTRIM([SUP].[NAME])), '')   AS [SupplierName],
           ISNULL(LTRIM(RTRIM([SPL].[TYPE])), '')   AS [Type],
           [SPL].[DATE]                             AS [Date],
           ISNULL(LTRIM(RTRIM([SPL].[REF])), '')    AS [Ref],
           ISNULL([SPL].[BATCHNO], 0)               AS [BatchNo],
           ISNULL([SPL].[PREF], 0)                  AS [Pref],
           ISNULL(LTRIM(RTRIM([SPL].[NARR])), '')   AS [Narrative],
           ISNULL([SPL].[ORIGINAL], 0)              AS [Original],
           ISNULL([SPL].[OSVALUE], 0)               AS [OSValue],
           [SPL].[ENTRYDATE]                        AS [EntryDate],
           ISNULL(LTRIM(RTRIM([SPL].[Matter])), '') AS [Matter],
           ISNULL([SPL].[RECORDID], 0)              AS [RecordID]
      FROM [dbo].[SupplierLedger] AS [SPL]
           LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
                        ON [SUP].[CODE] = [SPL].[SUPP]
     WHERE [SPL].[RECORDID] = @RecordID

    SELECT ISNULL([ALO].[BATCHNO], 0)                 AS [BatchNo],
           ISNULL([ALO].[PREF], 0)                    AS [Pref],
           [ALO].[DATE]                               AS [AllocationDate],
           [SPL].[DATE]                               AS [TransactionDate],
           ISNULL([ALO].[ABATCHNO], 0)                AS [ABatchNo],
           ISNULL([ALO].[OPREF], 0)                   AS [OPref],
           ISNULL(LTRIM(RTRIM([ALO].[OREF])), '')     AS [ORef],
           ISNULL([ALO].[VALUE], 0)                   AS [Value],
           ISNULL(LTRIM(RTRIM([ALO].[USERCODE])), '') AS [UserCode],
           ISNULL([ALO].[AllNo], 0)                   AS [AllNo],
           ISNULL([ALO].[KEYID], 0)                   AS [KeyID]
      FROM [dbo].[SupplierLedger] AS [SPL]
           INNER JOIN [dbo].[Allocations] AS [ALO]
                   ON [SPL].[BATCHNO] = [ALO].[BATCHNO]
                  AND [SPL].[PREF]    = [ALO].[PREF]
     WHERE [SPL].[RECORDID] = @RecordID

     SET NOCOUNT OFF
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_GetSupplierLedgerDetails] (
       @PageNumber    INT          = 1,
       @PageSize      INT          = 100,
       @SearchString  VARCHAR(500) = '',
       @SortColumn    VARCHAR(100) = 'Supp',
       @SortOrder     VARCHAR(100) = 'ASC',
       @Code          VARCHAR(10)  = '',
       @Flag          VARCHAR(15)  = '')
AS
/********************************************************************************************************
 * Fetches the Supplier Ledger details                                                                  *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_GetSupplierLedgerDetails]                                        *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-06-30    Natarajan S              Created                                                       *
 * 2021-12-29    Balamurugan C            Modified - Added Third Party Balance column in supplier list  *
 * 2021-12-30    Vinodhkumar.M            Modified - Added Matter column in supplier Ledger,            *
 *                                                   balance in Supplier                                *
 * 2022-07-21    Ghayathri.S.V            Modified - To implement dynamic sql query to fetch sort       *
 *                                               and search datas and fetch debtor ledger balances      *
 * 2024-02-09    John Ginnane             Renamed two columns to fix bug as part of #17689              *
 ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON

    /*Supplier LIST*/
    IF @Flag = 'SUPPLIERLIST'
    BEGIN
        SELECT [SUP].[CODE]    AS [Code],
               [SUP].[NAME]    AS [Name],
               [SUP].[TPBAL]   AS [ThirdPartyBalance],
               [SUP].[BALANCE] AS [Balance]
          FROM [dbo].[Suppliers] AS [SUP]
               ORDER BY [SUP].[CODE]
    END

    /*GRID DETAILS FROM SUPPLIER LEDGER*/
    IF @Flag = 'SUPPLIERLEDGER'
    BEGIN
        DECLARE @sql    NVARCHAR(MAX)
        DECLARE @search NVARCHAR(500) = ''
        DECLARE @offset INT = @PageSize * (@PageNumber - 1)
        
        SET @sql = 'SELECT ISNULL(LTRIM(RTRIM([SPL].[SUPP])), '''')    AS [SupplierCode],
                           ISNULL(LTRIM(RTRIM([SUP].[NAME])), '''')    AS [SupplierName],
                           ISNULL(LTRIM(RTRIM([SPL].[TYPE])), '''')    AS [Type],
                           [SPL].[DATE]                                AS [Date],
                           ISNULL(LTRIM(RTRIM([SPL].[REF])), '''')     AS [Ref],
                           ISNULL([SPL].[BATCHNO], 0)                  AS [BatchNo],
                           ISNULL([SPL].[PREF], 0)                     AS [Pref],
                           ISNULL(LTRIM(RTRIM([SPL].[NARR])), '''')    AS [Narrative],
                           ISNULL([SPL].[ORIGINAL], 0)                 AS [Original],
                           ISNULL([SPL].[OSVALUE], 0)                  AS [OSValue],
                           [SPL].[ENTRYDATE]                           AS [EntryDate],
                           ISNULL(LTRIM(RTRIM([SPL].[MATTER])), '''')  AS [Matter],
                           ISNULL([SPL].[RECORDID], 0)                 AS [RecordID]
                      FROM [dbo].[SupplierLedger] AS [SPL]
                           LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
                                        ON [SUP].[CODE] = [SPL].[SUPP]
                     WHERE [SPL].[SUPP] = ''' + @Code  + '''' + 
                      'AND ([SPL].[PREF]     LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[DATE]     LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[RECORDID] LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[REF]      LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[NARR]     LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[SUPP]     LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[BATCHNO]  LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[YEAR]     LIKE ' + '''%' + @SearchString + '%' + '''' +
                        'OR [SPL].[MATTER]   LIKE ' + '''%' + @SearchString + '%' + '''' + ')
                           ORDER BY ' + @SortColumn + ' '  + @SortOrder + ' ' +
                            'OFFSET ' + CAST(@offset   AS NVARCHAR(10)) + ' ROWS ' + 
                        'FETCH NEXT ' + CAST(@PageSize AS NVARCHAR(10)) + ' ROWS ONLY'

        EXEC sp_executesql @sql

        SELECT COUNT(*) AS [TotalRecord]
          FROM [dbo].[SupplierLedger] AS [SPL]
         WHERE [SPL].[SUPP] = @Code      
           AND ([SPL].[PREF]     LIKE '%' + @SearchString + '%'
             OR [SPL].[DATE]     LIKE '%' + @SearchString + '%'
             OR [SPL].[RECORDID] LIKE '%' + @SearchString + '%'
             OR [SPL].[REF]      LIKE '%' + @SearchString + '%'
             OR [SPL].[NARR]     LIKE '%' + @SearchString + '%'
             OR [SPL].[SUPP]     LIKE '%' + @SearchString + '%'
             OR [SPL].[BATCHNO]  LIKE '%' + @SearchString + '%'
             OR [SPL].[YEAR]     LIKE '%' + @SearchString + '%'
             OR [SPL].[MATTER]   LIKE '%' + @SearchString + '%')
    END
END
GO
IF OBJECT_ID(N'KAAS_GetThirdPartyLedgerDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_GetThirdPartyLedgerDetails]
END

GO


CREATE PROCEDURE [dbo].[KAAS_GetThirdPartyLedgerDetails]
(

@SuppCode VARCHAR(10)='',
@Year INT
)
AS

/*******************************************************************************************************
* Fetches the Third party ledger details															   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetThirdPartyLedgerDetails]									   *
* SAMPLE DATA [KAAS_GetThirdPartyLedgerDetails] 'BRADY','2018'										   *                                                                                              *
* Modification History:                                                                                *
* 2021-07-02    Natarajan S		        Created			
* 2022-03-14    Ghayathri.S.V	        Modified where conditiond to fetch Tax No and Service details	*
 *******************************************************************************************************/
BEGIN

		SELECT  
			 [BAT].[BatchNo],
			 [BAT].[Type], 
			 [BAT].[Code], 
			 [BAT].[Pref], 
			 [BAT].[Ref], 
			 [BAT].[Date], 
			 [BAT].[Matter], 
			 [BAT].[Supp], 
			 [BAT].[Narr], 
			 [BAT].[Value], 
			 [BAT].[Posted], 
			 [BAT].[PerNo], 
			 [BAT].[Year], 
			 [BAT].[EntryDate], 
			 [BAT].[RecNo],
			 [BAT].[ChequeReqNo],
			 [SUP].[TaxNo],
			 [SUP].[ServiceCode]
		 FROM 
			 [dbo].[BatchH] [BAT] 
   INNER JOIN
			 [dbo].[Suppliers] [SUP]
		   ON
		     [BAT].[Supp] = [SUP].[Code]
	   WHERE [BAT].[Supp] = @SuppCode 
		AND  [BAT].[Year] = @Year 
		AND  [BAT].[ThirdParty] = 'Y' 
     ORDER BY  
			 [BAT].[Supp] ASC



END

GO



IF  EXISTS 
(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KAAS_GetVATCodes]') AND type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[KAAS_GetVATCodes]
END	
GO

CREATE PROCEDURE [dbo].[KAAS_GetVATCodes]

AS

/*******************************************************************************************************
* Fetches the list of VAT codes                                                                        * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetVATCodes]       											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-03-23    Revathy D        Created                                                               *
* 2024-01-19    Ghayathri.S.V    Updated the select to fetch only unretired VAT codes in Invoice       *
 *******************************************************************************************************/

BEGIN

SELECT	
	   VAC.[CODE] AS Vat,
       VAC.[RATE] AS Rate     
  FROM [dbo].[VATCodes] VAC
  WHERE VAC.RETIRED <> 'Y'
 
ORDER BY  
  VAC.[CODE] ASC


END

GO



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

CREATE PROCEDURE [dbo].[KAAS_GetWorkTypeGroupDropdownList]
AS
/*******************************************************************************************************
* Fetches dropdown list values for worktype group                                                      * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetWorkTypeGroupDropdownList]   	                     		   *
*                                                                                                      *
* Modification History:                                                                                *
* 09 Aug  2021    Natarajan S        Created														   *                                        
 *******************************************************************************************************/
BEGIN
 SET NOCOUNT ON
  SELECT [Code],
         [Description] 
    FROM [dbo].[WorkTypes] 
   WHERE [Retired]='N'

  SELECT  RIGHT(100+[WorkGroup],2)	AS [WorkGroup],
         [GroupOrder],
		 [Description] 
	FROM [WorkGroup1]

  SELECT [WorkGroup2]   AS [WorkGroup2],
         [description2] AS [Description] 
    FROM [dbo].[WorkGroup2]

 SET NOCOUNT OFF
END

GO


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

CREATE PROCEDURE [dbo].[KAAS_GetWorkTypeGroupList] (
@GroupType VARCHAR(30))
AS
/*******************************************************************************************************
* Fetches the work group type                                                                          * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetWorkTypeGroupList] 'typeOfWork1'   	                       *
*                                                                                                      *
* Modification History:                                                                                *
* 05 Aug 2021    Natarajan S        Created														       * 
* 2023-10-19	Vignesh M       Modified   Removed Extra white space in Nominal Reporting Seq  		   *
 *******************************************************************************************************/
BEGIN
 SET NOCOUNT ON

 IF(@GroupType = 'typeOfWorkGroup')
    BEGIN
      SELECT [WTG].[RecordID]						AS [RecordID],
             [WTG].[WorkType]						AS [WorkType],
             LTRIM(RTRIM([WTS].[Desc]))             AS [WorkTypeDescription],
 RIGHT(100 + [WTG].[Group1],2)						AS [Group1],
   		     LTRIM(RTRIM([WG1].[Description]))      AS [G1Description],
   		     [WTG].[Group2]							AS [Group2],
   		     LTRIM(RTRIM([WG2].[Description2]))     AS [G2Description]
        FROM [dbo].[WorkTypeGroupings] [WTG]
   LEFT JOIN [dbo].[WorkGroup2] [WG2]
          ON [WTG].[Group2] = [WG2].[WorkGroup2]
   LEFT JOIN [dbo].[WorkGroup1] [WG1] 
          ON [WTG].[Group1] = [WG1].[WorkGroup]
   LEFT JOIN [dbo].[WorkTypes] [WTS] 
   	   ON [WTG].[WorkType] = [WTS].[Code]
      END


IF(@GroupType = 'typeOfWork1')
BEGIN
SELECT [WorkGroup]					[Group],
       [GroupOrder]					[GroupOrder],
       LTRIM(RTRIM([Description]))  [Description]
  FROM [dbo].[WorkGroup1]

END
IF(@GroupType = 'typeOfWork2')
BEGIN
SELECT [WorkGroup2]					[Group],
       LTRIM(RTRIM([Description2])) [Description]
  FROM [dbo].[WorkGroup2]
END 

 SET NOCOUNT OFF
END

GO

IF  EXISTS 
(SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KAAS_GetWorkTypes]') AND type in (N'P', N'PC'))
BEGIN
DROP PROCEDURE [dbo].[KAAS_GetWorkTypes]
END	
GO
/****** Object:  StoredProcedure [dbo].[KAAS_GetWorkTypes]    Script Date: 11-06-2021 17:46:11 ******/
 
CREATE PROCEDURE [dbo].[KAAS_GetWorkTypes] 
(
@Code varchar(20)
)

AS

/*******************************************************************************************************
* Fetches Work Types Masters					                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_GetWorkTypes]  'ACC'											   *
*                                                                                                      *
* Modification History:                                                                                *
* 11 June 2021    Natarajan S        Created														   *                                          
 *******************************************************************************************************/

BEGIN

SET NOCOUNT ON

 IF(@Code <> '0')
	BEGIN
	SELECT 
		  [Code]		AS [Code],
		  [Description]	AS [Description],
		  [Retired]		AS [Retired]
	  FROM 
		  [dbo].[WorkTypes]
	 WHERE
		  CODE = @Code 
	END
ELSE
	BEGIN
	SELECT 
		  [Code]		AS [Code],
		  [Description]	AS [Description],
		  [Retired]		AS [Retired]
	  FROM 
		  [dbo].[WorkTypes]

	END




		  
		   

SET NOCOUNT OFF

END

GO

IF OBJECT_ID(N'KAAS_Get_ReportId', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_Get_ReportId]
END
GO
CREATE PROCEDURE [dbo].[KAAS_Get_ReportId]
(
 @FileName  VARCHAR(500)
) 
AS
/*******************************************************************************************************
* This SP used to Fetch report Id                                                                      * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_Get_ReportId]   	            								   *
*                                                                                                      *
* Modification History:                                                                                *
* 16 July 2021       Revathy D        Created		
* 15 February 2024	 Nithyanandham.m  Modified	Change table name from CRReport to Kaas_CRReport       *                                          
* 17 April 2024	     Revathy D        Modified	Added a column 'ReportNameKey'                         *                                          
 *******************************************************************************************************/ 
BEGIN
 SET NOCOUNT ON
	SELECT
		   [CRR].[Reportid] As [ReportId],
	       [CRR].[filename] As [FileName],
		   [CRR].[name]     As [ReportName]	
	  FROM 
		   [dbo].[Kaas_CRReport] CRR
	 WHERE 
		   [CRR].[ReportNameKey] = @FileName
 SET NOCOUNT OFF
END
GO




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

CREATE PROCEDURE [dbo].[KAAS_ImportDNDSearchBill] (
       @MATTERCODE  VARCHAR(20),
       @HANDLERCODE VARCHAR(10),
       @XML         NVARCHAR(MAX))
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_ImportDNDSearchBill]                                                                          *
 *                                                                                                           *
 * Performs a synchronisation of data that are either deferred to the night-time (e.g. HandlerNames)         *
 * or data that have become out of sync due to anything unexpected such as a software crash                  *
 * - this will cover the likes of DiaryAttachments v. DiaryAttachmentSelector                                *
 *                                                                                                           *
 * Compatibility information - PLEASE update older versions if necessary to ensure the compatible software   *
 *                                    remains fully functional                                               *
 *   *****************************************************************************************************   *
 *   *                                                                                                   *   *
 *   * Supersedes:                              -                                                        *   *
 *   * First compatible version:                5.8.1.18                                                 *   *
 *   * Last compatible software version:        -                                                        *   *
 *   * Superseded by:                           -                                                        *   *
 *   *                                                                                                   *   *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification History                                                                                      *
 * 2023-11-27  John Ginnane      Created                                                                     *
 * 2024-02-26  Vignesh M         Modified - Restricted duplicate entries                                     *
 * 2024-02-27  Vignesh M         Modified - Batchno returned after batch is created                          *
 *                                                                                                           *
 *************************************************************************************************************/
BEGIN
    SET NOCOUNT ON;
    SET QUOTED_IDENTIFIER ON;
    SET DATEFORMAT dmy;

    DECLARE @AUTOPOST          BIT
    DECLARE @DEFAULTSUPPLIER   VARCHAR(10)
    DECLARE @DEFAULTOUTLAYCODE VARCHAR(10)
    DECLARE @TODAY             DATETIME
    DECLARE @YEAR              INT
    DECLARE @PERIOD            INT
    DECLARE @PERIODEND         DATETIME
    DECLARE @EICONVERT         DECIMAL(9, 6)
    DECLARE @OUTLAY            VARCHAR(10)
    DECLARE @idoc              INT

    DECLARE @UseBranches       BIT
    DECLARE @Branch            VARCHAR(10)

    SELECT @YEAR      = [CON].[YEAR],
           @PERIOD    = [CON].[CURPER],
           @PERIODEND = DATEADD(DAY, [CON].[PERIODEND], '18001228'),
           @EICONVERT = 0.787564, -- This is hard coded in clarion code
           @OUTLAY    = [CON].[OUTLAY],
           @TODAY     = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
           @UseBranches = CASE WHEN ISNULL([CON].[INDICATOR22], '') = 'Y'
                                    THEN 1
                               ELSE 0 END
      FROM [dbo].[control] AS [CON]

    SELECT @PERIODEND = ISNULL(@PERIODEND, @TODAY),
           @YEAR      = ISNULL(@YEAR, YEAR(@TODAY)),
           @PERIOD    = ISNULL(@PERIOD, MONTH(@PERIOD))
  
    SELECT @AUTOPOST          = CASE WHEN [SET].[KeyName] = 'DNDSearchBillAutoPost'
                                      AND ISNULL([SET].[KeyValue], '') IN ('Y', 'true', '1')
                                          THEN 1
                                     ELSE ISNULL(@AUTOPOST, 0) END,
           @DEFAULTSUPPLIER   = CASE WHEN [SET].[KeyName] = 'DNDSearchBillDefaultSupplier'
                                          THEN ISNULL([SET].[KeyValue], '')
                                     ELSE ISNULL(@DEFAULTSUPPLIER, '') END,
           @DEFAULTOUTLAYCODE = CASE WHEN [SET].[KeyName] = 'DNDSearchBillDefaultOutlayCode'
                                          THEN ISNULL([SET].[KeyValue], '')
                                     ELSE ISNULL(@DEFAULTOUTLAYCODE, '') END
      FROM [dbo].[Settings] AS [SET]
     WHERE [SET].[KeyName] = 'DNDSearchBillAutoPost'
        OR [SET].[KeyName] = 'DNDSearchBillDefaultSupplier'
        OR [SET].[KeyName] = 'DNDSearchBillDefaultOutlayCode'
    
    IF ISNULL(@UseBranches, 0) = 1
    BEGIN
        SELECT @Branch = ISNULL([MAT].[Branch], '')
          FROM [dbo].[matters] AS [MAT]
         WHERE [MAT].[Code] = @MATTERCODE
    END
    ELSE
    BEGIN
        SET @Branch = ''
    END
    
    DECLARE @HEADERS TABLE (
            [id]                 INT          IDENTITY(1, 1) PRIMARY KEY,
            [BatchNo]            INT          DEFAULT(0),
            [PostRef]            INT          DEFAULT(0),

            [Batch]              INT,
            [TransactionType]    VARCHAR(1),
            [Code]               VARCHAR(10),
            [Branch]             VARCHAR(10),
            [Ref]                VARCHAR(10),
            [Date]               DATETIME,
            [Fee]                VARCHAR(10),
            [Matter]             VARCHAR(20),
            [Supp]               VARCHAR(10),
            [Narr]               VARCHAR(100),
            [ClientAc]           VARCHAR(1),
            [UserCode]           VARCHAR(10),
            [HandlerCode]        VARCHAR(10),
            [EntryDate]          DATETIME,

            [Value]              DECIMAL(19, 2), -- Gross
            [SubTotal]           DECIMAL(19, 2), -- Also gross
            [VATTotal]           DECIMAL(19, 2), -- VAT
            
            [Year]               INT,
            [Period]             INT)

    DECLARE @DETAILS TABLE (
            [id]              INT         IDENTITY(1, 1) PRIMARY KEY,
            [LineNo]          INT,
            [BatchNo]         INT         DEFAULT(0),
            [PostRef]         INT         DEFAULT(0),

            [Batch]           INT,
            [TransactionType] VARCHAR(1),
            [LineType]        VARCHAR(1),
            [Code]            VARCHAR(10),
            [Ref]             VARCHAR(10),
            [Date]            DATETIME,
            [Fee]             VARCHAR(10),
            [Branch]          VARCHAR(10),
            [Narr]            VARCHAR(100),
            [Matter]          VARCHAR(20),
            [Supp]            VARCHAR(10),
            [Value]           DECIMAL(19, 2), -- Net Value
            [VATCode]         VARCHAR(1),
            [VATValue]        DECIMAL(19, 2), -- VAT value
            [OutlayCode]      VARCHAR(10),
            [ClientAc]        VARCHAR(1),
            [Deposit]         VARCHAR(1))
    
    BEGIN TRY
    EXEC sp_xml_preparedocument @idoc OUTPUT, @XML
    END TRY
    BEGIN CATCH
    EXEC sp_xml_preparedocument @idoc OUTPUT, '<invoice/>'
    END CATCH

    -- Make sure the XML file fits our expected format:
    -- root node = "invoice"
    -- node contains attributes:
    --    1. Date
    --    2. "InvoiceNo
    -- node also contains one of these attributes:
    --    1. TotalONV
    --    2. TotalOWV
    --    3. TotalSWV
    --    4. TotalVAT
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM OPENXML(@idoc, 'invoice', 2)
                     WITH ([Date]            VARCHAR(50)    '@Date',
                           [InvoiceNo]       VARCHAR(50)    '@InvoiceNo',
                           [TotalONV]        DECIMAL(19, 2) '@TotalONV',     -- Total Outlay Non-VATable
                           [TotalOWV]        DECIMAL(19, 2) '@TotalOWV',     -- Total Outlay VATable (excl. VAT)
                           [TotalOverall]    DECIMAL(19, 2) '@TotalOverall', -- Gross
                           [TotalSWV]        DECIMAL(19, 2) '@TotalSWV',     -- Services VATable (excl. VAT)
                           [TotalVAT]        DECIMAL(19, 2) '@TotalVAT'      -- Total VAT
                           ) AS [XML]
                    WHERE [XML].[Date] IS NOT NULL
                      AND [XML].[InvoiceNo] IS NOT NULL
                      AND ([XML].[TotalONV] IS NOT NULL
                        OR [XML].[TotalOWV] IS NOT NULL
                        OR [XML].[TotalSWV] IS NOT NULL
                        OR [XML].[TotalVAT] IS NOT NULL))
    BEGIN
        RETURN
    END

    INSERT INTO @DETAILS (
           [Batch],
           [TransactionType],
           [LineType],
           [Code],
           [Ref],
           [Date],
           [Fee],
           [Branch],
           [Narr],
           [Matter],
           [Supp],
           [Value],
           [VATCode],
           [VATValue],
           [OutlayCode],
           [ClientAc],
           [Deposit])
    SELECT ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY [Date] ASC) AS [Batch],
           'B'                                                   AS [Type],
           'O'                                                   AS [LineType], -- OUTLAY column
           ISNULL(@OUTLAY, '')                                   AS [Code],
           LEFT([XML].[InvoiceNo], 10)                           AS [Ref],
           CASE WHEN [XML].[Date] LIKE '%[1-2][0-9][0-9][0-9][0-1][0-9][0-3][0-9]%'
                     THEN CONVERT(DATETIME, [XML].[Date], 112)
                ELSE @TODAY END                                  AS [Date],
           ''                                                    AS [Fee],
           @Branch                                               AS [Branch],
           'Bill from ' + ISNULL([SUP].[NAME], '')               AS [Narrative],
           ISNULL(@MATTERCODE, '')                               AS [Matter],
           ISNULL(@DEFAULTSUPPLIER, '')                          AS [Supplier],
           ISNULL([XML].[TotalONV], 0) + ISNULL([XML].[TotalOWV], 0) + ISNULL([XML].[TotalSWV], 0) + ISNULL([XML].[TotalVAT], 0) AS [Net],
           'E'                                                   AS [VATCode], -- Hard code 'E' for exempt
           0                                                     AS [VAT], -- VAT from purchase bill is added to GROSS, and we don't claim it here
           ISNULL(@DEFAULTOUTLAYCODE, '')                        AS [OutlayCode],
           'N'                                                   AS [ClientAc],
           'N'                                                   AS [Deposit]
      FROM OPENXML(@idoc, 'invoice', 2)
      WITH ([Date]            VARCHAR(50)    '@Date',
            [InvoiceNo]       VARCHAR(50)    '@InvoiceNo',
            [TotalONV]        DECIMAL(19, 2) '@TotalONV',     -- Total Outlay Non-VATable
            [TotalOWV]        DECIMAL(19, 2) '@TotalOWV',     -- Total Outlay VATable (excl. VAT)
            [TotalOverall]    DECIMAL(19, 2) '@TotalOverall', -- Gross
            [TotalSWV]        DECIMAL(19, 2) '@TotalSWV',     -- Services VATable (excl. VAT)
            [TotalVAT]        DECIMAL(19, 2) '@TotalVAT',     -- Total VAT

            [Total_Gross]     DECIMAL(19, 2) '@Total_Gross',  -- Gross (again?)
            [Total_Net]       DECIMAL(19, 2) '@Total_Net',    -- Net (outlay non-VATable + outlay VATable + services?)
            [Total_ONV]       DECIMAL(19, 2) '@Total_ONV',    -- Total Outlay Non-VATable (again?)
            [Total_OWV]       DECIMAL(19, 2) '@Total_OWV',    -- Total Outlay VATable (excl. VAT) (again?)
            [Total_SWV]       DECIMAL(19, 2) '@Total_SWV',    -- Total Services VATable (excl. VAT) (again?)
            [Total_Vat]       DECIMAL(19, 2) '@Total_Vat',    -- Total VAT (again?)
            [VATRate]         DECIMAL(19, 2) '@VATRate'       -- Need to try find a VAT code for this rate
            ) AS [XML]
           LEFT OUTER JOIN [dbo].[VATCodes] AS [VAT]
                        ON [VAT].[RATE] = [XML].[VATRate]
           LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
                        ON [SUP].[CODE] = @DEFAULTSUPPLIER
                    
    INSERT INTO @HEADERS (
           [Batch],
           [TransactionType],
           [Code],
           [Branch],
           [Ref],
           [Date],
           [Fee],
           [Matter],
           [Supp],
           [Narr],
           [ClientAc],
           [UserCode],
           [HandlerCode],
           [EntryDate],
           [Value],
           [SubTotal],
           [VATTotal])
    SELECT [DET].[Batch]                              AS [Batch],
           'B'                                        AS [TransactionType],
           ''                                         AS [Code],
           @Branch                                    AS [Branch],
           MIN([DET].[Ref])                           AS [Reference],
           MIN([DET].[Date])                          AS [Date],
           ''                                         AS [Fee],
           ISNULL(@MATTERCODE, '')                    AS [MatterCode],
           ISNULL(@DEFAULTSUPPLIER, '')               AS [Supplier],
           MAX([DET].[Narr])                          AS [Narrative],
           'Y'                                        AS [ClientAc],
           'KEYHOUSE'                                 AS [UserCode], -- We don't link handler code to clarion user, so hardcode KEYHOUSE
           @HANDLERCODE                               AS [HandlerCode],
           @TODAY                                     AS [EntryDate],
           SUM([DET].[Value])                         AS [Value], -- Detail line already contains GROSS so don't add VAT again
           SUM([DET].[Value])                         AS [SubTotal],
           SUM([DET].[VATValue])                      AS [VATTotal]
      FROM @DETAILS AS [DET]
           GROUP BY [DET].[Batch]
           
    EXEC sp_xml_removedocument @idoc

	IF EXISTS (
		SELECT TOP 1 1
		  FROM [BatchH] AS [BAT]
			   INNER JOIN @DETAILS AS [DET]
					   ON [BAT].[MATTER] = [DET].[Matter]
					  AND [BAT].[REF]    = [DET].[Ref]
					  AND [BAT].[Supp]   = @DEFAULTSUPPLIER
					  AND [BAT].[TYPE]   = 'B')
	BEGIN
		SELECT '-1' [BatchNo]
        RETURN
    END
    
    -- A lot of this code was taken from ky_NETImportTransactionXML

    -- Fill in Line Numbers to help with error reporting
    ;WITH [CTE] ([Batch], [id], [LineNumber]) AS (
    SELECT [DET].[Batch],
           [DET].[id],
           ROW_NUMBER() OVER (PARTITION BY [DET].[Batch]
                                  ORDER BY [DET].[id] ASC)
      FROM @DETAILS AS [DET])
    UPDATE [DET]
       SET [DET].[LineNo] = [CTE].[LineNumber]
      FROM @DETAILS AS [DET]
           INNER JOIN [CTE]
                   ON [DET].[id] = [CTE].[id]

    -- Prepare batch and pref numbers
    DECLARE @LastBatchNo INT
    DECLARE @LastPostRef INT

    SELECT @LastBatchNo = [T].[BATCHNO],
           @LastPostRef = [T].[PREF],
           @TODAY       = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
      FROM [dbo].[ky_NETTFGetLastBatchNoAndPostRef]() AS [T]

    ;WITH [CTE] ([id], [NewBatchNo], [NewPostRef]) AS (
    SELECT [HED].[id],
           @LastBatchNo + ROW_NUMBER() OVER (ORDER BY [HED].[Batch], [HED].[id]),
           @LastPostRef + ROW_NUMBER() OVER (ORDER BY [HED].[Batch], [HED].[id])
      FROM @HEADERS AS [HED])
    UPDATE [HED]
       SET [HED].[BatchNo] = [CTE].[NewBatchNo],
           [HED].[PostRef] = [CTE].[NewPostRef]
      FROM @HEADERS AS [HED]
           INNER JOIN [CTE]
                   ON [CTE].[id] = [HED].[id]

    SELECT @LastPostRef = MAX([HED].[PostRef])
      FROM @HEADERS AS [HED]

    ;WITH [CTE] ([id], [NewBatchNo], [NewPostRef]) AS (
    SELECT [DET].[id],
           [HED].[BatchNo],
           @LastPostRef + ROW_NUMBER() OVER (ORDER BY [DET].[Batch], [DET].[id])
      FROM @DETAILS AS [DET]
           INNER JOIN @HEADERS AS [HED]
                   ON [HED].[Batch] = [DET].[Batch])
    UPDATE [DET]
       SET [DET].[BatchNo] = [CTE].[NewBatchNo],
           [DET].[PostRef] = [CTE].[NewPostRef]
      FROM @DETAILS AS [DET]
           INNER JOIN [CTE]
                   ON [CTE].[id] = [DET].[id]
                       
    UPDATE [HED]
       SET [HED].[Year]   = @YEAR,
           [HED].[Period] = @PERIOD
      FROM @HEADERS AS [HED]
    
    -- Insert into BatchH
    INSERT INTO [dbo].[BatchH]  (
           [BATCHNO],
           [POSTFWD],
           [TYPE],
           [CODE],
           [BRANCH],
           [PREF],
           [REF],
           [DATE],
           [FEE],
           [MATTER],
           [SUPP],
           [NARR],
           [VALUE],
           [SUBTOT],
           [POSTED],
           [CLIENTAC],
           [PERNO],
           [YEAR],
           [PAYEE],
           [OUTLAYTOT],
           [VATTOT],
           [FEETOT],
           [INVCR],
           [THIRDPARTY],
           [USERCODE],
           [ENTRYDATE],
           [CLIENTBANK],
           [CURRENCY],
           [CURRENCYVALUE],
           [CUROUTLAYTOT],
           [CURVATTOT],
           [CURFEETOT],
           [RECNO],
           [SINGLELINE],
           [TEMPLATE],
           [CHEQUEREQNO],
           [WRITEDOWN],
           [WRITEBACKHOURS],
           [WRITEBACKVALUE],
           [CORRECTCOPY],
           [CreditInvoiceNo],
           [DraftBillNo],
           [EFTSent],
           [EFTDate],
           [EFTFileNumber],
           [EFTFileName],
           [EFTYorN],
           [ClientCode],
           [PayClient],
           [OnceOffPayment],
           [CaseAssCode],
           [EFTEmailYorN],
           [HandlerCode],
           [PaymentMethod],
           [ClearedDate])
    SELECT [HED].[BatchNo],    /* BATCHNO */
           '',   /* POSTFWD */
           [HED].[TransactionType],   /* TYPE */
           [HED].[Code],   /* CODE */
           [HED].[Branch],   /* BRANCH */
           [HED].[PostRef],    /* PREF */
           [HED].[Ref],   /* REF */
           [HED].[Date], /* DATE */
           [HED].[Fee],   /* FEE */
           [HED].[Matter],   /* MATTER */
           [HED].[Supp],   /* SUPP */
           [HED].[Narr],   /* NARR */
           [HED].[Value],    /* VALUE */
           [HED].[SubTotal],    /* SUBTOT */
           'N',   /* POSTED */
           [HED].[ClientAc],   /* CLIENTAC */
           [HED].[Period],    /* PERNO */
           [HED].[Year],    /* YEAR */
           '',   /* PAYEE */
           0,    /* OUTLAYTOT */
           [HED].[VATTotal],    /* VATTOT */
           0,    /* FEETOT */
           'I',   /* INVCR */
           '',   /* THIRDPARTY */
           [HED].[UserCode],   /* USERCODE */
           [HED].[EntryDate], /* ENTRYDATE */
           '',   /* CLIENTBANK */
           '',   /* CURRENCY */
           [HED].[Value] * -@EICONVERT,    /* CURRENCYVALUE - Minus for some reason in desktop app! */
           0,    /* CUROUTLAYTOT */
           [HED].[VATTotal] * @EICONVERT,    /* CURVATTOT */
           0,    /* CURFEETOT */
           0,    /* RECNO */
           '',   /* SINGLELINE */
           '',   /* TEMPLATE */
           0,    /* CHEQUEREQNO */
           NULL, /* WRITEDOWN */
           0,    /* WRITEBACKHOURS */
           0,    /* WRITEBACKVALUE */
           '',   /* CORRECTCOPY */
           0,    /* CreditInvoiceNo */
           0,    /* DraftBillNo */
           'N',   /* EFTSent */
           NULL, /* EFTDate */
           0,    /* EFTFileNumber */
           '',   /* EFTFileName */
           'N',   /* EFTYorN */
           '',   /* ClientCode */
           'N',   /* PayClient */
           'N',   /* OnceOffPayment */
           '',   /* CaseAssCode */
           'N',   /* EFTEmailYorN */
           [HED].[HandlerCode],   /* HandlerCode */
           0,    /* PaymentMethod */
           NULL /* ClearedDate */
      FROM @HEADERS AS [HED]
     WHERE [HED].[BatchNo] > 0

    INSERT INTO [dbo].[BatchDetails] (
           [BATCHNO],
           [TYPE],
           [CODE],
           [PREF],
           [REF],
           [DATE],
           [FEE],
           [BRANCH],
           [NARR],
           [MATTER],
           [SUPP],
           [VALUE],
           [VATCODE],
           [VATVAL],
           [CLIENTYN],
           [OUTLAY],
           [PENDING],
           [YEAR],
           [PERNO],
           [ENTRYCURRENCY],
           [CURRENCYVALUE],
           [CURRENCYVAT],
           [OUTLAYCODE],
           [THIRDPARTY],
           [PAYEE],
           [HEADPREF],
           [HEADBATCH],
           [ALLOCBATCH],
           [ALLOCPREF],
           [ALLOCREF],
           [ALLOCVALUE],
           [ALLOCWRITEOFF],
           [PSUPP],
           [UNDETAKING],
           [CaseAssCode],
           [OnceOffPayment],
           [PayClient],
           [ClientCode],
           [EFTEmailYorN],
           [RegisteredPost],
           [PreBilledOutlay])
    SELECT [DET].[BatchNo],    /* BATCHNO */
           [HED].[TransactionType],   /* TYPE */
           [DET].[Code],   /* CODE */
           [DET].[PostRef],    /* PREF */
           [DET].[Ref],   /* REF */
           ISNULL([DET].[Date], [HED].[Date]), /* DATE */
           [DET].[Fee],   /* FEE */
           [DET].[Branch],   /* BRANCH */
           [DET].[Narr],   /* NARR */
           [DET].[Matter],   /* MATTER */
           '', --[DET].[Supp],   /* SUPP - Apparently this is left blank when transactions entered manually */ 
           [DET].[Value],    /* VALUE */
           [DET].[VATCode],   /* VATCODE */
           [DET].[VATValue],    /* VATVAL */
           '',   /* CLIENTYN */
           [DET].[LineType],   /* OUTLAY */
           '',   /* PENDING */
           [HED].[Year],    /* YEAR */
           [HED].[Period],    /* PERNO */
           'E',   /* ENTRYCURRENCY */
           [DET].[Value] * @EICONVERT,    /* CURRENCYVALUE */
           [DET].[VATValue] * @EICONVERT,    /* CURRENCYVAT */
           [DET].[OutlayCode],   /* OUTLAYCODE */
           '',   /* THIRDPARTY */
           '',   /* PAYEE */
           0,    /* HEADPREF */
           0,    /* HEADBATCH */
           0,    /* ALLOCBATCH */
           0,    /* ALLOCPREF */
           '',   /* ALLOCREF */
           0,    /* ALLOCVALUE */
           '',   /* ALLOCWRITEOFF */
           '',   /* PSUPP */
           0,    /* UNDETAKING */
           '',   /* CaseAssCode */
           'N',   /* OnceOffPayment */
           'N',   /* PayClient */
           '',   /* ClientCode */
           'N',   /* EFTEmailYorN */
           0,    /* RegisteredPost */
           0    /* PreBilledOutlay */
      FROM @HEADERS AS [HED]
           INNER JOIN @DETAILS AS [DET]
                   ON [HED].[Batch] = [DET].[Batch]
     WHERE [DET].[BatchNo] > 0

    SELECT @LastBatchNo = [T].[BATCHNO],
           @LastPostRef = [T].[PREF]
      FROM [dbo].[ky_NETTFGetLastBatchNoAndPostRef]() AS [T]

    UPDATE [CON]
       SET [CON].[LASTBATCH] = @LastBatchNo,
           [CON].[LASTPREF]  = @LastPostRef
      FROM [dbo].[control] AS [CON]

    -- Try to auto-post if option is turned on
    IF @AUTOPOST = 1 AND OBJECT_ID(N'KAAS_UpdatePostingSAMPurchaseBill', N'P') IS NOT NULL
    BEGIN
        DECLARE @I         INT
        DECLARE @N         INT
        DECLARE @BATCHNO_W INT
        DECLARE @POSTFWD   VARCHAR(1)

        SELECT @I = 1,
               @N = ISNULL(MAX([HED].[id]), 0)
          FROM @HEADERS AS [HED]

        WHILE @I <= @N
        BEGIN
            SET @BATCHNO_W = NULL
            SET @POSTFWD   = NULL

            SELECT @BATCHNO_W = [HED].[BatchNo],
                   @POSTFWD   = CASE WHEN [HED].[Date] > @PERIODEND THEN 'Y' ELSE 'N' END
              FROM @HEADERS AS [HED]
             WHERE [HED].[id] = @I

            EXEC [dbo].[KAAS_UpdatePostingSAMPurchaseBill] @BATCHNO_W, @POSTFWD, @HANDLERCODE

            SET @I = @I + 1
        END
        
    END
	SELECT TOP 1 [DET].[BatchNo]
	  FROM @DETAILS AS [DET]
     WHERE [DET].[BatchNo] > 0
END
GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_ImportOutlayIssueInvoice' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_ImportOutlayIssueInvoice] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_ImportOutlayIssueInvoice]
	( 
		@BatchNo       INT,
		@Date	       DATETIME,
		@Matter		   VARCHAR(20),
		@NextPeriodEnd DATETIME,
		@SingleLine	   VARCHAR(1) = ''
	)
AS
 /*******************************************************************************************************
 * Import Outlay inserting issue invoice batch detail logic                                             * 
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_ImportOutlayIssueInvoice]   			            	            *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2022-11-16    Ghayathri.S.V        Created                                                           *
 * 2024-03-14    Balamurugan.C        Modified - Added logic for Single Line process, if single line is *
												 checked we to sum all the outlay of other batches      *
												 and convert into single outlay record					*
 * 2024-03-22    Vignesh M            Modified - Narrative text is changed								*
 *******************************************************************************************************/
 BEGIN
 	BEGIN TRY
		BEGIN TRAN

			DECLARE @VATEXCLUDE         CHAR(1)
            DECLARE @IECONVERT          DECIMAL(17,6)
            DECLARE @CURRENTYEAR        INT
            DECLARE @CURRENTPERIOD      INT
			DECLARE @NEWPREF            INT
			DECLARE @SUMOFVALUE		    DECIMAL(19, 2)
			DECLARE @SUMOFCURRENCYVALUE DECIMAL(19, 2)
			DECLARE @SINGLELINEREF		VARCHAR(10)
			DECLARE @DEFAULTOUTLAY		VARCHAR(10)



			SELECT @IECONVERT      = [CON].[IECONVERT],
                   @VATEXCLUDE     = [CON].[VATEXCLUDE],
                   @CURRENTYEAR    = [CON].[YEAR],
                   @CURRENTPERIOD  = [CON].[CURPER],
				   @DEFAULTOUTLAY  = [CON].[OUTLAY] 
             FROM  [dbo].[control] AS [CON]



IF(@SingleLine='N')
	BEGIN

		  DECLARE @Ref             VARCHAR(10),					
				  @Narr            VARCHAR(100),				
				  @Value           DECIMAL(17, 2),
				  @CurrencyValue   DECIMAL(17, 2)				

		  DECLARE importOutlay_Cursor CURSOR FOR

          SELECT @BatchNo,
                 [BAH].[REF],
                 @Date,
                 [BAH].[NARR],
                 [MAT].[VALUEO],
                 CONVERT(DECIMAL(19, 2),[MAT].VALUEO * @IECONVERT)
		    FROM MatterLedger [MAT]
			JOIN BatchH [BAH]
			 ON  [BAH].BATCHNO = [MAT].BATCHNO
			AND  [BAH].TYPE <> 'I'
		  WHERE  [MAT].MATTER = @Matter
		    AND  [MAT].VALUEO<>0 
			AND  [MAT].[BILLINGDATE] IS NULL
			AND  (([BAH].[POSTFWD] = 'Y' AND [MAT].[DATE] <> @NextPeriodEnd ) OR [MAT].[FEE] <> '')

			OPEN importOutlay_Cursor
		  
		  FETCH 
	  NEXT FROM importOutlay_Cursor
		  INTO  @BatchNo,                    
			    @Ref,             
			    @Date,                    
			    @Narr,         
			    @Value,
			    @CurrencyValue

		WHILE @@FETCH_STATUS = 0
		BEGIN
			(
			  SELECT @NEWPREF = (LastPref + 1)
			    FROM [dbo].[Control] WITH(NOLOCK)
	        )

	/* INSERT INTO ISSUE INVOICE BATCH DETAIL */
   INSERT INTO [dbo].[BatchDetails] (
                           [BATCHNO],
                           [TYPE],
                           [CODE],
                           [PREF],
                           [REF],
                           [DATE],
                           [FEE],
                           [BRANCH],
                           [NARR],
                           [MATTER],
                           [SUPP],
                           [VALUE],
                           [VATCODE],
                           [VATVAL],
                           [CLIENTYN],
                           [OUTLAY],
                           [PENDING],
                           [YEAR],
                           [PERNO],
                           [ENTRYCURRENCY],
                           [CURRENCYVALUE],
                           [CURRENCYVAT],
                           [OUTLAYCODE],
                           [THIRDPARTY],
                           [PAYEE],
                           [HEADPREF],
                           [HEADBATCH],
                           [ALLOCBATCH],
                           [ALLOCPREF],
                           [ALLOCREF],
                           [ALLOCVALUE],
                           [ALLOCWRITEOFF],
                           [PSUPP],
                           [UNDETAKING],
                           [CaseAssCode],
                           [OnceOffPayment],
                           [PayClient],
                           [ClientCode],
                           [EFTEmailYorN],
                           [RegisteredPost],
                           [PreBilledOutlay])
	    VALUES			   (@BatchNo,       /*BATCHNO*/                                                    
                            'I',		    /*TYPE*/
                            'OUTLAY',	    /*CODE*/
                            @NEWPREF,	    /*PREF*/
                            @Ref,	        /*REF*/
                            @Date,		    /*DATE*/
                            '',			    /*FEE*/
                            '',		        /*BRANCH*/
                            @Narr,		    /*NARR*/
                            '',             /*MATTER*/
							'',             /*SUPP*/
                            @Value,         /*VALUE*/
                            @VATEXCLUDE,    /*VATCODE*/
                            0.00,           /*VATVAL*/
                            '',             /*CLIENTYN*/
                            'O',            /*OUTLAY*/
                            '',             /*PENDING*/
                            @CURRENTYEAR,   /*YEAR*/
                            @CURRENTPERIOD, /*PERNO*/
                            'E',		    /*ENTRYCURRENCY*/
                            @CurrencyValue, /*CURRENCYVALUE*/
                            0.00,           /*CURRENCYVAT*/
                            '',				/*OUTLAYCODE*/
                            '',				/*THIRDPARTY*/
                            '',				/*PAYEE*/
                            0,				/*HEADPREF*/
                            0,				/*HEADBATCH*/
                            0,				/*ALLOCBATCH*/
                            0,				/*ALLOCPREF*/
                            '',				/*ALLOCREF*/
                            0.00,			/*ALLOCVALUE*/
                            '',				/*ALLOCWRITEOFF*/
                            '',				/*PSUPP*/
                            0,				/*UNDETAKING*/
                            '',				/*CASEASSCODE*/
                            'N',			/*ONCEOFFPYMENT*/
                            'N',			/*PAYCLIENT*/
                            '',				/*CLIENTCODE*/
                            'N',			/*EFTEMAILYorN*/
                            0,				/*REGISTEREDPOST*/
                            0)				/*PREBILLEDOUTLAY*/

		/*UPDATE AND SELECT PREF FOR BATCH DETAILS*/
	    UPDATE [dbo].[Control] 
		   SET [LASTPREF] = (@NEWPREF) 
	     WHERE [NEXT_DOC_NO] = 0  

		 FETCH 
	 NEXT FROM importOutlay_Cursor
		  INTO @BatchNo,                    
			   @Ref,             
			   @Date,                    
			   @Narr,         
			   @Value,
			   @CurrencyValue
	      END
	    CLOSE importOutlay_Cursor;
   DEALLOCATE importOutlay_Cursor;





   END
ELSE
	BEGIN
		 SELECT @SUMOFVALUE			= SUM([MAT].[VALUEO]),
				@SUMOFCURRENCYVALUE = CONVERT(DECIMAL(19, 2),SUM([MAT].VALUEO) * @IECONVERT)
				FROM MatterLedger [MAT]
				JOIN BatchH [BAH]
				 ON  [BAH].BATCHNO = [MAT].BATCHNO
				AND  [BAH].TYPE <> 'I'
			  WHERE  [MAT].MATTER = @Matter
				AND  [MAT].VALUEO<>0 
				AND  [MAT].[BILLINGDATE] IS NULL
				AND  (([BAH].[POSTFWD] = 'Y' AND [MAT].[DATE] <> @NextPeriodEnd ) OR [MAT].[FEE] <> '')

	 SELECT @SINGLELINEREF = [Ref] FROM [dbo].[BatchH] WHERE [BatchNo] = @BatchNo

	SELECT @NEWPREF = (LastPref + 1)
		FROM [dbo].[Control] WITH(NOLOCK)

	/* INSERT INTO ISSUE INVOICE BATCH DETAIL */
   INSERT INTO [dbo].[BatchDetails] (
                           [BATCHNO],
                           [TYPE],
                           [CODE],
                           [PREF],
                           [REF],
                           [DATE],
                           [FEE],
                           [BRANCH],
                           [NARR],
                           [MATTER],
                           [SUPP],
                           [VALUE],
                           [VATCODE],
                           [VATVAL],
                           [CLIENTYN],
                           [OUTLAY],
                           [PENDING],
                           [YEAR],
                           [PERNO],
                           [ENTRYCURRENCY],
                           [CURRENCYVALUE],
                           [CURRENCYVAT],
                           [OUTLAYCODE],
                           [THIRDPARTY],
                           [PAYEE],
                           [HEADPREF],
                           [HEADBATCH],
                           [ALLOCBATCH],
                           [ALLOCPREF],
                           [ALLOCREF],
                           [ALLOCVALUE],
                           [ALLOCWRITEOFF],
                           [PSUPP],
                           [UNDETAKING],
                           [CaseAssCode],
                           [OnceOffPayment],
                           [PayClient],
                           [ClientCode],
                           [EFTEmailYorN],
                           [RegisteredPost],
                           [PreBilledOutlay])
	    VALUES			   (@BatchNo,				/*BATCHNO*/                                                    
                            'I',					/*TYPE*/
                            @DEFAULTOUTLAY,			/*CODE*/
                            @NEWPREF,				/*PREF*/
                            @SINGLELINEREF,		    /*REF*/
                            @Date,					/*DATE*/
                            '',						/*FEE*/
                            '',						/*BRANCH*/
                            'Total Outlays',		/*NARR*/
                            '',						/*MATTER*/
							'',						/*SUPP*/
                            @SUMOFVALUE,			/*VALUE*/
                            @VATEXCLUDE,			/*VATCODE*/
                            0.00,					/*VATVAL*/
                            '',						/*CLIENTYN*/
                            'O',					/*OUTLAY*/
                            '',						/*PENDING*/
                            @CURRENTYEAR,			/*YEAR*/
                            @CURRENTPERIOD,			/*PERNO*/
                            'E',					/*ENTRYCURRENCY*/
                            @SUMOFCURRENCYVALUE,	/*CURRENCYVALUE*/
                            0.00,					/*CURRENCYVAT*/
                            '',						/*OUTLAYCODE*/
                            '',						/*THIRDPARTY*/
                            '',						/*PAYEE*/
                            0,						/*HEADPREF*/
                            0,						/*HEADBATCH*/
                            0,						/*ALLOCBATCH*/
                            0,						/*ALLOCPREF*/
                            '',						/*ALLOCREF*/
                            0.00,					/*ALLOCVALUE*/
                            '',						/*ALLOCWRITEOFF*/
                            '',						/*PSUPP*/
                            0,						/*UNDETAKING*/
                            '',						/*CASEASSCODE*/
                            'N',					/*ONCEOFFPYMENT*/
                            'N',					/*PAYCLIENT*/
                            '',						/*CLIENTCODE*/
                            'N',					/*EFTEMAILYorN*/
                            0,						/*REGISTEREDPOST*/
                            0)						/*PREBILLEDOUTLAY*/

	/*UPDATE AND SELECT PREF FOR BATCH DETAILS*/
	    UPDATE [dbo].[Control] 
		   SET [LASTPREF] = (@NEWPREF) 
	     WHERE [NEXT_DOC_NO] = 0 


	END

		COMMIT TRAN

	END TRY

 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
 END CATCH

 END
GO

IF OBJECT_ID(N'KAAS_InsertContactCategory', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertContactCategory]
END
GO
CREATE PROCEDURE [dbo].[KAAS_InsertContactCategory] 
	(
		@CatType	  VARCHAR(6)  = '',
		@Code		  VARCHAR(10) = '',
		@Mode		  VARCHAR(20) = '',
		@Description  VARCHAR(30) = '',
		@Prompt1	  VARCHAR(20) = '',
		@Prompt2	  VARCHAR(20) = '',
		@Prompt3	  VARCHAR(20) = '',
		@Prompt4	  VARCHAR(20) = '',
		@Prompt5	  VARCHAR(20) = '',
		@Prompt6	  VARCHAR(20) = '',
		@Prompt7	  VARCHAR(20) = '',
		@Prompt8	  VARCHAR(20) = '',
		@Prompt9	  VARCHAR(20) = '',
		@Prompt10	  VARCHAR(20) = ''
	)
/*******************************************************************************************************
*                                                                                                       *
* Stored Procedure Name	: [dbo].[KAAS_InsertContactCategory]											*
* Copied from			: NA																			*
*                                                                                                       *
* Modification History	:                                                                               *
* 2021-06-14	Balamurugan C		Created	
* 2022-03-03	Ghayathri.S.V		Script Modified for Insert and Edit								
*******************************************************************************************************/
AS
BEGIN
				IF( @Mode = 'EDIT' )
					BEGIN
						IF EXISTS (
									SELECT TOP 1 1
									  FROM  [dbo].[Category]
									  WHERE [Code]    = @Code
								  )
							BEGIN 
								UPDATE [dbo].[Category]
								   SET [CatType]  = @CatType,
									   [Desc$]	  = @Description,
						               [Prompt1]  = @Prompt1,
						               [Prompt2]  = @Prompt2,
						               [Prompt3]  = @Prompt3,
						               [Prompt4]  = @Prompt4,
						               [Prompt5]  = @Prompt5,
						               [Prompt6]  = @Prompt6,
						               [Prompt7]  = @Prompt7,
						               [Prompt8]  = @Prompt8,
						               [Prompt9]  = @Prompt9,
						               [Prompt10] = @Prompt10
					            WHERE  [Code]     = @Code
							END
					END
				IF ( @Mode = 'INSERT')
					BEGIN
						IF NOT EXISTS (
									SELECT TOP 1 1
									  FROM  [dbo].[Category]
									  WHERE [Code]    = @Code
								  )
							BEGIN
								INSERT 
								  INTO	[dbo].[Category]
										(
										[Code],      
										[CatType],
										[Desc$],
										[Prompt1],
										[Prompt2],
										[Prompt3],
										[Prompt4],
										[Prompt5],
										[Prompt6],
										[Prompt7],
										[Prompt8],
										[Prompt9],
										[Prompt10]
										)
							   VALUES   (  
										@Code,				/*[Code]*/
										@CatType,			/*[CatType]*/
										@Description,		/*[Desc$]*/
										@Prompt1,			/*[Prompt1]*/
										@Prompt2,			/*[Prompt2]*/	
										@Prompt3,			/*[Prompt3]*/
										@Prompt4,			/*[Prompt4]*/
										@Prompt5,			/*[Prompt5]*/
										@Prompt6,			/*[Prompt6]*/
										@Prompt7,			/*[Prompt7]*/
										@Prompt8,			/*[Prompt8]*/
										@Prompt9,			/*[Prompt9]*/
										@Prompt10			/*[Prompt10]*/
										)
							END
					END
				IF ( @Mode = 'DELETE')
					BEGIN
						IF EXISTS (
									SELECT TOP 1 1
									  FROM  [dbo].[Category]
									  WHERE [Code]    = @Code
								  )
						DELETE 
						FROM	[dbo].[Category]
						WHERE   [Code]    = @Code 
					      AND   [CatType] = @CatType
				    END
END
GO




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

CREATE PROCEDURE [dbo].[KAAS_InsertDebtorsLedgerAllocation] (
       @ReceiptRecordID INT,
       @InvoiceRecordID INT,
       @VALUE           DECIMAL(17, 2),
       @FEES            DECIMAL(17, 2),
       @OUTLAY          DECIMAL(17, 2),
       @VAT             DECIMAL(17, 2),
       @UserCode        VARCHAR(30),
       @DATE            DATETIME,
       @Result          TINYINT OUTPUT)
AS
/*******************************************************************************************************
 * Used to insert debtors ledger allocation                                                            *
 * Stored Procedure Name: [dbo].[KAAS_InsertDebtorsLedgerAllocation]                                   *
 *                                                                                                     *
 * Modification History:                                                                               *
 * 2021-07-09   Natarajan S        Created                                                             *
 * 2021-07-12   Natarajan S        Modified  Allocation ID from control table.                         *
 * 2022-03-08   Balamurugan.C      Modified - Handled TCL Statements and Formatting                    *
 * 2023-11-28   John Ginnane       #17504 - Removing time component from date and refactored code      *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    -- Make sure receipt exists
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[DebtorsLedger] AS [DTL]
                    WHERE [DTL].[RECORDID] = @ReceiptRecordID)
    BEGIN
        SET @Result = 0
        RETURN
    END

    -- Make sure invoice exists
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[DebtorsLedger] AS [DTL]
                    WHERE [DTL].[RECORDID] = @InvoiceRecordID)
    BEGIN
        SET @Result = 0
        RETURN
    END

    BEGIN TRY
        BEGIN TRANSACTION
        
        DECLARE @AllNo INT
        DECLARE @TODAY DATETIME

        -- Get today's date only
        SET @TODAY = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

        -- Check both [dbo].[control] AND [dbo].[Allocations]
        SELECT TOP 1
               @AllNo = ISNULL([CON].[LastAlloc], 0) + 1
          FROM [dbo].[control] AS [CON]

        SELECT TOP 1 @AllNo = CASE WHEN ISNULL(MAX([ALO].[AllNo]), 0) > @AllNo
                                        THEN ISNULL(MAX([ALO].[AllNo]), 0)
                                   ELSE ISNULL(@AllNo, 0) END
          FROM [dbo].[Allocations] AS [ALO]
      
        -- Use a common table expression (CTE) to combine 
        -- data from both rows into a single row then use a
        -- UNION to get two rows with data from both rows
        ;WITH [CombinedData] ([AllNo],
                              [InvoiceBatchNo],
                              [InvoicePostRef],
                              [InvoiceRef],
                              [InvoiceVATCode],
                              [ReceiptBatchNo],
                              [ReceiptPostRef],
                              [ReceiptRef],
                              [ReceiptVATCode],
                              [Date],
                              [Value],
                              [Fees],
                              [Outlay],
                              [VAT],
                              [UserCode]) AS (
        SELECT @AllNo,
               [INV].[BATCHNO],
               [INV].[PREF],
               [INV].[REF],
               [INV].[VATCODE],
               [REC].[BATCHNO],
               [REC].[PREF],
               [REC].[REF],
               [REC].[VATCODE],
               @TODAY,
               @VALUE,
               @FEES,
               @OUTLAY,
               @VAT,
               @UserCode
         FROM [dbo].[DebtorsLedger] [INV]
              CROSS APPLY [dbo].[DebtorsLedger] [REC]
        WHERE [INV].[RECORDID] = @InvoiceRecordID
          AND [REC].[RECORDID] = @ReceiptRecordID)

        INSERT INTO [dbo].[Allocations] (
               [BATCHNO],
               [PREF],
               [DATE],
               [ABATCHNO],
               [OPREF],
               [OREF],
               [VALUE],
               [FEES],
               [OUTLAY],
               [VAT],
               [USERCODE],
               [AllNo],
               [VATCODE])
               -- Invoice side
        SELECT [CD].[InvoiceBatchNo],  /* BATCHNO */
               [CD].[InvoicePostRef],  /* PREF */
               [CD].[Date],            /* DATE */
               [CD].[ReceiptBatchNo],  /* ABATCHNO */
               [CD].[ReceiptPostRef],  /* OPREF */
               [CD].[ReceiptRef],      /* OREF */
               [CD].[Value],           /* VALUE */
               [CD].[Fees],            /* FEES */
               [CD].[Outlay],          /* OUTLAY */
               [CD].[VAT],             /* VAT */
               [CD].[UserCode],        /* USERCODE */
               [CD].[AllNo],           /* AllNo */
               [CD].[ReceiptVATCode]   /* VATCODE */
          FROM [CombinedData] AS [CD]
               UNION ALL
               -- Receipt side
        SELECT [CD].[ReceiptBatchNo],  /* BATCHNO */
               [CD].[ReceiptPostRef],  /* PREF */
               [CD].[Date],            /* DATE */
               [CD].[InvoiceBatchNo],  /* ABATCHNO */
               [CD].[InvoicePostRef],  /* OPREF */
               [CD].[InvoiceRef],      /* OREF */
               [CD].[Value],           /* VALUE */
               [CD].[Fees],            /* FEES */
               [CD].[Outlay],          /* OUTLAY */
               [CD].[VAT],             /* VAT */
               [CD].[UserCode],        /* USERCODE */
               [CD].[AllNo],           /* AllNo */
               [CD].[InvoiceVATCode]   /* VATCODE */
          FROM [CombinedData] AS [CD]
        
        UPDATE [INV]
           SET [INV].[OSValue]  = [INV].[OSValue]  + @VALUE,
               [INV].[OSFees]   = [INV].[OSFees]   + @FEES,
               [INV].[OSOUTLAY] = [INV].[OSOutlay] + @OUTLAY,
               [INV].[OSVAT]    = [INV].[OSVat]    + @VAT
          FROM [dbo].[DebtorsLedger] [INV]
         WHERE [INV].[RECORDID]  = @InvoiceRecordID

        UPDATE [REC]
           SET [REC].[OSValue]  = [REC].[OSValue]  - @VALUE,
               [REC].[OSFees]   = [REC].[OSFees]   - @FEES,
               [REC].[OSOUTLAY] = [REC].[OSOutlay] - @OUTLAY,
               [REC].[OSVAT]    = [REC].[OSVat]    - @VAT
          FROM [dbo].[DebtorsLedger] [REC]
         WHERE [REC].[RECORDID]  = @ReceiptRecordID
 
        UPDATE [CON]
           SET [CON].[LastAlloc] = @AllNo
          FROM [dbo].[control] AS [CON]

        SET @Result = 1
        
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        SET @Result = 0

        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_InsertDeleteNominalLedgerComments' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_InsertDeleteNominalLedgerComments] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_InsertDeleteNominalLedgerComments] 
    (
		@Date		  DATETIME	   = NULL,
		@Narr		  VARCHAR(100) = '',
		@Code		  VARCHAR(10)  = '',
		@Ref		  VARCHAR(10)  = '',
		@Year		  INT		   = 0,
		@RecordId	  INT		   = 0,
		@Mode		  VARCHAR(20)  = 'INSERT',
		@User         VARCHAR(20)  = '',
		@EntryDate    DATE         = NULL
	)
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_InsertDeleteNominalLedgerComments]							   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-07-28	Balamurugan C		Created															   *
* 2022-03-03	Balamurugan C		Modified - Handled TCL Statements   and formatting                 *
*******************************************************************************************************/
AS
BEGIN
	SET NOCOUNT ON
	 BEGIN TRY
        BEGIN TRAN
			IF( @Mode = 'INSERT' )
				BEGIN
					   SET @EntryDate   = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](GETDATE(),   @User)), 0)
					   SET @Date        = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date,       @User)), 0)

					   INSERT 
						 INTO [dbo].[NominalLedger]
								  (
									[Code],
									[BatchNo],
									[Pref],
									[Date],
									[Narr],
									[Ref],
									[Value],
									[CurrencyValue],
									[Year],
									[EntryDate]
								  )
					   VALUES     ( 
									@Code,                  /*[Code]*/
									0,						/*[BatchNo]*/
									0,						/*[Pref]*/
									@Date,					/*[Date]*/
									@Narr,					/*[Narr]*/
									@Ref,					/*[Ref]*/
									0.00,					/*[Value]*/
									0.00,					/*[CurrencyValue]*/
									@Year,					/*[Year]*/
									@EntryDate          	/*[EntryDate]*/
								   )
				END
			ELSE
				BEGIN
					   DELETE 
						 FROM [dbo].[NominalLedger]
						WHERE [RecordID] = @RecordId
				END
	    	COMMIT TRAN

		 END TRY
		 BEGIN CATCH
				DECLARE @ErrorMsg      NVARCHAR(4000), 
						@ErrorSeverity INT,
						@ErrorState    INT; 

				 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
						@ErrorSeverity = ERROR_SEVERITY(), 
						@ErrorState    = ERROR_STATE()

			  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

				 IF @@TRANCOUNT > 0  
					BEGIN
						ROLLBACK TRANSACTION;
					END   
		 END CATCH
	SET NOCOUNT OFF
END
GO


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

GO
/****** Object:  StoredProcedure [dbo].[KAAS_InsertDeleteSuppliersDetails]    Script Date: 6/17/2021 6:19:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[KAAS_InsertDeleteSuppliersDetails] (
	@Code				VARCHAR(10)='',
	@Name				VARCHAR(40)='',
	@Address			VARCHAR(500)='',
	@Phone				VARCHAR(50)='',
	@EmailAddress		VARCHAR(100)='',
	@TaxNo				VARCHAR(15)='',
	@ServiceCode		VARCHAR(6)='',
	@VATNo				VARCHAR(20)='',
	@DeftpStatus		VARCHAR(1)='',
	@BankName			VARCHAR(60)='',
	@BankAddress		VARCHAR(120)='',
	@BankSortCode		VARCHAR(20)='',
	@BankAccNo			VARCHAR(20)='',
	@Iban				VARCHAR(34)='',
	@Bic				VARCHAR(20)='',
	@BankType			VARCHAR(1)='',
	@EFTEmailAddress	VARCHAR(150)='',
	@Retired			VARCHAR(1)='',
	@Mode			 	VARCHAR(20)='',
	@Nominal			VARCHAR(40)=''
	)
/*******************************************************************************************************
*                                                                                                       *
* Stored Procedure Name	: [dbo].[KAAS_InsertDeleteSuppliersDetails]										*
* Copied from			: NA																			*
*                                                                                                       *
* Modification History	:                                                                               *
* 2021-06-16	Balamurugan C		Created	
* 2021-02-28	Ghayathri.S.V		Modified to check validations before delete
* 2024-01-19	Revathy.D		    Included Nominal field in add/edit                                  *
*******************************************************************************************************/
AS
BEGIN
	DECLARE @deleteCount INT = 0
    IF( @Mode = 'EDIT' )
      BEGIN
          IF EXISTS (
					  SELECT TOP 1 1
                      FROM   dbo.[Suppliers]
                      WHERE  [code] = @Code
					)
            BEGIN
                UPDATE dbo.[Suppliers]
				SET
					[Code]				=	@Code,
					[Name]				=	@Name,
					[Address]			=	@Address,
					[Phone]				=	@Phone,
					[EmailAddress]		=	@EmailAddress,
					[TaxNo]				=	@TaxNo,
					[ServiceCode]		=	@ServiceCode,
					[VATNo]				=	@VATNo,
					[DeftpStatus]		=	@DeftpStatus,
					[BankName]			=	@BankName,
					[BankAddress]		=	@BankAddress,		
					[BankSortCode]		=	@BankSortCode,
					[BankAccNo]			=	@BankAccNo,
					[Iban]				=	@Iban,
					[Bic]				=	@Bic,	
					[BankType]			=	@BankType,
					[EFTEmailAddress]	=	@EFTEmailAddress,
					[Retired]			=	@Retired,
					[Nominal]           =   @Nominal

                WHERE  [Code] = @Code
            END
		END
    IF( @Mode = 'INSERT' )
	  BEGIN
          IF NOT EXISTS (
					  SELECT TOP 1 1
                      FROM   dbo.[Suppliers]
                      WHERE  [code] = @Code
					)
            BEGIN
                INSERT INTO dbo.[Suppliers]
                            (
								[Code],				
								[Name],				
								[Address],			
								[Phone],				
								[EmailAddress],		
								[TaxNo],				
								[ServiceCode],		
								[VATNo],				
								[DeftpStatus],		
								[BankName],			
								[BankAddress],		
								[BankSortCode],		
								[BankAccNo],			
								[Iban],				
								[Bic],				
								[BankType],			
								[EFTEmailAddress],	
								[Retired],
								[Nominal]			
							)
                VALUES     ( 
								@Code,				/*[Code]*/
								@Name,				/*[Name]*/
								@Address,			/*[Address]*/
								@Phone,				/*[Phone]*/
								@EmailAddress,		/*[EmailAddress]*/
								@TaxNo,				/*[TaxNo]*/
								@ServiceCode,		/*[ServiceCode]*/
								@VATNo,				/*[VATNo]*/
								@DeftpStatus,		/*[DeftpStatus]*/
								@BankName,			/*[BankName]*/
								@BankAddress,		/*[BankAddress]*/		
								@BankSortCode,		/*[BankSortCode]*/
								@BankAccNo,			/*[BankAccNo]*/
								@Iban,				/*[Iban]*/
								@Bic,				/*[Bic]*/
								@BankType,			/*[BankType]*/
								@EFTEmailAddress,	/*[EFTEmailAddress]*/
								@Retired,			/*[Retired]*/
								@Nominal			/*[Nominal]*/
							 )
            END
      END
    IF( @Mode = 'VALIDATE')
	  BEGIN

		SET @deleteCount = 
					(
						SELECT COUNT(1) 
						  FROM	[dbo].[Suppliers]	    SUP
						  JOIN	[dbo].[SupplierLedger]	SUPL
						  ON	SUP.[CODE] = SUPL.[SUPP]
						  WHERE	SUP.[Code] = @Code
					)

					IF(@deleteCount > 0)
						BEGIN
								SELECT 'Postings Present'	AS [Message]
						END
					ELSE 
						BEGIN
							SELECT 'Postings Not Present' AS [Message]
						END
			
		END
	IF( @Mode = 'DELETE' )
			BEGIN 
				 DELETE 
				   FROM  dbo.[Suppliers]
				   WHERE [Code] = @Code
			END
END

GO


IF OBJECT_ID(N'KAAS_InsertSAMAccruals', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertSAMAccruals]
END
GO
CREATE PROCEDURE 
	   [dbo].[KAAS_InsertSAMAccruals]
 (
	@NominalAc   VARCHAR(10),
	@AccrualAc   VARCHAR(10),
	@Description VARCHAR(40),
	@Value       DECIMAL,
	@ValueYTD    DECIMAL,
	@RecordId    INT
 )
AS 
/*******************************************************************************************************
* [dbo].[KAAS_InsertSAMAccruals]                                                                          *
* Description: Used to post accrual details                                                             *					  
* Modification History:                                                                                *
* 2021-08-04   Revathy D        Created							                                       *      
*******************************************************************************************************/
BEGIN 
 SET NOCOUNT ON  
 IF ISNULL(@RecordId, 0) = 0
    BEGIN
        INSERT INTO [dbo].[Accruals] (
               [NOMINALFROM],
               [NOMINALTO],
               [DESCRIPTION],
               [VALUE],
               [VALUEYTD])
        SELECT @NominalAc,
               @AccrualAc,
               @Description,
               @Value,
               @ValueYTD
    END
    ELSE
    BEGIN
       UPDATE [dbo].[Accruals]
          SET [NOMINALFROM]  = @NominalAc,
              [NOMINALTO]    = @AccrualAc,
              [DESCRIPTION]  = @Description,
              [VALUE]        = @Value,
              [VALUEYTD]     = @ValueYTD
        WHERE [RECORDID]     = @RecordId
    END 
 SET NOCOUNT OFF
END 
GO



IF EXISTS (SELECT TOP 1 1 
           FROM   sys.[objects] SO 
           WHERE  SO.[name] = N'KAAS_INSERTSAMDiaryDetails' 
                  AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_INSERTSAMDiaryDetails] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_INSERTSAMDiaryDetails] 
	(
			@MatterCode		   VARCHAR(20),
			@Priority		   VARCHAR(5),
			@Highlighted	   VARCHAR(20),
			@Publisher		   VARCHAR(20),
			@Status			   INT,
			@ActionCode		   VARCHAR(20),
			@ActionStatus	   VARCHAR(20),
			@ActionType		   VARCHAR(20),
			@ProcessType	   VARCHAR(20),
			@FNCode			   VARCHAR(20),
			@TeamCode		   VARCHAR(20),
			@Text1			   VARCHAR(MAX),
			@Date			   DATETIME,
			@diaryWarningDate  DATETIME,
			@Handler           VARCHAR(10),
			@Result	           INT OUTPUT
	) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].[KAAS_INSERTSAMDiaryDetails]		'000001/0000','H','','N',0,'ADMUD','NA','U','I','ADM','COM','UNDERTAKING EXAMPLE',0					 * 
  * Modification History:                                                                                *
  * 2021-03-26 Natarajan S        Created																 *
  * 2022-03-08 Balamurugan.C      Modified - Handled TCL Statements and Formatting                       *           
   *******************************************************************************************************/
  BEGIN 
   BEGIN TRY 
	 BEGIN TRANSACTION

		  DECLARE @TIMECONVERT   INT
		  DECLARE @IdentityValue INT
		      SET @TIMECONVERT   = [dbo].[KAAS_ConvertTimeToClarion](GETDATE())
             EXEC @IdentityValue = [dbo].[KAAS_GetNextActionID]
		   INSERT 
		     INTO [dbo].[diary] 
				( [ActionID],
				  [CASECODE],
				  [PRIORITY],
				  [HIGHLIGHTED],
				  [PUBLISH],
				  [DATE],
				  [STATUS],
				  [ACTIONCODE],
				  [ACTIONSTATUS],
				  [ACTIONTYPE],
				  [PROCESSTYPE],
				  [FNCODE],
				  [TEAMCODE],
				  [TEXT1],
				  [TEXT2],
				  [DELEGATEDFNR],
				  [DELEGATEDDATE],
				  [DELEGATEDBACKDATE],
				  [DEFERRED],
				  [DUEDATE],
				  [IMAGENO],
				  [DYSTARTTIME],
				  [DYENDTIME],
				  [DURATION],
				  [ORGINALACTIONID],
				  [MILESTEONETYPE],
				  [ATTACHMENTS],
				  [PROCESSSTATUS],
				  [WORKPROCESS],
				  [BILLABLE],
				  [BILLDESCRIPTION],
				  [EMAILADDRESS],
				  [EMAIL],
				  [SUBJECT],
				  [DELEGATIONSTATUS],
				  [DRAFTBILLNO],
				  [CHEQUEREQNO],
				  [TXMSENT],
				  [LOCATION],
				  [HEARINGTYPE],
				  [FORCOPY],
				  [TXMDATE],
				  [TXMSEQNO],
				  [DISPLAYTEXT],
				  [FLAG],
				  [ADDRESSTO],
				  [CCTO],
				  [BCCTO],
				  [CLIENTCONTACTID],
				  [CONTACTCATEGORY],
				  [CAMPAIGN],
				  [FILENUM],
				  [CASEASSOCIATE]
		    ) 
		   VALUES
		    (
				  @IdentityValue,																							/*[ActionID]*/
				  @MatterCode, 																								/*[CASECODE]*/
				  @Priority,																								/*[PRIORITY]*/
				  @Highlighted,																								/*[HIGHLIGHTED]*/
				  @Publisher,																								/*[PUBLISH]*/
				  DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@diaryWarningDate, @Handler)), 0),			/*[DATE]*/
				  @Status,																									/*[STATUS]*/
				  @ActionCode,																								/*[ACTIONCODE]*/
				  @ActionStatus,																							/*[ACTIONSTATUS]*/
				  @ActionType,																								/*[ACTIONTYPE]*/
				  @ProcessType,																								/*[PROCESSTYPE]*/
				  @FNCode,																									/*[FNCODE]*/
				  @TEAMCODE,																								/*[TEAMCODE]*/
				  @TEXT1,																									/*[TEXT1]*/
				  NULL,																										/*[TEXT2]*/
				  NULL,																										/*[DELEGATEDFNR]*/
				  NULL,																										/*[DELEGATEDDATE]*/
				  NULL,																										/*[DELEGATEDBACKDATE]*/
				  NULL,																										/*[DEFERRED]*/
				  DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0),						/*[DUEDATE]*/
				  0,																										/*[IMAGENO]*/
				  @TIMECONVERT,																								/*[DYSTARTTIME]*/
				  @TIMECONVERT,																								/*[DYENDTIME]*/
				  NULL,																										/*[DURATION]*/
				  @IdentityValue,																							/*[ORGINALACTIONID]*/
				  'JP',																										/*[MILESTEONETYPE]*/
				  'N',																										/*[ATTACHMENTS]*/
				  0,																										/*[PROCESSSTATUS]*/
				  NULL,																										/*[WORKPROCESS]*/
				  0,																										/*[BILLABLE]*/
				  '',																										/*[BILLDESCRIPTION]*/
				  NULL,																										/*[EMAILADDRESS]*/
				  NULL,																										/*[EMAIL]*/
				  '',																										/*[SUBJECT]*/
				  0,																										/*[DELEGATIONSTATUS]*/
				  0,																										/*[DRAFTBILLNO]*/
				  NULL,																										/*[CHEQUEREQNO]*/
				  0,																										/*[TXMSENT]*/
				  NULL,																										/*[LOCATION]*/
				  NULL,																										/*[HEARINGTYPE]*/
				  NULL,																										/*[FORCOPY]*/
				  NULL,																										/*[TXMDATE]*/
				  NULL,																										/*[TXMSEQNO]*/
				  @TEXT1,																									/*[DISPLAYTEXT]*/
				  NULL,																										/*[FLAG]*/
				  NULL,																										/*[ADDRESSTO]*/
				  NULL,																										/*[CCTO]*/
				  NULL,																										/*[BCCTO]*/
				  NULL,																										/*[CLIENTCONTACTID]*/
				  NULL,																										/*[CONTACTCATEGORY]*/
				  NULL,																										/*[CAMPAIGN]*/
				  0,																										/*[FILENUM]*/
				  NULL																										/*[CASEASSOCIATE]*/
			 )

	       INSERT 
	         INTO [dbo].[DiaryDelegations]
			 (    [ACTIONID],
				  [HANDLER],
				  [TEAM],
				  [DATE],
				  [TIME],
				  [DATER],
				  [TIMER],
				  [DUEDATE],
				  [DUETIME],
				  [REVIEW],
				  [STATUS],
				  [OWNER],
				  [DELEGATE],
				  [DELEGATESTATUS],
				  [ACTIONTYPE],
				  [FROMHANDLER],
				  [RETURNEDBY],
				  [DELTYPE]
			 )
		   VALUES 
			 (    @IdentityValue,                                  /*[ACTIONID]*/
				  @FNCode,										   /*[HANDLER]*/
				  @TeamCode,									   /*[TEAM]*/
				  CONVERT(DATETIME, @diaryWarningDate ,112),	   /*[DATE]*/
				  @TIMECONVERT,									   /*[TIME]*/
				  NULL,											   /*[DATER]*/
				  '',											   /*[TIMER]*/
				  CONVERT(DATETIME, @Date ,112),				   /*[DUEDATE]*/
				  @TIMECONVERT,									   /*[DUETIME]*/
				  ' ',											   /*[REVIEW]*/
				  0,											   /*[STATUS]*/
				  'Y',											   /*[OWNER]*/
				  'JP',											   /*[DELEGATE]*/
				  0,											   /*[DELEGATESTATUS]*/
				  'U',											   /*[ACTIONTYPE]*/
				  'JP',											   /*[FROMHANDLER]*/
				  '',											   /*[RETURNEDBY]*/
				  'Created'										   /*[DELTYPE]*/
			 )
		       SET @Result = @IdentityValue

    	 COMMIT TRANSACTION                      
	END TRY
	BEGIN CATCH
				SET @Result = 0
			DECLARE @ErrorMsg      NVARCHAR(4000), 
					@ErrorSeverity INT,
					@ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

		  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
				 IF @@TRANCOUNT > 0  
					BEGIN
						ROLLBACK TRANSACTION;
					END     
	END CATCH
	
  END 

GO


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

go 

CREATE PROCEDURE 
	   [dbo].[KAAS_INSERTSAMMatterLedgerComment] 
	  (@MatterCode  VARCHAR(20),
	   @Narrative   VARCHAR(MAX),
	   @ClientMin   FLOAT,
	   @Date        DATETIME,
	   @HandlerCode VARCHAR(20),
	   @Result	    TINYINT OUTPUT) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].[KAAS_INSERTSAMMatterLedgerComment]									 * 
  * Modification History:                                                                                *
  * 2021-03-26 Natarajan S        Created																 *  
  * 2021-07-08 Natarajan S        Modified - Formatting Added.											 *
  * 2022-03-08 Balamurugan.C      Modified - Handled TCL Statements                                      *     
  * 2023-05-09 Vignesh M          Modified - Logged in Handler code is added                             *     
  ********************************************************************************************************/
  BEGIN 
   	  BEGIN TRY
		BEGIN TRAN
			  INSERT 
				INTO [dbo].[MatterLedger]
				  (  [Matter],
					 [BatchNo],
					 [PRef],
					 [Date],
					 [Ref],
					 [Narr],
					 [ValueD],
					 [ValueO],
					 [ValueC],
					 [Fee],
					 [Per],
					 [Year],
					 [EntryDate],
					 [Client],
					 [ValueCC],
					 [ValueCD],
					 [DepositType],
					 [CurValueD],
					 [CurValueO],
					 [CurValueC],
					 [CurValueCC],
					 [CurValueCD],
					 [Billed],
					 [BillingYear],
					 [BillingPeriod],
					 [BillingDate],
					 [BilledOutlayValue],
					 [InvoiceNo],
					 [IncludeInBill]
				  )
			  VALUES  
			      (  @MatterCode,       /*[Matter]*/
					 0,					/*[BatchNo]*/
					 0,					/*[PRef]*/
					 @Date,				/*[Date]*/
					 @HandlerCode,		/*[Ref]*/
					 @Narrative,		/*[Narr]*/
					 0.00,				/*[ValueD]*/
					 0.00,				/*[ValueO]*/
					 0.00,				/*[ValueC]*/
					 '',				/*[Fee]*/
					 0,					/*[Per]*/
					 0,					/*[Year]*/
					 GETDATE(),			/*[EntryDate]*/
					 '',				/*[Client]*/
					 0.00,				/*[ValueCC]*/
					 0.00,				/*[ValueCD]*/
					 '',				/*[DepositType]*/
					 0.00,				/*[CurValueD]*/
					 0.00,				/*[CurValueO]*/
					 0.00,				/*[CurValueC]*/
					 0.00,				/*[CurValueCC]*/
					 0.00,				/*[CurValueCD]*/
					 '',				/*[Billed]*/
					 0,					/*[BillingYear]*/
					 0,					/*[BillingPeriod]*/
					 NULL,				/*[BillingDate]*/
					 0.00,				/*[BilledOutlayValue]*/
					 0,					/*[InvoiceNo]*/
					 0					/*[IncludeInBill]*/
				  )

				 SET @Result = 1

			  UPDATE [OMO]
				 SET [OMO].[ClientMin] = @ClientMin
				FROM [dbo].[OpenMattersOnly] [OMO]
			   WHERE [OMO].[Code] = @MatterCode 


			  COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH
  END 

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

GO

CREATE PROCEDURE [dbo].[KAAS_INSERTSAMUndertakingDetails] (
			     @MatterCode                VARCHAR(20),
			     @Seq                       INT,
			     @Type                      VARCHAR(10),
			     @Details                   VARCHAR(MAX),
			     @Who                       VARCHAR(MAX),
			     @ActionID                  INT,
			     @GivenOrReceived           VARCHAR(10),
			     @DealingNumber             VARCHAR(10),
			     @Notes                     VARCHAR(MAX),
			     @CommercialOrNonCommerical VARCHAR(10),
			     @Status                    VARCHAR(50),
			     @Value                     DECIMAL,
			     @AuthorizedByFE            VARCHAR(10),
			     @UndertakingTo             VARCHAR(10),
			     @Date                      DATETIME,
			     @Handler                   VARCHAR(10),
				 @AddCommentLedger			BIT,
			     @Result	                TINYINT OUTPUT
                 ) 
AS 
  /********************************************************************************************************************************************************
  *Used to list the matter ledger                                                                                                                         *
  * Stored Procedure Name: [dbo].[KAAS_INSERTSAMUndertakingDetails]																	    				  * 
  * Modification History:                                                                                                                                 *
  * 26 MAR 2021 Natarajan S        Created																                                                  * 
  * 13 JUL 2021 Natarajan S        Created																                                                  *
  * 03 DEC 2021 Vinodhkumar M      Modified - Added add comment Ledger field							                                                  *
  * 08 Mar 2022 Balamurugan.C      Modified - Handled TCL Statements and Formatting                                                                       *     
   ********************************************************************************************************************************************************/
 BEGIN TRY 
  BEGIN TRANSACTION
   DECLARE @CurrentDate DATETIME;
       SET @CurrentDate				  = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](GETDATE(), @Handler)), 0)
       SET @Type                      = SUBSTRING(@Type, 1, 1)
       SET @GivenOrReceived			  = SUBSTRING(@GivenOrReceived, 1, 1)
       SET @CommercialOrNonCommerical = SUBSTRING(@CommercialOrNonCommerical, 1, 1)
                
    INSERT 
      INTO [dbo].[Undertakings] 
    	  ([MATTER],
    	   [SEQ],
    	   [DISCHARGEDATE],
    	   [TYPE],
    	   [DESCRIPTION],
    	   [WHO],
    	   [ACTIONID],
    	   [GIVENORRECEIVED],
    	   [NOTIFIED],
    	   [DISCHARGEDESCRIPTION],
    	   [DISCHARGEDBY],
    	   [DEALINGNUMBER],
    	   [NOTES],
    	   [COMMERCIALORNON],
    	   [STATUS],
    	   [DATE],
    	   [UNDDATE],
    	   [VALUE],
    	   [UNDVALUE],
    	   [AUTHORISEDBYFE],
    	   [HANDLER],
    	   [UNDERTAKINGTO],
    	   [CASECONTACT],
    	   [CATEGORY],
    	   [ISCONDITIONAL],
    	   [CONDITION],
    	   [NEEDSATTENTION],
		   [AddCommentLedger]) 
   VALUES (@MatterCode,                                                                               /*[MATTER]*/
    	   @Seq,												                                      /*[SEQ]*/
    	   NULL,												                                      /*[DISCHARGEDATE]*/
    	   @Type,												                                      /*[TYPE]*/
    	   @Details,											                                      /*[DESCRIPTION]*/
    	   @Who,												                                      /*[WHO]*/
    	   @ActionID,											                                      /*[ACTIONID]*/
    	   @GivenOrReceived,									                                      /*[GIVENORRECEIVED]*/
    	   ' ',													                                      /*[NOTIFIED]*/
    	   '',													                                      /*[DISCHARGEDESCRIPTION]*/
    	   '',													                                      /*[DISCHARGEDBY]*/
    	   @DealingNumber,										                                      /*[DEALINGNUMBER]*/
    	   @Notes,												                                      /*[NOTES]*/
    	   @CommercialOrNonCommerical,							                                      /*[COMMERCIALORNON]*/
    	   @Status,												                                      /*[STATUS]*/
    	   DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0),		  /*[DATE]*/
    	   DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0),		  /*[UNDDATE]*/
    	   @Value,												                                      /*[VALUE]*/
    	   @Value,												                                      /*[UNDVALUE]*/
    	   @AuthorizedByFE,										                                      /*[AUTHORISEDBYFE]*/
    	   @AuthorizedByFE,										                                      /*[HANDLER]*/
    	   @UndertakingTo,										                                      /*[UNDERTAKINGTO]*/
    	   @UndertakingTo,										                                      /*[CASECONTACT]*/
    	   '',													                                      /*[CATEGORY]*/
    	   0,													                                      /*[ISCONDITIONAL]*/
    	   '',													                                      /*[CONDITION]*/
    	   0,													                                      /*[NEEDSATTENTION]*/
		   @AddCommentLedger)									                                      /*[AddCommentLedger]*/
    SET @Result = 1
 COMMIT TRANSACTION                      
END TRY
BEGIN CATCH
	    SET @Result = 0
	DECLARE @ErrorMsg      NVARCHAR(4000), 
			@ErrorSeverity INT,
			@ErrorState    INT; 

	 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
			@ErrorSeverity = ERROR_SEVERITY(), 
			@ErrorState    = ERROR_STATE()

  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END   
END CATCH

GO

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

CREATE PROCEDURE [dbo].[KAAS_InsertSupplierLedgerAllocation] (
       @BillRecordID    INT,
       @PaymentRecordID INT,
       @VALUE           DECIMAL(17, 2),
       @DATE            DATETIME,
       @UserCode        VARCHAR(30),
       @Result          TINYINT         OUTPUT)
AS
/********************************************************************************************************
 * Used to insert supplier ledger allocation                                                            *
 * Stored Procedure Name: [dbo].[KAAS_InsertSupplierLedgerAllocation]                                   *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-07-09   Natarajan S        Created                                                              *
 * 2021-07-12   Natarajan S        Modified  Allocation ID from control table.                          *
 * 2022-02-25   Ghayathri.S.V      Modified  Insert Logic by adding two where clauses.                  *
 * 2022-02-28   Balamurugan.C      Modified - Handled TCL Statements                                    *
 * 2024-02-01   John Ginnane       #17658 - Refactored code                                             *
 ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    -- Make sure bill exists
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[SupplierLedger] AS [SPL]
                    WHERE [SPL].[RECORDID] = @BillRecordID)
    BEGIN
        SET @Result = 0
        RETURN
    END

    -- Make sure payment exists
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[SupplierLedger] AS [SPL]
                    WHERE [SPL].[RECORDID] = @PaymentRecordID)
    BEGIN
        SET @Result = 0
        RETURN
    END

    BEGIN TRY
        BEGIN TRANSACTION
        
        DECLARE @AllNo INT
        DECLARE @TODAY DATETIME
        
        -- Get today's date only
        SET @TODAY = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

        -- Check both [dbo].[control] AND [dbo].[Allocations]
        SELECT TOP 1
               @AllNo = ISNULL([CON].[LastAlloc], 0) + 1
          FROM [dbo].[control] AS [CON]

        SELECT TOP 1 @AllNo = CASE WHEN ISNULL(MAX([ALO].[AllNo]), 0) > @AllNo
                                        THEN ISNULL(MAX([ALO].[AllNo]), 0)
                                   ELSE ISNULL(@AllNo, 0) END
          FROM [dbo].[Allocations] AS [ALO]
      
        -- Use a common table expression (CTE) to combined
        -- data from both rows into a single row, then use
        -- a UNION to get two rows with data from both
        ;WITH [CombinedData] ([AllNo],
                              [BillBatchNo],
                              [BillPostRef],
                              [BillRef],
                              [PaymentBatchNo],
                              [PaymentPostRef],
                              [PaymentRef],
                              [Date],
                              [Value],
                              [UserCode]) AS (
        SELECT @AllNo,
               [BIL].[BATCHNO],
               [BIL].[PREF],
               [BIL].[REF],
               [PAY].[BATCHNO],
               [PAY].[PREF],
               [PAY].[REF],
               @TODAY,
               @VALUE,
               @UserCode
          FROM [dbo].[SupplierLedger] AS [BIL]
               CROSS APPLY [dbo].[SupplierLedger] AS [PAY]
         WHERE [BIL].[RECORDID] = @BillRecordID
           AND [PAY].[RECORDID] = @PaymentRecordID)

        INSERT INTO [dbo].[Allocations] (
               [BATCHNO],
               [PREF],
               [DATE],
               [ABATCHNO],
               [OPREF],
               [OREF],
               [VALUE],
               [FEES],
               [OUTLAY],
               [VAT],
               [USERCODE],
               [AllNo],
               [VATCode])
               -- Bill side
        SELECT [CD].[BillBatchNo],     /* BATCHNO */
               [CD].[BillPostRef],     /* PREF */
               [CD].[Date],            /* DATE */
               [CD].[PaymentBatchNo],  /* ABATCHNO */
               [CD].[PaymentPostRef],  /* OPREF */
               [CD].[PaymentRef],      /* OREF */
               [CD].[Value],           /* VALUE */
               0,                      /* FEES */
               0,                      /* OUTLAY */
               0,                      /* VAT */
               [CD].[UserCode],        /* USERCODE */
               [CD].[AllNo],           /* AllNo */
               ''                      /* VATCODE */
          FROM [CombinedData] AS [CD]
               UNION ALL
               -- Payment side
        SELECT [CD].[PaymentBatchNo],  /* BATCHNO */
               [CD].[PaymentPostRef],  /* PREF */
               [CD].[Date],            /* DATE */
               [CD].[BillBatchNo],     /* ABATCHNO */
               [CD].[BillPostRef],     /* OPREF */
               [CD].[BillRef],         /* OREF */
               [CD].[Value],           /* VALUE */
               0,                      /* FEES */
               0,                      /* OUTLAY */
               0,                      /* VAT */
               [CD].[UserCode],        /* USERCODE */
               [CD].[AllNo],           /* AllNo */
               ''                      /* VATCODE */
          FROM [CombinedData] AS [CD]
        
         UPDATE [BIL]
            SET [BIL].[OSValue] = [BIL].[OSValue] + @VALUE
           FROM [dbo].[SupplierLedger] AS [BIL]
          WHERE [BIL].[RECORDID] = @BillRecordID

         UPDATE [PAY]
            SET [PAY].[OSValue] = [PAY].[OSValue] - @VALUE
           FROM [dbo].[SupplierLedger] AS [PAY]
          WHERE [PAY].[RECORDID] = @PaymentRecordID
           
        UPDATE [CON]
           SET [CON].[LastAlloc] = @AllNo
          FROM [dbo].[control] AS [CON]

        SET @Result = 1
        
        COMMIT TRANSACTION
    END TRY
    BEGIN CATCH
        SET @Result = 0

        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
END
GO
IF EXISTS (SELECT TOP 1 1 
           FROM   sys.[objects] SO 
           WHERE  SO.[name] = N'KAAS_InsertSupplierLedgerComment' 
                  AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_InsertSupplierLedgerComment] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_InsertSupplierLedgerComment] 
	   (
		    @Supp      VARCHAR(20),
			@User      VARCHAR(50),
			@Comments  VARCHAR(MAX),
			@Date      DATETIME,
			@Result	   TINYINT OUTPUT
	   )
  AS 
  /*******************************************************************************************************
  * Used to insert supplier ledger comment                                                               *
  * Stored Procedure Name: [dbo].[KAAS_InsertSupplierLedgerComment]									     * 
  * Modification History:                                                                                *
  * 2021-07-07 Natarajan S        Created																 *  
  * 2021-07-08 Natarajan S        Modified - Formatting Added.											 *
  * 2022-02-28 Balamurugan.C      Modified - Handled TCL Statements                                      *    
  *******************************************************************************************************/
  BEGIN 
	SET NOCOUNT ON
	   BEGIN TRY
         BEGIN TRAN
				 INSERT 
				   INTO [dbo].[SupplierLedger]
					(   
						[Supp],
						[Type],
						[Date],
						[Ref],
						[BatchNo],
						[Pref],
						[Narr],
						[Original],
						[OSValue],
						[Year],
						[Per],
						[EntryDate],
						[ThirdParty],
						[ThirdPartyValue],
						[Matter],
						[PendingOutlay]
					)
				 VALUES 
						(@Supp,       /*[Supp]*/
						 ' ',		  /*[Type]*/
						 @Date,		  /*[Date]*/
						 @User,		  /*[Ref]*/
						 0,			  /*[BatchNo]*/
						 0,			  /*[Pref]*/
						 @Comments,	  /*[Narr]*/
						 0.00,		  /*[Original]*/
						 0.00,		  /*[OSValue]*/
						 0,			  /*[Year]*/
						 0,			  /*[Per]*/
						 @Date,		  /*[EntryDate]*/
						 'N',		  /*[ThirdParty]*/
						 0.00,		  /*[ThirdPartyValue]*/
						 '',		  /*[Matter]*/
						 0.00) 		  /*[PendingOutlay]*/

					SET @Result=1
	       COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH
   SET NOCOUNT OFF
  END 

GO
 
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_InsertUpdateAccountMenuPermission' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_InsertUpdateAccountMenuPermission] 
  END 
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[KAAS_InsertUpdateAccountMenuPermission]
(
	@HandlerCode			      VARCHAR(10),
	@CurrentHandlerCode		      VARCHAR(10),
	@HandlerMenuPermissionTypeTbl    HandlerMenuPermissionType READONLY
)
AS
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_InsertUpdateAccountMenuPermission]      						   *
* Description: Insert / Update SAM Menu Permission 		    										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2024-01-04    Balamurugan C        Created                                                           *
 *******************************************************************************************************/
BEGIN


		UPDATE [HPM]
		   SET [HPM].[ReadAccess] = [TMP].ReadAccess ,
			   [HPM].[WriteAccess] = [TMP].WriteAccess
		  FROM [dbo].[HandlerMenuPermissionMap] [HPM]
	INNER JOIN @HandlerMenuPermissionTypeTbl [TMP] ON 
			   [TMP].[MenuId] = [HPM].[MenuId] AND
			   [TMP].[HandlerPermissionMapId] = [HPM].[HandlerPermissionMapId]
		 WHERE [TMP].[HandlerPermissionMapId] <> 0

		INSERT 
		  INTO [dbo].[HandlerMenuPermissionMap]
			   (
				[HandlerCode],
				[MenuId],
				[ReadAccess],
				[WriteAccess],
				[LastModifiedBy],
				[LastModifiedDate]
			   )
		SELECT @HandlerCode,
			   [MenuId],
			   [ReadAccess],
			   [WriteAccess],
			   @CurrentHandlerCode,
			   GETDATE()
		  FROM @HandlerMenuPermissionTypeTbl
		 WHERE HandlerPermissionMapId = 0

		SELECT [MenuId], [ReadAccess], [WriteAccess] FROM @HandlerMenuPermissionTypeTbl
		WHERE HandlerPermissionMapId = 0
END
GO

IF OBJECT_ID(N'KAAS_InsertUpdateFeeEarnerCodesDetails', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertUpdateFeeEarnerCodesDetails]
END
GO
CREATE PROCEDURE [dbo].[KAAS_InsertUpdateFeeEarnerCodesDetails] 
	(
	      @Code		        VARCHAR(10) = '',
	      @Name		        VARCHAR(40) = '',
	      @Nominal	        VARCHAR(10) = '',
	      @Retired	        VARCHAR(1)  = '',
	      @Mode		        VARCHAR(20) = '',
		  @Branch	        VARCHAR(10) = ''
	)
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_InsertUpdateFeeEarnerCodesDetails]							   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-06-23	Balamurugan C		Created															   *
* 2022-03-02	Vignesh.M		    Modified Branch Implemented 	
* 2022-03-04	Ghayathri.S.V		Script Modified for Insert and Edit
*******************************************************************************************************/
AS
BEGIN
		IF( @Mode = 'EDIT' )
		  BEGIN
			  IF EXISTS 
			     (
			        SELECT TOP  1 1
				    FROM       [dbo].[FeeEarnerCodes]
					WHERE      [Code] = @Code
			     )
				BEGIN
					UPDATE [dbo].[FeeEarnerCodes]
					   SET [Name]	 = @Name,
						   [Nominal] = @Nominal,
						   [Retired] = @Retired,
						   [Branch]  = @Branch
					 WHERE [Code]    = @Code
				END
			END
		IF( @Mode = 'INSERT' )
		  BEGIN
			  IF NOT EXISTS 
			     (
			         SELECT TOP  1 1
					 FROM [dbo].[FeeEarnerCodes]
					 WHERE [Code] = @Code
				 )
				BEGIN
				    INSERT 
					  INTO [dbo].[FeeEarnerCodes]
							   (
								 [Code],
								 [Name],
								 [Nominal],
								 [Retired],
								 [Branch]
							   )
				    VALUES     ( 
					             @Code,      /*[Code]*/
								 @Name,		 /*[Name]*/
								 @Nominal,   /*[Nominal]*/
								 @Retired,   /*[Retired]*/
								 @Branch     /*[Branch]*/
							   )
				END
		   END
		IF( @Mode = 'DELETE' )
			  BEGIN
			    DELETE 
			      FROM [dbo].[FeeEarnerCodes]
			     WHERE [Code] = @Code
		      END
END
GO


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

GO

CREATE PROCEDURE [dbo].[KAAS_InsertUpdateNominalReportingSeq] (
	@Code		  VARCHAR(4)='',
	@Desc		  VARCHAR(40)='',
	@Pb		      VARCHAR(1)='',
	@Mode		  VARCHAR(20)=''
	)
/*******************************************************************************************************
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_InsertUpdateNominalReportingSeq]								   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-06-18	Balamurugan C		Created	
* 2022-03-04	Ghayathri.S.V		Script Modified for Insert and Edit	*
*******************************************************************************************************/
AS
BEGIN
    IF( @Mode = 'EDIT' )
      BEGIN
          IF EXISTS (
						SELECT TOP 1 1
						  FROM  [dbo].[NominalReportSeq]
                         WHERE  [Code] = @Code
				     )
           BEGIN
                UPDATE [dbo].[NominalReportSeq]
                SET    [DESC] = @Desc,
                       [PB]	  = @Pb
                WHERE  [CODE] = @Code
                       
            END
	   END
    IF( @Mode = 'INSERT' )
	  BEGIN
		  IF NOT EXISTS (
						   SELECT TOP 1 1
						     FROM  [dbo].[NominalReportSeq]
                            WHERE  [Code] = @Code
					    )
        BEGIN
		    INSERT 
			INTO  [dbo].[NominalReportSeq]
                  (
					[CODE],
                    [DESC],
                    [PB]
				  )
           VALUES ( 
					@Code,    /*[Code]*/
                    @Desc,	  /*[DESC]*/
                    @Pb       /*[PB]*/
				  )
         END
	END
    IF( @Mode = 'DELETE' )
		  BEGIN
              DELETE 
			  FROM  [dbo].[NominalReportSeq]
              WHERE [CODE] = @Code
		  END
END


GO


IF OBJECT_ID(N'KAAS_InsertUpdatePaymentMethods', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertUpdatePaymentMethods]
END
GO
CREATE PROCEDURE [dbo].[KAAS_InsertUpdatePaymentMethods] 
    (
            @Id					INT          = 0,
            @Description		VARCHAR(500) = '',
            @ClearDays			INT          = 0,
            @Retired			TINYINT      = 0,
            @Mode				VARCHAR(20)  = 'INSERTEDIT'
	)
/*******************************************************************************************************
* Stored Procedure Name	: [dbo].[KAAS_InsertUpdatePaymentMethods]									   *
* Copied from			: NA																		   *
*																									   *
* Modification History	:                                                                              *
* 2021-06-22	Balamurugan C		Created															   *
*******************************************************************************************************/
AS
BEGIN
	SET NOCOUNT ON
		IF( @Mode = 'INSERTEDIT' )
		  BEGIN
			  IF EXISTS 
			    (
				    SELECT TOP 1 1
				      FROM [dbo].[PaymentMethods]
				     WHERE [id] = @Id
				)
				BEGIN
					UPDATE [dbo].[PaymentMethods]
					   SET [Description] =	@Description,
						   [ClearDays]	 =	@ClearDays,
						   [Retired]	 =	@Retired
					 WHERE [id] = @Id
						   
				END
			  ELSE
				BEGIN
					INSERT 
					  INTO [dbo].[PaymentMethods]
								(
								  [Description],
								  [ClearDays],
								  [Retired]
								)
					VALUES		( 
								  @Description,
								  @ClearDays,
								  @Retired
								)
				END
		  END
		ELSE
		  BEGIN
			  DELETE 
			    FROM [dbo].[PaymentMethods]
			   WHERE [id] = @Id
		  END
	SET NOCOUNT OFF
END

GO


IF OBJECT_ID(N'KAAS_InsertUpdateVATCodes', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertUpdateVATCodes]
END
GO
CREATE PROCEDURE [dbo].[KAAS_InsertUpdateVATCodes] 
    (
	        @Code		  VARCHAR(1)   = '',
	        @Rate		  DECIMAL(5,2) = 0,
	        @Mode		  VARCHAR(20)  = '',
			@Comments	  VARCHAR(2000) = '',
			@Retired	  VARCHAR(1) = 'N'
	)
/*******************************************************************************************************
* Stored Procedure Name	: [dbo].[KAAS_InsertUpdateVATCodes]											   *
* Copied from			: NA																		   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-06-21	Balamurugan C		Created		
* 2022-03-04	Ghayathri.S.V		Script Modified for Insert and Edit
* 2023-09-27	Ghayathri.S.V   	Inserted the Comments column while INSERTING AND UPDATING vatcodes *
* 2023-12-13	Vignesh M   		Added Retired field												   *
*******************************************************************************************************/
AS
BEGIN
		IF( @Mode = 'EDIT' )
		  BEGIN
			  IF EXISTS 
				(
					SELECT TOP 1 1
					  FROM [dbo].[VATCodes]
					 WHERE [Code] = @Code
				)
				BEGIN
					UPDATE [dbo].[VATCodes]
					   SET [Rate] = @Rate,
						   [Comments] = @Comments,
						   [RETIRED] = @Retired
					 WHERE [Code] = @Code
						   
				END
			END
		IF( @Mode = 'INSERT')
		  BEGIN
			  IF NOT EXISTS  
				(
					SELECT TOP 1 1
					  FROM [dbo].[VATCodes]
					 WHERE [Code] = @Code
				)
				BEGIN
					INSERT 
					  INTO [dbo].[VATCodes]
								(
								  [Code],     /*[Code]*/
								  [Rate],	  /*[Rate]*/
								  [Comments],  /*[Comments]*/
								  [RETIRED]	   /*[Retired]*/
								)
					VALUES		( 
								  @Code,
								  @Rate,
								  @Comments,
								  @Retired
								)
				END
		    END
		IF( @Mode = 'DELETE')

				BEGIN
					DELETE 
					  FROM [dbo].[VATCodes]
					 WHERE [Code] = @Code
				END
END

GO

IF OBJECT_ID(N'KAAS_InsertUpdateWorkGroup', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertUpdateWorkGroup]
END
GO
CREATE PROCEDURE [dbo].[KAAS_InsertUpdateWorkGroup] 
    (
	        @RecordID  INT,
	        @WorkType  VARCHAR(50),
	        @Group1	   VARCHAR(10),
	        @Group2	   VARCHAR(10),
			@Result    INT OUTPUT
	)
/*******************************************************************************************************
* Stored Procedure Name	: [dbo].[KAAS_InsertUpdateWorkGroup]										   *																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-08-10	Natarajan S		Created															       *
*******************************************************************************************************/
AS
BEGIN
	SET NOCOUNT ON
	IF(@RecordID = 0)
	BEGIN
	 INSERT INTO [dbo].[WorkTypeGroupings] (
                 [WorkType],
			     [Group1],
			     [Group2])
	      VALUES (@WorkType,
	             @Group1,
			     @Group2
	 		     )
	 SET @Result = 1;
	END
	ELSE 
	BEGIN
	      UPDATE [dbo].[WorkTypeGroupings]
	      SET [WorkType] = @WorkType,
		        [Group1] = @Group1,
			    [Group2] = @Group2
		  WHERE RecordID = @RecordID
	  SET @Result = 1;
	END
	SET NOCOUNT OFF
END

GO



IF OBJECT_ID(N'KAAS_InsertUpdateWorkType', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_InsertUpdateWorkType]
END
GO
CREATE PROCEDURE [dbo].[KAAS_InsertUpdateWorkType] 
    (
	        @Mode         VARCHAR(10),
			@Type         VARCHAR(5),
			@OldWorkGroup varchar(50),
	        @WorkGroup    VARCHAR(50),
	        @GroupOrder	  VARCHAR(10) NULL,
	        @Description  VARCHAR(60),
			@Result       INT OUTPUT
	)
/*******************************************************************************************************
* Stored Procedure Name	: [dbo].[KAAS_InsertUpdateWorkType]										       *																   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-08-10	Natarajan S		Created															       *
* 2022-04-26    Balamurugan C   Modified - Increased Parameter Length and							   *
*                                           added duplicate check condition                             *
*******************************************************************************************************/
AS
BEGIN
	SET NOCOUNT ON
	IF(@Type = 'ONE')
	 BEGIN
	      IF(@Mode = 'INSERT')
	      BEGIN

	      IF EXISTS(SELECT WorkGroup FROM WorkGroup1 WHERE WorkGroup=@WorkGroup)
	       BEGIN
	        SET @Result = 0;
	       END
	      ELSE 
	       BEGIN
	          INSERT INTO [dbo].[WorkGroup1] (
                          [WorkGroup],
	         		      [GroupOrder],
	         		      [Description])
	               VALUES (@WorkGroup,
	                      @GroupOrder,
	         		      @Description)
	          SET @Result = 1;
	         END
	 END
	      ELSE 
	      BEGIN
	IF EXISTS(SELECT WorkGroup FROM WorkGroup1 WHERE WorkGroup = @WorkGroup AND WorkGroup <> @OldWorkGroup)
	 BEGIN
	  SET @Result = 0;
	 END
	 ELSE 
	 BEGIN
	      UPDATE [dbo].[WorkGroup1]
	         SET [WorkGroup] = @WorkGroup,
		         [GroupOrder] = @GroupOrder,
			     [Description] = @Description
		  WHERE [WorkGroup] = @OldWorkGroup
	  SET @Result = 1;
	 END
	END
	   END
	   ELSE
	    BEGIN
		    IF(@Mode = 'INSERT')
	      BEGIN
	      IF EXISTS(SELECT WorkGroup2 FROM WorkGroup2 WHERE WorkGroup2 = @WorkGroup)
	       BEGIN
	        SET @Result = 0;
	       END
	      ELSE 
	       BEGIN
	          INSERT INTO [dbo].[WorkGroup2] (
                          [WorkGroup2],
	         		      [Description2])
	               VALUES (@WorkGroup,
	                      @Description)
	          SET @Result = 1;
	         END
	 END
	      ELSE 
	      BEGIN
	IF EXISTS(SELECT WorkGroup2 FROM WorkGroup2 WHERE WorkGroup2 = @WorkGroup AND WorkGroup2 <> @OldWorkGroup)
	 BEGIN
	  SET @Result = 0;
	 END
	 ELSE 
	 BEGIN
	      UPDATE [dbo].[WorkGroup2]
	         SET [WorkGroup2] = @WorkGroup,
		         [Description2] = @Description
		   WHERE [WorkGroup2] = @OldWorkGroup
	  SET @Result = 1;
	 END
	END
		END
	SET NOCOUNT OFF
END

GO



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

GO

CREATE PROCEDURE 
       [dbo].[KAAS_MaintainInsertMaster] 
(
  @MasterName       VARCHAR(50),
  @Code             VARCHAR(100),
  @Description      VARCHAR(MAX),
  @Retired          VARCHAR(2),
  @Childcare        CHAR(1) = '',
  @RGBColour        INT = 0,
  @DefaultRate      FLOAT = 0,
  @ClientCharge     INT = 0,
  @Value            FLOAT = 0,
  @ClientValue      FLOAT = 0,
  @User             VARCHAR(8) = '' , 
  @Mode			    VARCHAR(10),
  @NewCodeVal	    VARCHAR(20) = '',
  @BackGroundColour VARCHAR(30) = '#FF008000',
  @Result		    BIT OUTPUT
)
AS
/*******************************************************************************************************
*This procedure is used to Fetch details FROM the below listed Masters table.						   *
* [dbo].[KAAS_MaintainInsertMaster]	'UndertakingStatus','as','yu','N','',0,0,0,0,0,'','INSERT','yu',0
select * from undertakingstatus																                                       *
* Stored Procedure Name	: [dbo].[KAAS_MaintainInsertMaster]											   *
* Copied from			: [dbo].[ky_NETMaintainInsertMaster]										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-06-16	NATARAJAN S		Created                                                                *
* 2021-07-01	Prabhu V		Changed Master Name for File Colour as per                             *
								Master Name we provided in front end and Added Retired for Update      *
* 2021-07-02	Prabhu V		SP structure changed as per coding standrard in Keyhouse               *
* 2023-08-23	Ghayathri.S.V	Modified the billing update procedure as per coding in keyhouse        *
* 2023-08-24	Ghayathri.S.V	Modified the client group procedure as per coding in keyhouse		   *
* 2023-08-28	Ghayathri.S.V   Inserted the Document CLass and Type 
								procedure as per coding in keyhouse									   *
* 2023-08-29	Ghayathri.S.V   Modified the Marital Status,Tax Type, Narratives,Tax Head, 
								Salutation Codes to fetch the grid data								   *
* 2023-11-28	Revathy.D       Modified the Item Types Codes to fetch the grid data				   *
* 2023-11-29	Revathy.D       Added SMS template                                                     *
* 2023-12-14	Vignesh M       Modified the Retired field is added for Add/Edit Nominal Types		   *
* 2023-12-18	Revathy.D       Modified param for Charge Type                                         *
 *******************************************************************************************************/

BEGIN
 DECLARE @Command VARCHAR(MAX)
 DECLARE @HandleRate AS FLOAT
 DECLARE @EventDesc AS VARCHAR(300) 
 SET @HandleRate = 0
 SET @EventDesc=''


 IF(@Mode = 'INSERT')
	BEGIN
		Exec @Result = [KAAS_CheckCodeExists_Maintenance] 	  
			@Mode,
			@MasterName,
			@Code,
			@Description,
			@NewCodeVal
	END
	

IF(@Result = 0)
	BEGIN
		SET @Result = 0 
	END
ELSE 
  BEGIN

	 IF (@MasterName='Departments')
		BEGIN
			IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						[dbo].[departments] 
			            ([Code], 
			            [Description], 
			            [Desc], 
			            [Retired]) 
			  VALUES    (@Code, 
			             @Description, 
			             @Description, 
			             @Retired) 
			ELSE
			  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[departments] WHERE RTRIM([Code])= @Code)
			  UPDATE 
					 [dbo].[departments] 
			  SET    [Code] = @NewCodeVal, 
			         [Description] = @Description, 
			         [Desc] = @Description, 
			         [Retired] = @Retired 
			  WHERE  [Code] = @Code 
		END		
	 ELSE IF (@MasterName='Worktypes')
		BEGIN
			IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[WorkTypes] 
			              ([Code], 
			               [Description], 
			               [Desc], 
			               [Retired]) 
			  VALUES      (@Code, 
			               @Description, 
			               @Description, 
			               @Retired) 
			ELSE 
			  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[WorkTypes] WHERE RTRIM([Code])= @Code)
			  UPDATE 
					 [dbo].[WorkTypes] 
			  SET    [Code] = @NewCodeVal, 
			         [Description] = @Description, 
			         [Desc] = @Description, 
			         [Retired] = @Retired 
			  WHERE  [Code] = @Code     
		END
	 ELSE IF (@MasterName='NominalTypes')
		BEGIN
			IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[NominalTypes] 
			              ([ntyCode], 
			               [ntydesc], 
			               [Retired]) 
			  VALUES      (@Code, 
			               @Description, 
			               @Retired) 
			ELSE
			  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[NominalTypes] WHERE RTRIM([ntyCode]) = @Code)
			  UPDATE [dbo].[NominalTypes] 
			  SET    [ntyCode] = @NewCodeVal, 
			         [ntydesc] = @Description , 
			         [Retired] = @Retired 
			  WHERE  [ntyCode] = @Code 
		END
	 ELSE IF ( @MasterName = 'CategoryType' ) 
		BEGIN 
		      IF ( @Mode = 'INSERT' ) 
		        INSERT INTO 
							[dbo].[CategoryType] 
		                    ([CategoryType], 
		                     [Description]) 
		        VALUES      (@Code, 
		                     @Description) 
		      ELSE
			    IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[CategoryType] WHERE RTRIM(CategoryType) = @Code)
		        UPDATE 
					   [dbo].[CategoryType]
		        SET    [CategoryType] = @NewCodeVal, 
		               [Description] = @Description 
		        WHERE  Rtrim(CategoryType) = @Code 
		END 
	 ELSE IF (@MasterName='NationCodes')
		BEGIN 
			IF ( @Mode = 'INSERT' ) 
			INSERT INTO 
						[dbo].[NationCodes] 
			            ([Nation], 
			            [Desc]) 
			VALUES      (@Code, 
			            @Description) 
			ELSE
			IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[NationCodes] WHERE RTRIM([Nation]) = @Code)
			UPDATE 
				   [dbo].[NationCodes]
			SET    
				   [Nation] = @NewCodeVal, 
			       [Desc] = @Description 
			WHERE  Rtrim([Nation]) = @Code 
		END 
	 ELSE IF (@MasterName='DepositType')
		BEGIN
			IF ( @Mode = 'INSERT' ) 
			  INSERT INTO [dbo].[DepositType] 
			              ([Code], 
			               [Description]
			               ) 
			  VALUES      (@Code, 
			               @Description) 
			ELSE 
			  UPDATE 
					 [dbo].[DepositType] 
			  SET    
					 [Code] = @NewCodeVal, 
			         [Description] = @Description
			  WHERE  [Code] = @Code     
		END
	 ELSE IF (@MasterName='OutlayCode')
		BEGIN
		  IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[OutlayCode] 
			              ([Code], 
			               [Description]) 
			  VALUES      (@Code, 
			               @Description) 
		  ELSE 
			  UPDATE 
					 [dbo].[OutlayCode] 
			  SET    
					 [Code] = @NewCodeVal, 
			         [Description] = @Description
			  WHERE  [Code] = @Code     
		END
	 ELSE IF (@MasterName='Narratives')
		BEGIN
		  IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[Narratives] 
			              ([Code], 
			               [Narrative]) 
			  VALUES      (@Code, 
			               @Description) 
		  ELSE 
			  UPDATE 
					 [dbo].[Narratives] 
			  SET    [Code] = @NewCodeVal, 
			         [Narrative] = @Description
			  WHERE  [Code] = @Code     
		END
	 ELSE IF (@MasterName='ServiceCodes')
		BEGIN
		  IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[ServiceCodes] 
			              ([Code], 
			               [Description]) 
			  VALUES      (@Code, 
			               @Description) 
		  ELSE 
			  UPDATE 
					 [dbo].[ServiceCodes] 
			  SET    [Code] = @NewCodeVal, 
			         [Description] = @Description
			  WHERE  [Code] = @Code     
		END
	 ELSE IF (@MasterName='Branch')
		BEGIN
		  IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[Branch] 
			              ([BranchCode], 
			               [Description], 
			               [Retired]) 
			  VALUES      (@Code, 
			               @Description, 
						   CASE @Retired WHEN 'Y' THEN 1 ELSE 0 END) 
		  ELSE
			  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[Branch] WHERE RTRIM([BranchCode]) = @Code)
			  UPDATE 
					 [dbo].[Branch] 
			  SET    [BranchCode] = @NewCodeVal, 
			         [Description] = @Description, 
			         [Retired] = CASE @Retired WHEN 'Y' THEN 1 ELSE 0 END 
			  WHERE  [BranchCode] = @Code     
		END
	 ELSE IF (@MasterName='UndertakingStatus')
		BEGIN
		  IF ( @Mode = 'INSERT' ) 
			  INSERT INTO 
						  [dbo].[UndertakingStatus] 
			              ([StatusDesc],
						   [Retired]) 
			  VALUES      (@NewCodeVal,
						   @Retired) 
		  ELSE
			  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[UndertakingStatus] WHERE RTRIM([RecordID]) = @Code)
			  UPDATE 
					 [dbo].[UndertakingStatus] 
			  SET    
			         [StatusDesc] = @NewCodeVal,
			         [Retired] = @Retired
			  WHERE  [RecordID] = @Code     
		END
	 ELSE IF (@MasterName='FeeEarners')
		BEGIN
		  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[FeeEarnerCodes] WHERE RTRIM([Code])=@Code )
			 BEGIN
				  UPDATE   
						   [dbo].[FeeEarnerCodes]
				  SET
						   [Name]  = @Description,
						   [Retired] = @Retired
				  WHERE    RTRIM([Code]) = @Code
				 END
		  ELSE
			 BEGIN
				  INSERT INTO 
							  [dbo].[FeeEarnerCodes] 
							  ([Code],
							  [Name],
							  [Retired] )
				  VALUES      (@Code,
							   @Description,
							   @Retired)
			 END
		END
	 ELSE IF (@MasterName='FileColours')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[FileColours] WHERE RTRIM(ISNULL([ColourCode],''))=@Code )
			 BEGIN
				  UPDATE   
						   [dbo].[FileColours]
				  SET
						   [ColourCode]  = @Code,
						   [ColourDesc]  = @Description,
						   [RGBColour] = ISNULL(@RGBColour, -1),
						   [BackGroundColour] = UPPER(@BackGroundColour),
						   [ForegroundColour] = UPPER(@BackGroundColour),
						   [Retired]   = @Retired
				  WHERE
						   RTRIM(ISNULL([ColourCode],'')) = @Code
			 END
		 ELSE
			BEGIN
				  INSERT INTO 
							  [dbo].[FileColours] 
							  ([ColourCode],
							   [ColourDesc], 
							   [RGBColour],
							   [Retired],
							   [BackgroundColour],
							   [ForegroundColour])
				  VALUES
							  (@Code,
							   @Description, 
							   ISNULL(@RGBColour, -1),
							   @Retired,
							   UPPER(@BackGroundColour),
							   UPPER(@BackGroundColour))
			END
		 END
	 ELSE IF (@MasterName='Maritals')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM dbo.[MiscCodes] WHERE RTRIM([CdeCode])=@Code AND [CdeType]='MRS')
			 BEGIN
				  UPDATE   
						   [dbo].[MiscCodes]
				  SET
						   [CdeDesc] = @Description,
						   [Retired] = @Retired
				  WHERE
						   RTRIM([CdeCode]) = @Code AND [CdeType] = 'MRS'
			 END
		 ELSE
			 BEGIN
				  INSERT INTO   
								[dbo].[MiscCodes] 
								([CdeType],
								 [CdeCode],
								 [CdeDesc],
								 [Retired])
				  VALUES
								('MRS',
								 @Code,
								 @Description,
								 @Retired)
			 END
	 END
	 ELSE IF (@MasterName='TaxType')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[TaxType] WHERE RTRIM([TaxType])=@Code)
			 BEGIN
				  UPDATE   
						   [dbo].[TaxType]
				  SET
						   [TaxDesc] = @Description
				  WHERE
						   RTRIM([TaxType]) = @Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO   
								[dbo].[TaxType] 
								([TaxType],
								 [TaxDesc])
				  VALUES
								(@Code,
								 @Description)
			 END
	  END
	 ELSE IF (@MasterName='DesktopNarr')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[DesktopNarr] WHERE RTRIM([Code])=@Code)
			 BEGIN
				  UPDATE   
						   [dbo].[DesktopNarr]
				  SET
						   [Code] = @Code,
						   [Narrative] = @Description,
						   [Retired] = @Retired
				  WHERE
						   RTRIM([Code]) = @Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO 
							  [dbo].[DesktopNarr] 
							  ([Code],
							   [Narrative],
							   [Retired])
				  VALUES
							  (@Code,
							   @Description,
							   @Retired)
			 END
		 END
	 ELSE IF (@MasterName='TimeAdminCodes')
		BEGIN
		 IF EXISTS(SELECT   TOP 1 1  FROM [dbo].[TimeAdminCodes] WHERE RTRIM([NCCode]) = @Code)
			 BEGIN
				  UPDATE   
						   [dbo].[TimeAdminCodes]
				  SET
						   [Description] = @Description,
						   [Retired] = @Retired
				  WHERE
						   RTRIM([NCCode]) = @Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO  
							   [dbo].[TimeAdminCodes] 
							   ([NCCode],
								[Description],
								[Retired])
				  VALUES
							   (@Code,
								@Description,
								@Retired)
			 END
		END
	 ELSE IF (@MasterName='DocumentClasses')
		 BEGIN
			IF EXISTS(SELECT   TOP 1 1  FROM [dbo].[DocumentClasses] WHERE RTRIM([CLASSCODE]) = @Code)
				BEGIN
					UPDATE   
						   [dbo].[DocumentClasses]
					SET
						   [CLASSDESCRIPTION] = @Description,
						   [Retired] = @Retired
					WHERE
						   RTRIM([CLASSCODE]) = @Code
				END
			ELSE
				BEGIN
					INSERT INTO  
							   [dbo].[DocumentClasses] 
							   ([CLASSCODE],
								[CLASSDESCRIPTION],
								[Retired])
					VALUES
							   (@Code,
								@Description,
								@Retired)
				END
		 END
	 ELSE IF (@MasterName='filetypes')
		 BEGIN
			IF EXISTS(SELECT   TOP 1 1  FROM [dbo].[filetypes] WHERE RTRIM([Type]) = @Code)
				BEGIN
					UPDATE   
						   [dbo].[filetypes]
					SET
						   [Description] = @Description
						   --[FilePath]    = @FilePath
					WHERE
						   RTRIM([Type]) = @Code
				END
			ELSE
				BEGIN
					INSERT 
						INTO [dbo].[filetypes]
							 ([Type],
							 [Description]
							 --[FilePath]
							 )
					VALUES	(@Code,
							 @Description
							 --@FilePath
							 )
				END
		 END
	 ELSE IF (@MasterName='BillDescriptions')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[BillDescriptions]  WHERE RTRIM(ISNULL([Number],'')) = @Code)
		 BEGIN
		  UPDATE   [dbo].[BillDescriptions]
		  SET
				   [BillDescriptions] = @Description,
				   [Retired] = @Retired
		  WHERE
				   [Number] = @Code
		 END
		 ELSE
		 BEGIN
		  INSERT INTO [dbo].[BillDescriptions] 
					  ([SearchField],
					   [BillDescriptions],
					   [Retired])
		  VALUES
					  (@Code,
					   @Description,
					   @Retired)
		 END
		END
	 ELSE IF (@MasterName='Undertaking')
		 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[UndertakingStatus] WHERE [RecordID] = @Code)
			 BEGIN
			  UPDATE   [dbo].[UndertakingStatus]
			  SET
					   [StatusDesc] = @Description,
					   [Retired]    = @Retired
			  WHERE
					   [RecordID] = @Code
			 END
		 ELSE
			 BEGIN
			  INSERT INTO  [dbo].[UndertakingStatus] 
						   ([StatusDesc],
							[Retired])
			  VALUES
						   (@Description,
							@Retired)
			 END
		 END
	 ELSE IF (@MasterName='Branch')
		 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[Branch] WHERE RTRIM([BranchCode])=@Code)
			 BEGIN
			  UPDATE   [dbo].[Branch]
			  SET
					   [Description] = @Description
			  WHERE
					   RTRIM([BranchCode]) = @Code
			 END
		 ELSE
			 BEGIN
			  INSERT INTO   [dbo].[Branch] 
							([BranchCode],
							 [Description])
				 VALUES
							(@Code,
							 @Description)
			 END
		 END
	 ELSE IF (@MasterName='TaxHead')
		 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[TaxHead] WHERE RTRIM([TaxHead])=@Code)
			 BEGIN
			  UPDATE   [dbo].TaxHead
			  SET
					   [Description] = @Description
			  WHERE
					   RTRIM([TaxHead])=@Code
			 END	
		 ELSE
			 BEGIN
			  INSERT INTO   [dbo].[TaxHead] 
							([TaxHead],
							 [Description])
			  VALUES
							(@Code,
							 @Description)
			 END
		 END
     ELSE IF (@MasterName='SalutationCodes')
		BEGIN
		 IF EXISTS(SELECT   TOP 1 1  FROM SalutationCodes WHERE RTRIM(Code)=@Code)
			 BEGIN
				  UPDATE [dbo].[SalutationCodes]
				  SET
						 [Description] = @Description
				  WHERE
						 RTRIM([Code])=@Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO  [dbo].[SalutationCodes] 
							   ([Code],
								[Description])
				  VALUES
							   (@Code,
								@Description)
			 END
		 END
	 ELSE IF (@MasterName='Charge Type')
		 BEGIN
		 IF EXISTS(SELECT   TOP 1 1  FROM [dbo].[ChargeType] WHERE RTRIM([ChargeType])=@Code AND RTRIM([TaxHead])=@NewCodeVal)
			 BEGIN
				  UPDATE   [dbo].[ChargeType]
				  SET
						   [ChargeType]  = @Code,
						   [Description] = @Description
				  WHERE
						   RTRIM([ChargeType]) = @Code  
				  AND      RTRIM([TaxHead])  = @NewCodeVal
			 END
		 ELSE
			 BEGIN
				  INSERT INTO [dbo].[ChargeType] 
							  ([ChargeType],
							   [Description],
							   [TaxHead])
				  VALUES
							  (@Code,
							   @Description,
							   @NewCodeVal)
			 END
		 END
	 ELSE IF (@MasterName='Item Types')
		 BEGIN
		 IF EXISTS(SELECT   TOP 1 1  FROM [dbo].[ItemTypes] WHERE RTRIM([TypeCode])=@Code)
			 BEGIN
				  UPDATE [dbo].[ItemTypes]
				  SET
						 [TypeDescription]  =  @Description,
						 [DeedType] = CASE WHEN @Childcare = 'D' THEN 1 ELSE 0 END,
						 [WillType] = CASE WHEN @Childcare = 'W' THEN 1 ELSE 0 END
				  WHERE
						 RTRIM([TypeCode]) = @Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO [dbo].[ItemTypes] 
							  ([TypeCode],
							   [TypeDescription],
							   [DeedType],
							   [WillType])
				  VALUES
							  (@Code,
							   @Description,
							   CASE WHEN @Childcare = 'D' THEN 1 ELSE 0 END,
							   CASE WHEN @Childcare = 'W' THEN 1 ELSE 0 END)
			 END
		 END
	 ELSE IF (@MasterName='Location')
		 BEGIN
		 IF EXISTS(SELECT TOP 1 1  FROM [dbo].[ItemLocations] WHERE RTRIM([Code])=@Code)
			 BEGIN
				  UPDATE  [dbo].[ItemLocations]
				  SET
						  [Description] = @Description,
						  [Fullyn]   = @childcare,
						  [Retired]  = @Retired
				  WHERE
						  RTRIM([Code]) = @Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO  [dbo].[ItemLocations] 
							   ([Code],
								[Description],
								[Fullyn],
								[Retired])
				  VALUES
							   (@Code,
								@Description,
								@childcare,
								@Retired )
			 END
		 END
	 ELSE IF (@MasterName='GroupModule')
		BEGIN
			 IF EXISTS(SELECT TOP 1 1  FROM [dbo].[ModuleGroup] WHERE RTRIM([GroupName])=@Code)
				 BEGIN
				  UPDATE   [dbo].[ModuleGroup]
				  SET
						   [Description] = @Description,
						   [IsActive] = @Retired
				  WHERE
						   RTRIM([GroupName]) = @Code
				 END
			 ELSE
				 BEGIN
				  INSERT INTO [dbo].[ModuleGroup] 
							  ([GroupName],
							   [Description],
							   [IsActive])
				  VALUES
							  (@Code,
							   @Description,
							   @Retired)
				 END
		END
	 ELSE IF (@MasterName='Occupation')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[MiscCodes] WHERE  RTRIM([CdeCode]) = RTRIM(@Code) AND RTRIM([CdeType]) = 'OCC')
			 BEGIN
			  UPDATE
				   [dbo].[MiscCodes]
			  SET
				   [CdeDesc]  = @Description
			  WHERE
				   RTRIM([CdeCode]) = @Code
			 END
		 ELSE
			 BEGIN
			  INSERT INTO
				   [dbo].[MiscCodes]
				   ([CdeType], 
					[CdeCode], 
					[CdeDesc], 
					[CdeTeam] )
			  VALUES
				   ('OCC',
					@Code,
					@Description,
					'')
			 END
		 END
	 ELSE IF (@MasterName='Contact Type')
		BEGIN
			 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[MiscCodes] WHERE  RTRIM([CdeCode]) = RTRIM(@Code) AND RTRIM([CdeType]) = 'CCL')
				 BEGIN
				  UPDATE
					  [dbo].[MiscCodes]
				  SET
					  [CdeDesc]  = @Description
				  WHERE
					  RTRIM([CdeCode]) = @Code
				 END
			 ELSE
				 BEGIN
				  INSERT INTO
						   [dbo].[MiscCodes] 
						   ([CdeType], [CdeCode], [CdeDesc], [CdeTeam] )
				  VALUES
						   ('CCL',
							@Code,
							@Description,
							'')
				 END
		 END
	 ELSE IF (@MasterName='ClientGroup')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[ClientGroup] WHERE  RTRIM([GroupCode]) = RTRIM(@Code))
			 BEGIN
				  UPDATE
						[dbo].[ClientGroup]
				  SET
						[GroupName]  = @Description
				  WHERE
						RTRIM([GroupCode]) = @Code
			 END
		 ELSE
			 BEGIN
				  INSERT INTO
							[dbo].[ClientGroup] 
							([GroupCode], 
							 [GroupName] )
				  VALUES
							(@Code,
							 @Description)
			 END
		 END
	 ELSE IF (@MasterName='HandlerChargeGroup')
		BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[HandlerChargeGroups] WHERE  RTRIM(ISNULL([Code],'')) = RTRIM(@Code))
			 BEGIN
				SET @HandleRate=(Select [Defaultrate] from [dbo].[HandlerChargeGroups] where RTRIM(ISNULL([Code],'')) = @Code)
				IF @HandleRate <> @DefaultRate
					BEGIN
						SET @EventDesc='Updated Default Rate from ( ' + CONVERT(varchar(10),@HandleRate)+ ' ) to ( ' + CONVERT(varchar(10),@DefaultRate) + ' )'
						INSERT INTO 
								[dbo].RateChangesLog
								([User],
								[Event],
								[FromWhere],
								[UpdatedDate],
								[AffectedTo])
						VALUES
								(@User,
								@EventDesc,
								'Maintain Handler Charge Group',
								GETDATE(),
								@Code)
          
					END
				  UPDATE
						[dbo].[HandlerChargeGroups]
				  SET
						[Name]  = @Description,
						[DefaultRate] =  @DefaultRate
				  WHERE
						RTRIM(ISNULL([Code],'')) = @Code
			 END
		 ELSE
			 BEGIN
			  INSERT INTO
						[dbo].[HandlerChargeGroups] 
						([Code],
						[Name],
						[DefaultRate])
			  VALUES
						(@Code,
						@Description,
						@DefaultRate)
			 END
	   END
	 ELSE IF (@MasterName='StatusCodes')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[StatusCodes] WHERE  RTRIM([Code]) = RTRIM(@Code))
			 BEGIN
			  UPDATE
					[dbo].[StatusCodes]
			  SET
				    [Description] = @Description,
				    [Retired]     = @Retired
			  WHERE
					RTRIM([Code]) = @Code

			  UPDATE [SM]
				 SET 
					 [SM].[MatterStatusDescription] = RTRIM(ISNULL(@Description, ''))
				FROM [dbo].[SearchMatters] [SM]
			   WHERE [SM].[MatterStatus] = @Code
			 END
		 ELSE
			 BEGIN
			  INSERT INTO
						[dbo].[StatusCodes] 
						([Code],
						 [Description],
						 [Retired])
			  VALUES
						(@Code,
						 @Description,
						 @Retired)
			 END
     END
	 ELSE IF (@MasterName='UDFCategory')
	 BEGIN
		  IF EXISTS(SELECT  TOP 1 1  FROM UDFCategory  WHERE id=@Code)
			 BEGIN
			  UPDATE 
					[dbo].[UDFCategory]
			  SET
					[UDFCategory] = @Description
			  WHERE
				    [ID]  = @Code
			 END
		 ELSE
			 BEGIN
			  INSERT INTO
						[dbo].[UDFCategory]
						([UDFCategory] )
			  VALUES
						(@Description)
			 END
	 END
	 ELSE IF (@MasterName='SDLTForm')
		BEGIN
			IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[SDLTForm]  WHERE [FormID] = @RGBColour)
				BEGIN
					UPDATE
						[dbo].[SDLTForm]
					SET
						[FormName] = @Code ,
						[Description] = @Description
					WHERE
						[FormID] = @RGBColour
				END
			ELSE
				BEGIN
					INSERT INTO
						    [dbo].[SDLTForm] 
						    ([FormName],
						    [Description])
					VALUES
							(@Code,
							@Description)
				END
		 END
	 ELSE IF (@MasterName='UndertakingsCategory')
	 BEGIN
		  IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[UndertakingsCategory] WHERE RTRIM([Code])= RTRIM(@Code))
			 BEGIN
				UPDATE
					[dbo].[UndertakingsCategory]
				SET
					[Description] = @Description
				WHERE
					RTRIM([Code]) = @Code
			 END
		  ELSE
			 BEGIN
				INSERT INTO
					[dbo].[UndertakingsCategory] 
					([Code],
					[Description])
				VALUES
					(@Code,
					@Description)
			 END
	 END
	 ELSE IF (@MasterName='KYCType')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[KYCType] WHERE RTRIM([PK_Type])= RTRIM(@Code))
			 BEGIN
				UPDATE
					[dbo].[KYCType]
				SET
					[Description] = @Description
				WHERE
					RTRIM([PK_Type]) = @Code
			 END
		 ELSE
			 BEGIN
				INSERT INTO
					[dbo].[KYCType]
					([Description])
				VALUES
					(@Description)
			 END
	 END
	 ELSE IF (@MasterName='IntroBy')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[IntroductionBy] WHERE RTRIM([Pk_Intro])= RTRIM(@Code))
			 BEGIN
				UPDATE
					[dbo].[IntroductionBy]
				SET
					[Description] = @Description
				WHERE
					RTRIM([Pk_Intro]) = @Code
			 END
		 ELSE
			 BEGIN
				INSERT INTO
					[dbo].[IntroductionBy] 
					([Description])
				VALUES
					(@Description)
			 END
	 END
	 ELSE IF (@MasterName='ClientType')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[ClientType] WHERE RTRIM([PK_ClientType])= RTRIM(@Code))
			 BEGIN
				UPDATE
					[dbo].[ClientType]
				SET
					[Description] = @Description
				WHERE
					RTRIM([PK_ClientType]) = @Code
			 END
		 ELSE
			 BEGIN
				INSERT INTO
					[dbo].[ClientType] 
					([Description])
				VALUES
					(@Description)
			 END
	 END
	 ELSE IF (@MasterName='ID Code')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[IDCodes] WHERE RTRIM(IdCode)= RTRIM(@Code))
		 BEGIN
			UPDATE
				[dbo].[IDCodes]
			SET
				[Description] = @Description,
				[Category]      = @Retired 
			WHERE
				RTRIM([IdCode]) = @Code
		 END
		 ELSE
			 BEGIN
				INSERT INTO
						[dbo].[IdCodes] 
						([IdCode],
						 [Description],
						 [Category])
				VALUES
						(@Code,
						 @Description,
						 @Retired)
			 END
	 END
	 ELSE IF (@MasterName='Outlay Code')
	 BEGIN
	 IF [dbo].[ISSAM4]() = 0
	   BEGIN
		 SET @Command = ' IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[OutlayCode] WHERE RTRIM([Code])= RTRIM(''' + Replace(@Code, '''', '''''') + '''))
		 BEGIN
			UPDATE
				OutlayCode
			SET
				[Description] = ''' + Replace(@Description, '''', '''''') + '''
			WHERE
				RTRIM(Code) = ''' + Replace(@Code, '''', '''''') + '''
		 END
		 ELSE
		 BEGIN
			INSERT INTO
				OutlayCode(Code,[Description])
			VALUES
				(''' + Replace(@Code, '''', '''''') + ''',''' + Replace(@Description, '''', '''''') + ''')
		 END'
		 EXEC (@Command)
	   END
	ELSE
	   BEGIN
		 SET @Command = ' IF EXISTS(SELECT  TOP 1 1  FROM OutlayCode WHERE RTRIM([OutlayCode])= RTRIM(''' + Replace(@Code, '''', '''''') + '''))
		 BEGIN
			UPDATE
				OutlayCode
			SET
				[Description] = ''' + Replace(@Description, '''', '''''') + '''
			WHERE
				RTRIM([OutlayCode]) = ''' + Replace(@Code, '''', '''''') + '''
		 END
		 ELSE
		 BEGIN
			INSERT INTO
				OutlayCode([OutlayCode],[Description])
			VALUES
				(''' + Replace(@Code, '''', '''''') + ''',''' + Replace(@Description, '''', '''''') + ''')
		 END'
		 EXEC (@Command)
	   END
	 END
	 ELSE IF (@MasterName='Interest')
	 BEGIN
		IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[MiscCodes] WHERE RTRIM([CdeCode])=@Code AND [CdeType]='IRT')
			 BEGIN
				  UPDATE
						[dbo].[MiscCodes]
				  SET
					    [CdeCode]  = @Code,
					    [CdeDesc] = @Description,
					    [Retired] = @Retired
				  WHERE
						RTRIM([CdeCode])=@Code AND [CdeType] ='IRT'
			 END
		 ELSE
			 BEGIN
				  INSERT INTO
							[dbo].[MiscCodes] 
							([CdeType],
							 [CdeCode],
							 [CdeDesc],
							 [Retired])
				  VALUES
							('IRT',
							@Code,
							@Description,
							@Retired)
			 END
	 END
	 
	 ELSE IF (@MasterName='CourtFees')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[CourtFees] WHERE RTRIM([Code])=@Code)
			BEGIN
				UPDATE 
						[dbo].[CourtFees]
				SET
						[Code] = @Code,
						[Description] = @Description,
						[ChargeClient] = @clientCharge,
						[Value] = @value,
						[ClientValue] = @ClientValue
				WHERE
						[Code] = @Code
			END
		  ELSE
			BEGIN
				INSERT INTO 
						[dbo].[CourtFees] 
						([Code],
						[Description],
						[ChargeClient],
						[Value],
						[ClientValue])
				VALUES 
					   (@Code,
						@Description,
						@clientCharge,
						@value,
						@ClientValue)
			END
	 END


	 ELSE IF (@MasterName='SMSTemplates')
	 BEGIN
		 IF EXISTS(SELECT  TOP 1 1  FROM [dbo].[SMSMessageTemplates] WHERE RTRIM([Code])=@Code)
			BEGIN
				UPDATE 
						[dbo].[SMSMessageTemplates]
				SET
						[Code] = @Code,
						[Message] = @Description,
						[Retired] = CASE WHEN @Retired = 'Y' THEN 1 ELSE 0 END
				WHERE
						[Code] = @Code
			END
		  ELSE
			BEGIN
				INSERT INTO 
						[dbo].[SMSMessageTemplates] 
						([Code],
						[Message],
						[Retired])
				VALUES 
					   (@Code,
						@Description,
						CASE WHEN @Retired = 'Y' THEN 1 ELSE 0 END)
			END
	 END
	 
	 SET @Result=1 
	 END
END

GO

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

CREATE PROCEDURE
       [dbo].[KAAS_MatterOpenClosed]
      (@Matter VARCHAR(20),
       @Closed CHAR(1))
AS
/************************************************************************************
 * Process to reopen closed matter records from archive enquiry                      *
*																					 *
* Stored Procedure Name : [dbo].[KAAS_MatterOpenClosed]
* Copied From : [dbo].[ky_NETToggleMatterOpenClosed]
*                                                                                    *
* Modification History:                                                              *
* 2022-05-31     Ghayathri.S.V        Created                                        *
 ************************************************************************************/
BEGIN

DECLARE @XML    NVARCHAR(MAX)
DECLARE @Return INT

SET @XML = CONVERT(NVARCHAR(MAX),
                   (SELECT *
                      FROM (SELECT @Matter AS [Matter],
                                   @Closed AS [Closed],
                                   0       AS [KeepOriginalCloseDate]) [Data]
                       FOR XML AUTO))

EXEC [dbo].[KAAS_MatterOpenClosedXML] @XML

END


GO


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

CREATE PROCEDURE
       [dbo].[KAAS_MatterOpenClosedXML]
      (@XML NVARCHAR(MAX))
AS
/************************************************************************************
 * Stored Procedure Name :  [dbo].[KAAS_MatterOpenClosedXML]
 * Copied From : [dbo].[ky_NETToggleMatterOpenClosedXML]
 * 
 * Re-open/close a matter
 *
 * Modification History:                                                              *
 * 2022-05-31     Ghayathri.S.V        Created  
 ************************************************************************************/
BEGIN
    
DECLARE @MATTER VARCHAR(20)
DECLARE @Closed VARCHAR(1)
DECLARE @KEEPORIGINALCLOSEDATE BIT

DECLARE @iSL INT

BEGIN TRY
EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
END TRY
BEGIN CATCH
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<Data />'
END CATCH

SELECT @MATTER                = [XML].[Matter],
       @Closed                = [XML].[Closed],
       @KEEPORIGINALCLOSEDATE = ISNULL([XML].[KeepOriginalCloseDate], 0)
  FROM OPENXML(@iSL, N'Data')
  WITH ([Matter]                VARCHAR(20) '@Matter',
        [Closed]                VARCHAR(1)  '@Closed',
        [KeepOriginalCloseDate] BIT         '@KeepOriginalCloseDate') AS [XML]
        
BEGIN TRY
EXEC sp_xml_removedocument @iSL
END TRY
BEGIN CATCH
END CATCH

-- Don't execute if parameters are invalid
IF ISNULL(@MATTER, '') = '' OR ISNULL(@Closed, '') = ''
BEGIN
    RETURN 
END

-- Original procedure code from here down
DECLARE @AlreadyClosed              INT
DECLARE @HasOutstandingBal          INT
DECLARE @HasOutstandingTimeBal      INT
DECLARE @HasOutstandingChargeBal    INT
DECLARE @HasOutstandingRec          INT
DECLARE @HasOutstandingDiary        INT
DECLARE @HasOutstandingUndertakings INT
DECLARE @HasUnallocatedReceipts     INT
DECLARE @HasDraftBills              INT
DECLARE @ClientCode                 VARCHAR(10)

DECLARE @Closables TABLE
       ([AlreadyClosed]              INT,
        [HasOutstandingBal]          INT,
        [HasOutstandingTimeBal]      INT,
        [HasOutstandingChargeBal]    INT,
        [HasOutstandingRec]          INT,
        [HasOutstandingDiary]        INT,
        [HasOutstandingUndertakings] INT,
        [HasUnallocatedReceipts]     INT,
        [HasDraftBills]              INT)

INSERT
  INTO @Closables
      ([AlreadyClosed],
       [HasOutstandingBal],
       [HasOutstandingTimeBal],
       [HasOutstandingChargeBal],
       [HasOutstandingRec],
       [HasOutstandingDiary],
       [HasOutstandingUndertakings],
       [HasUnallocatedReceipts],
       [HasDraftBills])
  EXEC [dbo].[KAAS_ReopenMatterClosable] @MATTER

SELECT @AlreadyClosed              = [MATS].[AlreadyClosed],
       @HasOutstandingBal          = [MATS].[HasOutstandingBal],
       @HasOutstandingTimeBal      = [MATS].[HasOutstandingTimeBal],
       @HasOutstandingChargeBal    = [MATS].[HasOutstandingChargeBal],
       @HasOutstandingRec          = [MATS].[HasOutstandingRec],
       @HasOutstandingDiary        = [MATS].[HasOutstandingDiary],
       @HasOutstandingUndertakings = [MATS].[HasOutstandingUndertakings],
       @HasUnallocatedReceipts     = [MATS].[HasUnallocatedReceipts],
       @HasDraftBills              = [MATS].[HasDraftBills]
  FROM @Closables MATS

IF NOT (@AlreadyClosed IS NULL)
  BEGIN
    IF (@AlreadyClosed = 1)
      BEGIN
        IF (@Closed = 'N')
          BEGIN
            UPDATE MAT
               SET MAT.[OrgClosedDate] = CASE WHEN @KEEPORIGINALCLOSEDATE = 1
                                                   THEN [MAT].[OrgClosedDate]
                                              ELSE MAT.[CloseDate] END,
                   MAT.[CloseDate] = NULL,
                   --MAT.[DestroyDate] = NULL,
                   MAT.[ReOpenedDate] = GetDate(),
                   MAT.[Closed] = 'N'
              FROM [dbo].[matters] MAT
             WHERE MAT.[Code] = @MATTER
          END
      END
    ELSE
      BEGIN
        IF (@Closed = 'Y') AND (@HasOutstandingBal = 0) AND (@HasOutstandingDiary = 0) AND (@HasOutstandingUndertakings = 0) AND (@HasUnallocatedReceipts = 0)
          BEGIN
            UPDATE MAT
               SET MAT.[CloseDate] = GetDate(),
                   MAT.[ReOpenedDate] = NULL,
                   MAT.[Closed] = 'Y'
              FROM [dbo].[matters] MAT
             WHERE MAT.[Code] = @MATTER

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

  SELECT @ClientCode = MAT.[ClientCode]
    FROM [dbo].[matters] MAT
   WHERE MAT.[Code] = @MATTER

  IF RTRIM(ISNULL(@ClientCode, '')) <> ''
    BEGIN
        /* Update our contact's LastMatter and OpenMatters */
        EXEC [dbo].[KAAS_UpdateContactLastMatter] @ClientCode
    END
END

GO



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


CREATE PROCEDURE
       [dbo].[KAAS_OffSetGetClosedMatters]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Code',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 * Stored Procedure Name : [dbo].[KAAS_OffSetGetClosedMatters]   			        *
 * Modification History:  															*
 * 2021-06-29   Ghayathri S.V	Created to Fetch the Closed Matter details for SAM 
 * 2021-07-05   Ghayathri S.V	Modified to implement dynamic sql query to fetch sort
								and search datas 
 * 2022-08-10    Ghayathri.S.V	Modified - To add FeCode column 
										   for server side pagination search
 ************************************************************************************/
BEGIN

DECLARE		   @sql        NVARCHAR(max)
DECLARE	    @search		   NVARCHAR(500) = ''
DECLARE		@offset		   INT = @PageSize * (@PageNumber -1)




SET			@sql =		'SELECT		A.[Code]					AS [Code], 
									A.[FECODE]					AS [FECode], 
									B.[Name]					AS [Name],
									A.[Description]				AS [Description], 
									A.[OldRef]					AS [OldRef], 
									A.[FileNum]					AS [FileNum], 
									A.[Dept]					AS [Dept], 
									A.[WTYPE]					AS [WorkType], 
									A.[User1]					AS [Ref1], 
									A.[User2]					AS [Ref2], 
									A.[User3]					AS [Ref3], 
									A.[CloseDate]				AS [CloseDate],
									A.[OrgClosedDate]			AS [OriginalClosedDate],
									A.[ReOpenedDate]			AS [ReopenedDate],
									B.[Address]					AS [Address],
									A.[Comment]					AS [Comment]
					      FROM	 	[dbo].[Matters] A 
			         LEFT JOIN		[dbo].[contacts] B 
		                    ON		A.[CLIENTCODE]= B.[CODE]   
	                     WHERE		[Closed] = ''Y''' +  
		                  'AND       ( 
										A.[Matter] LIKE' + '''%' + @SearchString + '%' + '''' +
										'OR
										A.[Description] LIKE ' + '''%' + @SearchString + '%' + '''' +
										'OR
										A.[Code] LIKE ' + '''%' + @SearchString + '%' + '''' +
										'OR
										A.[FECODE] LIKE ' + '''%' + @SearchString + '%' + '''' +'
									 )
					 ORDER BY ' +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET ' +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT ' +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

EXEC Sp_executesql @sql

						SELECT      COUNT(*)  'TotalRecord'
						  FROM      [dbo].[Matters] A 
						 WHERE 	    [Closed] = 'Y'  
						AND			( 
										 A.[Matter] LIKE '%' + @SearchString + '%' 
										OR
										A.[Description] LIKE '%' + @SearchString + '%' 
										OR
										A.[Code] LIKE '%' + @SearchString + '%' 
										OR
										A.[FECODE] LIKE '%' + @SearchString + '%'
									)
END

GO


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


CREATE PROCEDURE
       [dbo].[KAAS_OffsetGetOpenMatterDetails]
	    ( 
			 @Search        NVARCHAR(MAX),    
			 @PageNumber    INT,    
			 @PageSize      INT,
	         @ColumnNames   VARCHAR(50) = '',
	         @FilterValues  VARCHAR(50) = '',
	         @orderby       NVARCHAR(50)= '',    
             @order         NVARCHAR(4) = '',
			 @Mode			VARCHAR(10) = 'Grid' 
		 )
AS
/************************************************************************************ *
 * Fetching Open Matter Details														  *
 * Stored Procedure Name : [dbo].[KAAS_OffsetGetOpenMatterDetails]                    *
 * Copied from			 : [dbo].[KAAS_XMLMatterSearch]                               *
 * Modification History:  													          *																		  
 * 2022-07-05   Ghayathri S.V	Created to Fetch the Browse Matter details for SAM    *
								using dynamic query and offset functionality          *
 * 2022-09-01   Ghayathri S.V	Implemented logic to fetch recent matter list for     *
								Browse open matters table in SAM                      *
																			          *
 * 2023-09-25   Revathy.D	    Included a column for OpenInvoice details             * 
 * 2023-10-31   Revathy.D	    Modified - Included a column for comments and branch  *
 * 2024-01-19	Balamurugan.C   Modified - Added Dashboard condition for final select *
 * 2024-02-08	Balamurugan.C   Modified - Added Contact Name and Matter Description  *
 * 2024-03-14	Vignesh M		Modified - As per Client suggestion
								Handler privileges has been hidden					  *	
************************************************************************************/
BEGIN
      

DECLARE @closed                 NCHAR(1)      
DECLARE @howmany                INT
DECLARE @handler                NVARCHAR(10)
DECLARE @which                  INT      
DECLARE @BitWiseID              BIGINT      
DECLARE @searchtext             VARCHAR(MAX)      
DECLARE @searchonlycode         VARCHAR(3)      
DECLARE @departmentdesc         VARCHAR(50)      
DECLARE @department             VARCHAR(5)      
DECLARE @worktypedesc           VARCHAR(50)      
DECLARE @worktype               VARCHAR(5)      
DECLARE @filecolourdesc         VARCHAR(20)      
DECLARE @filecolour             VARCHAR(3)      
DECLARE @feecode                VARCHAR(10)      
      
DECLARE @includename            BIT      
DECLARE @includedescription     BIT      
DECLARE @includeaddress         BIT      
DECLARE @includeemail           BIT      
DECLARE @includecode            BIT      
DECLARE @includeoldref          BIT      
DECLARE @includeuser1           BIT      
      
DECLARE @andorname              VARCHAR(3)      
DECLARE @andornamevalue         VARCHAR(200)      
DECLARE @andordescription       VARCHAR(3)      
DECLARE @andordescriptionvalue  VARCHAR(200)      
DECLARE @andoraddress           VARCHAR(3)      
DECLARE @andoraddressvalue      VARCHAR(200)      
DECLARE @andorcode              VARCHAR(3)      
DECLARE @andorcodevalue         VARCHAR(200)      
DECLARE @andorfeecode           VARCHAR(3)      
DECLARE @andorfeecodevalue      VARCHAR(200)      
DECLARE @andoroldref            VARCHAR(3)      
DECLARE @andoroldrefvalue       VARCHAR(200)      
DECLARE @andordept              VARCHAR(3)      
DECLARE @andordeptvalue         VARCHAR(200)      
DECLARE @andoruser1             VARCHAR(3)      
DECLARE @andoruser1value        VARCHAR(200)      
DECLARE @andoruser2             VARCHAR(3)      
DECLARE @andoruser2value        VARCHAR(200)      
DECLARE @andoruser3             VARCHAR(3)      
DECLARE @andoruser3value        VARCHAR(200)      
DECLARE @andoryourref           VARCHAR(3)      
DECLARE @andoryourrefvalue      VARCHAR(200)      
DECLARE @andorwtype             VARCHAR(3)      
DECLARE @andorwtypevalue        VARCHAR(200)      
      
DECLARE @iSL INT      
    
DECLARE @StartRow INT;      
DECLARE @EndRow INT;

--FOR DEFAULT DATE; USE OF PARAMETERIZATION
DECLARE @DefaultDate VARCHAR(8) = '18000101';
DECLARE @DefaultDaybookDate VARCHAR(8) = '19000101';

SET NOCOUNT ON
    
SET @PageNumber = ISNULL(@PageNumber, 0) - 1; -- 0 BASED INDEX
        
IF(@PageNumber > -1)
BEGIN        
	SET @StartRow = ((@PageNumber) * @PageSize) + 1;
	SET @EndRow = (@StartRow + @PageSize) - 1;
END   
      
BEGIN TRY      
EXEC sp_xml_preparedocument @iSL OUTPUT, @Search      
END TRY      
BEGIN CATCH      
EXEC sp_xml_preparedocument @iSL OUTPUT, N'<search/>'      
END CATCH      
      
SELECT @closed = CASE ISNULL(SRC.[closed], N'A')      
                      WHEN N'Y' THEN N'Y'   
                      WHEN N'B' THEN N'B'    
					  WHEN N'N' THEN N'N'   
					  WHEN N'A' THEN N'A'   
                       END,      
       @orderby = ISNULL(SRC.[orderby], N''),      
       @order = CASE ISNULL(SRC.[order], N'DESC')
                     WHEN N'DESC'      
                          THEN N'DESC'      
                     ELSE N'ASC' END,      
       @howmany = ISNULL(SRC.[howmany], 500),      
       @handler = ISNULL(SRC.[handler], N''),      
       @which = CASE ISNULL(SRC.[which], 0)      
                     WHEN 1 THEN 1 --My Matters      
                     WHEN 2 THEN 2 --Recent Matters      
                     ELSE 0 END,   --All Matters      
       @searchtext = ISNULL(SRC.[search], ''),      
       @searchonlycode = ISNULL(SRC.[searchonlycode], ''),      
       @departmentdesc = ISNULL(SRC.[dept], ''),      
       @worktypedesc = ISNULL(SRC.[wtype], ''),      
       @filecolourdesc = ISNULL(SRC.[colour], ''),      
       @feecode = ISNULL(SRC.[feecodefilter], ''),      
       @includeaddress = ISNULL(SRC.[includeaddress], 0),      
       @includeemail = ISNULL(SRC.[includeemail], 0),      
       @includecode = ISNULL(SRC.[includecode], 0),      
       @includedescription = ISNULL(SRC.[includedescription], 0),      
       @includename = ISNULL(SRC.[includename], 0),      
       @includeoldref = ISNULL(SRC.[includeoldref], 0),      
       @includeuser1 = ISNULL(SRC.[includeuser1], 0),      
       @andorname = ISNULL(SRC.[andorname], ''),      
       @andornamevalue = ISNULL(SRC.[andornamevalue], ''),      
       @andordescription = ISNULL(SRC.[andordescription], ''),      
       @andordescriptionvalue = ISNULL(SRC.[andordescriptionvalue], ''),      
       @andoraddress = ISNULL(SRC.[andoraddress], ''),      
       @andoraddressvalue = ISNULL(SRC.[andoraddressvalue], ''),      
       @andorcode = ISNULL(SRC.[andorcode], ''),      
       @andorcodevalue = ISNULL(SRC.[andorcodevalue], ''),      
       @andorfeecode = ISNULL(SRC.[andorfeecode], ''),      
       @andorfeecodevalue = ISNULL(SRC.[andorfeecodevalue], ''),      
       @andoroldref = ISNULL(SRC.[andoroldref], ''),      
       @andoroldrefvalue = ISNULL(SRC.[andoroldrefvalue], ''),      
       @andordept = ISNULL(SRC.[andordept], ''),      
       @andordeptvalue = ISNULL(SRC.[andordeptvalue], ''),      
       @andoruser1 = ISNULL(SRC.[andoruser1], ''),      
       @andoruser1value = ISNULL(SRC.[andoruser1value], ''),      
       @andoruser2 = ISNULL(SRC.[andoruser2], ''),      
       @andoruser2value = ISNULL(SRC.[andoruser2value], ''),      
       @andoruser3 = ISNULL(SRC.[andoruser3], ''),      
       @andoruser3value = ISNULL(SRC.[andoruser3value], ''),      
       @andoryourref = ISNULL(SRC.[andoryourref], ''),      
       @andoryourrefvalue = ISNULL(SRC.[andoryourrefvalue], ''),      
       @andorwtype = ISNULL(SRC.[andorwtype], ''),      
       @andorwtypevalue = ISNULL(SRC.[andorwtypevalue], '')      
  FROM OPENXML(@iSL, N'search')      
  WITH ([closed]                   NCHAR(1)        '@closed',      
        [orderby]                  NVARCHAR(50)    '@orderby',      
        [order]                    NVARCHAR(4)     '@order',      
        [howmany]                  INT             '@howmany',      
        [handler]                  NVARCHAR(10)    '@handler',      
        [which]                    INT             '@which',      
        [search]                   VARCHAR(MAX)    '@search',      
        [searchonlycode]           VARCHAR(3)      '@searchonlycode',      
        [dept]                     VARCHAR(50)     '@departmentfilter',      
        [wtype]                    VARCHAR(50)     '@worktypefilter',      
        [colour]                   VARCHAR(20)     '@filecolourfilter',      
        [feecodefilter]            VARCHAR(10)     '@feecodefilter',      
        [includeaddress]           BIT             'include/includefield[@name="address"]',      
        [includecode]              BIT             'include/includefield[@name="code"]',      
        [includedescription]       BIT             'include/includefield[@name="description"]',      
        [includename]              BIT             'include/includefield[@name="name"]',      
        [includeoldref]            BIT             'include/includefield[@name="oldref"]',      
        [includeuser1]             BIT             'include/includefield[@name="user1"]',      
        [includeemail]             BIT             'include/includefield[@name="email"]',      
        [andorname]                VARCHAR(3)      'andor/andorfield[@name="name"]/@andor',      
        [andornamevalue]           VARCHAR(100)    'andor/andorfield[@name="name"]/@search',      
        [andordescription]         VARCHAR(3)      'andor/andorfield[@name="description"]/@andor',      
        [andordescriptionvalue]    VARCHAR(100)    'andor/andorfield[@name="description"]/@search',      
        [andoraddress]             VARCHAR(3)      'andor/andorfield[@name="address"]/@andor',      
        [andoraddressvalue]        VARCHAR(100)    'andor/andorfield[@name="address"]/@search',      
        [andorcode]                VARCHAR(3)      'andor/andorfield[@name="code"]/@andor',      
        [andorcodevalue]           VARCHAR(100)    'andor/andorfield[@name="code"]/@search',      
        [andorfeecode]             VARCHAR(3)      'andor/andorfield[@name="feecode"]/@andor',      
        [andorfeecodevalue]        VARCHAR(100)    'andor/andorfield[@name="feecode"]/@search',      
        [andoroldref]              VARCHAR(3)      'andor/andorfield[@name="oldref"]/@andor',      
        [andoroldrefvalue]         VARCHAR(100)    'andor/andorfield[@name="oldref"]/@search',      
        [andordept]                VARCHAR(3)      'andor/andorfield[@name="dept"]/@andor',      
        [andordeptvalue]           VARCHAR(100)    'andor/andorfield[@name="dept"]/@search',      
        [andoruser1]               VARCHAR(3)      'andor/andorfield[@name="user1"]/@andor',      
        [andoruser1value]          VARCHAR(100)    'andor/andorfield[@name="user1"]/@search',      
        [andoruser2]               VARCHAR(3)      'andor/andorfield[@name="user2"]/@andor',      
        [andoruser2value]          VARCHAR(100)    'andor/andorfield[@name="user2"]/@search',      
        [andoruser3]               VARCHAR(3)      'andor/andorfield[@name="user3"]/@andor',      
        [andoruser3value]          VARCHAR(100)    'andor/andorfield[@name="user3"]/@search',      
        [andoryourref]             VARCHAR(3)      'andor/andorfield[@name="yourref"]/@andor',      
        [andoryourrefvalue]        VARCHAR(100)    'andor/andorfield[@name="yourref"]/@search',      
        [andorwtype]               VARCHAR(3)      'andor/andorfield[@name="wtype"]/@andor',      
        [andorwtypevalue]          VARCHAR(100)    'andor/andorfield[@name="wtype"]/@search') SRC      
      
IF @filecolourdesc <> ''      
  BEGIN      
    SELECT @filecolour = FC.[COLOURCODE]      
      FROM [dbo].[FileColours] FC WITH (NOLOCK)      
     WHERE FC.[COLOURDESC] = @filecolourdesc      
  END      
      
SET @filecolour = ISNULL(@filecolour, '')      
      
IF @departmentdesc <> ''      
  BEGIN      
    SELECT @department = DP.[CODE]      
      FROM [dbo].[Departments] DP WITH (NOLOCK)      
     WHERE DP.[DESCRIPTION] = @departmentdesc      
  END      
      
SET @department = ISNULL(@department, '')      
      
IF @worktypedesc <> ''      
  BEGIN      
    IF @worktypedesc LIKE 'Unknown Worktype: %'      
      BEGIN      
        SELECT @worktype = WT.[CODE]      
          FROM [dbo].[WorkTypes] WT WITH (NOLOCK)      
         WHERE 'Unknown Worktype: ' + WT.[CODE] = @worktypedesc      
            OR WT.[DESC] = @worktypedesc      
      END      
    ELSE      
      BEGIN      
        SELECT @worktype = WT.[CODE]      
          FROM [dbo].[WorkTypes] WT WITH (NOLOCK)      
         WHERE WT.[DESC] = @worktypedesc      
      END      
  END      
      
SET @worktype = ISNULL(@worktype, '')      
      
SET @feecode = ISNULL(@feecode, '')      
      
EXEC sp_xml_removedocument @iSL      
      
DECLARE @NCOMMAND NVARCHAR(MAX)      
DECLARE @HasWhere BIT      
      
SET @HasWhere = 0      
      
SET @handler = CASE WHEN RTRIM(ISNULL(@handler, '')) = '' THEN 'ADM' ELSE RTRIM(@handler) END      
      
SELECT @BitWiseID = HNG.[BitWiseID]      
  FROM HandlerNETGroupMembership HNG WITH (NOLOCK)      
 WHERE HNG.[HANDLER] = CONVERT(VARCHAR(10), @handler)      
      
SET @BitWiseID = ISNULL(@BitWiseID, [dbo].[KAAS_FN_GetOldPermissions](RTRIM(ISNULL(@handler, ''))))      
      
IF (@handler = 'ADM')      
  BEGIN      
    SET @BitWiseID = CONVERT(BIGINT, -1)      
  END     
  
  -- Custom Filter Start
SET @NCOMMAND = N'   
DECLARE @StatusCount INT = 0;
IF @ColumnNames <> ''''
BEGIN
DECLARE @CustomFilter TABLE
       ([Status]     VARCHAR(20))	

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

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

	DECLARE @count INT
	DECLARE @lptcnt INT=1
	
	DECLARE @ColumnName VARCHAR(50)
	DECLARE @FilterValue VARCHAR(2000)

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

	WHILE @lptcnt <= @count
	BEGIN

	   SET @FilterValue =''''
	   SELECT @ColumnName = columnName FROM #columntbl WHERE rownumber = @lptcnt
	   SELECT @FilterValue = FilterValue FROM #FILTERVALUETBL WHERE rownumber = @lptcnt
	   IF(@ColumnName = ''Closed'')
		INSERT INTO @CustomFilter ([Status]) VALUES (@FilterValue)	   

	   SET @lptcnt = @lptcnt + 1;   

	END
	
	SET @StatusCount = (SELECT COUNT(1) FROM @CustomFilter WHERE [Status] IS NOT NULL AND [Status] <>'''')	
	
END '
-- Custom Filter End

SET @NCOMMAND = @NCOMMAND + N'      
  --SELECT ''How Many: '' + CONVERT(VARCHAR(10), @HowMany)      
  --SELECT ''Handler: '' + @Handler      
  --SELECT ''BitWise ID: '' + CONVERT(VARCHAR(10), @BitWiseID)      
      
DECLARE @Result TABLE      
       ([id]                    INT                       IDENTITY(1, 1) PRIMARY KEY CLUSTERED,      
        [Time]                  VARCHAR(5)                NOT NULL,      
        [Code]                  VARCHAR(20)               NOT NULL,      
        [FileColour]            VARCHAR(20)               NOT NULL,      
        [FileColour_Fld]        VARCHAR(20)               NOT NULL,      
        [BackgroundColour]      VARCHAR(30)               NOT NULL,      
        [TextColour]            VARCHAR(30)               NOT NULL,      
        [Name]                  VARCHAR(256)              NOT NULL,      
        [Description]           VARCHAR(200)              NOT NULL,      
        [Fe]                    VARCHAR(30)               NOT NULL,      
        [FeeCode]               VARCHAR(10)               NOT NULL,      
        [FeeEarner]             VARCHAR(30)               NOT NULL,      
        [User1]                 VARCHAR(100)              NOT NULL,      
        [User2]                 VARCHAR(100)              NOT NULL,      
        [User3]                 VARCHAR(100)              NOT NULL,      
        [Started]               DATETIME                  NOT NULL,      
        [Dept]                  VARCHAR(50)               NOT NULL,      
        [WorkType]              VARCHAR(50)               NOT NULL,      
        [Privileges]            BIGINT                    NOT NULL,      
        [OldRef]                VARCHAR(12)               NOT NULL,      
        [Address]               VARCHAR(500)              NOT NULL,      
        [Email]                 VARCHAR(50)               NOT NULL,      
        [Closed]                CHAR(1)                   NOT NULL,      
        [OrgCloseDate]          DATETIME                      NULL,      
        [CloseDate]             DATETIME                      NULL,      
        [FileRGBColour]         INT                       NOT NULL,      
        [LastAccessed]          DATETIME                      NULL,      
        [PhoneNumber]           VARCHAR(50)               NOT NULL,      
        [FileNum]               INT                       NOT NULL,      
        [ClientCode]            VARCHAR(10)               NOT NULL,      
        [DepartmentCode]        VARCHAR(5)                NOT NULL,      
        [FeeEarnerTeam]         VARCHAR(10)               NOT NULL,      
        [TeamName]              VARCHAR(30)               NOT NULL,      
        [YourRef]               VARCHAR(100)              NOT NULL,      
        [CaseStatusCode]        VARCHAR(6)                NOT NULL,      
        [CaseStatusDesc]        VARCHAR(50)               NOT NULL,
		[OutlayBal]				DECIMAL(9)					 NULL,
		[ClientCurBal]          DECIMAL(9)                   NULL,
		[ClientDepBal]          DECIMAL(9)                   NULL,
		[Comment]				        VARCHAR(3000)			       NOT NULL,
		[Branch]                VARCHAR(3)					         NULL,
		[OpenInvoiceNo]         INT                      NOT NULL,
		[ContactName]			VARCHAR(256)			 NULL,
		[MatterDesc]      VARCHAR(200)			 NULL
		)      
      
  INSERT      
    INTO @Result      
        ([Time],      
         [Code],      
         [FileColour],
         [FileColour_Fld],      
         [BackgroundColour],      
         [TextColour],      
         [Name],      
         [Description],      
         [Fe],      
         [FeeCode],      
         [FeeEarner],      
         [User1],      
         [User2],      
         [User3],      
         [Started],      
         [Dept],      
         [WorkType],      
		 [Privileges],      
         [OldRef],      
         [Address],      
         [Email],      
         [Closed],      
         [OrgCloseDate],      
         [CloseDate],      
         [FileRGBColour],      
         [LastAccessed],      
         [PhoneNumber],      
         [FileNum],      
         [ClientCode],      
         [DepartmentCode],      
         [FeeEarnerTeam],      
         [TeamName],      
         [YourRef],      
         [CaseStatusCode],      
         [CaseStatusDesc],
		 [OutlayBal],
		 [ClientCurBal],
		 [ClientDepBal],
		 [Comment],
		 [Branch],
		 [OpenInvoiceNo],
		 [ContactName],
		 [MatterDesc]
		 )      
    
  SELECT      
         CASE WHEN TTT.[TOTALTIME] = ''00:00''      
                   THEN ''''      
              ELSE TTT.[TOTALTIME] END													  AS [Time],      
         SM.[Code]                                                                        AS [Code],      
         SM.[FileColourDescription]                                                       AS [FileColour],      
         SM.[FileColourDescription]                                                       AS [FileColour_Fld],      
         SM.[FileBackgroundColour]                                                        AS [BackgroundColour],      
         SM.[TextColour]                                                                  AS [TextColour],      
         SM.[Name]                                                                        AS [Name],      
         RTRIM(ISNULL(SM.[Description],''''))                                             AS [Description],      
         SM.[HandlerName]                                                                 AS [Fe],      
         RTRIM(ISNULL(A.[FECode],''''))                                                   AS [FeeCode],      
         SM.[HandlerName]                                                                 AS [FeeEarner],      
         RTRIM(ISNULL(A.[User1],''''))                                                    AS [User1],      
         RTRIM(ISNULL(A.[User2],''''))                                                    AS [User2],      
         RTRIM(ISNULL(A.[User3],''''))                                                    AS [User3],      
         SM.[Started]                                                                     AS [Started],      
         RTRIM(ISNULL(A.[Dept],''''))                                                     AS [Dept],      
         RTRIM(ISNULL(A.[WType],''''))                                                    AS [WorkType],      
         SM.[Privileges]                                                                  AS [Privileges],      
         RTRIM(ISNULL(A.[OldRef],''''))                                                   AS [OldRef],      
         SM.[Address]                                                                     AS [Address],      
         SM.[Email]                                                                       AS [Email],      
         CASE WHEN SM.[Closed] = 0 THEN ''N'' ELSE ''Y'' END                              AS [Closed],      
         SM.[OrgClosedDate]                                                               AS [OriginalClosedDate],      
         SM.[CloseDate]                                                                   AS [CloseDate],      
         SM.[FileRGBColour]                                                               AS [FileRGBColour],      
         CASE WHEN YEAR(ISNULL(RML.[DateField], CONVERT(DATETIME, @DefaultDate))) < 1901      
                   THEN NULL      
              ELSE ISNULL(RML.[DateField], CONVERT(DATETIME, @DefaultDate)) END           AS [LastAccessed],      
         SM.[PhoneNumber]                                                                 AS [PhoneNumber],      
         SM.[FileNum]                                                                     AS [FileNum],      
         SM.[ClientCode]                                                                  AS [ClientCode],      
         RTRIM(ISNULL(A.[Dept],''''))                                                     AS [DepartmentCode],      
         SM.[Team]                                                                        AS [FeeEarnerTeam],      
         SM.[TeamName]                                                                    AS [TeamName],      
         RTRIM(ISNULL(A.[YourRef],''''))                                                  AS [YourRef],      
         SM.[MatterStatus]                                                                AS [CaseStatusCode],      
         SM.[MatterStatusDescription]                                                     AS [CaseStatusDesc],
		  A.[OutlayBal]																	  AS [OutlayBal],
		  A.[ClientCurBal]																  AS [ClientCurBal],
		  A.[ClientDepBal]																  AS [ClientDepBal],
		    RTRIM(ISNULL(A.[Comment], ''''))                                                  AS [Comment],
		    RTRIM(ISNULL(A.[Branch], ''''))                                                   AS [Branch],
		  (SELECT COUNT(1) FROM [dbo].[BillHeader] [BH]
                       WHERE ISNULL([BH].[OPENINVOICE], '''') = ''Y''
                         AND ISNULL([BH].[BILLNO], 0) = 0
						 AND [BH].[MATTER] = SM.[Code])									  AS [OpenInvoiceNo],
		B.[Name]																		  AS [ContactName],
	   RTRIM(ISNULL(A.[Description],''''))												  AS [MatterDesc] 
    FROM				[dbo].[SearchMatters] SM WITH (NOLOCK)      
	LEFT JOIN			[dbo].[Matters] A  ON A.[CODE] =  SM.[Code]
	LEFT OUTER JOIN		[dbo].[contacts] B ON  A.[CLIENTCODE]= B.[CODE]    
    CROSS APPLY			(SELECT SUBSTRING(CONVERT(VARCHAR, DATEADD(minute, ISNULL(SUM(ISNULL(TDB.[time], 0)), 0), @DefaultDaybookDate), 108), 1, 5) AS [TOTALTIME]      
                        FROM [dbo].[TimeDayBook] TDB WITH (NOLOCK)      
						WHERE TDB.[FeeEarn] = @handler      
                         AND TDB.[matter] = SM.[code]
					     ) TTT'      
      
SET @NCOMMAND = @NCOMMAND + N'      
         LEFT OUTER JOIN [dbo].[RecentMatterList] RML WITH (NOLOCK)      
       ON RML.[FEE] = @handler      
                     AND RML.[MATTER] = SM.[Code]
	      WHERE (@StatusCount = 0 OR (SM.[Closed] IN (SELECT FilterValue FROM 
															(SELECT LTRIM(RTRIM(m.n.value(''.[1]'',''varchar(8000)''))) AS FilterValue , ROW_NUMBER() OVER (ORDER BY (SELECT 1)) as rownumber
															 FROM(
																SELECT CAST(''<XMLRoot><RowData>'' + REPLACE((SELECT DISTINCT [Status] FROM @CustomFilter WHERE [Status] IS NOT NULL and [Status] <>''''),'','',''</RowData><RowData>'') + ''</RowData></XMLRoot>'' AS XML) AS x
																)t
																CROSS APPLY x.nodes(''/XMLRoot/RowData'')m(n)) FILTERVALUETBLFnl))  or SM.Closed=1)
				AND A.[Closed] <> ''Y''' 
/*   
--Handler Privileges
IF (@BitWiseID = 0)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   AND (   SM.[Privileges] = 0      
          OR SM.[Privileges] = -1)'      
  END      
ELSE IF (@BitWiseID = -1)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   AND 1 = 1'      
  END      
ELSE      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
   AND SM.[Privileges] & @BitWiseID <> 0'      
  END      
*/      
IF (@which = 1)      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode] = @handler'      
  END      
      
IF (@closed = 'N')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Closed] = 0'      
  END      
      
IF (@closed = 'Y')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Closed] = 1'      
  END      

IF (@closed = N'A')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND (SM.[Closed] = 0 OR SM.[Closed] = 1)'      
  END 
      
IF (@worktype <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[WType] = @WorkType'      
  END      
      
IF (@department <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Dept] = @department'      
  END      
      
IF (@filecolour <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FileColour] = @filecolour'      
  END      
      
IF (@feecode <> '')      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode] = @feecode'      
  END      
      
DECLARE @SearchIncludes NVARCHAR(MAX)      
      
SET @SearchIncludes = N''      
      
IF (@searchtext <> '')      
  BEGIN      
    IF SUBSTRING(@searchtext, 1, 1) <> '%'      
      BEGIN      
        SET @searchtext = '%' + @searchtext      
      END      
      
    IF SUBSTRING(@searchtext, LEN(@searchtext), 1) <> '%'      
      BEGIN      
        SET @searchtext = @searchtext + '%'      
      END      
      
    SET @searchtext = @searchtext COLLATE SQL_Latin1_General_Cp1251_CS_AS      
          
     IF (@includeaddress = 0)       
    AND (@includecode = 0)      
    AND (@includedescription = 0)      
    AND (@includename = 0)      
    AND (@includeoldref = 0)      
    AND (@includeuser1 = 0)      
    AND (@includeemail = 0)      
      BEGIN      
        -- This is the standard call - not from Advanced Matter Search, so we search in everything      
        IF @SearchIncludes <> N''      
          BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
          END      
      
        IF @searchonlycode <> 'yes'      
          BEGIN      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]         LIKE @searchtext      
          OR SM.[Code]                     LIKE @searchtext      
          OR SM.[User1]                    LIKE @searchtext      
          OR SM.[User2]                    LIKE @searchtext      
          OR SM.[User3]                    LIKE @searchtext      
          OR SM.[OldRef]                   LIKE @searchtext      
          OR SM.[YourRef]                  LIKE @searchtext      
          OR SM.[NCName]                   LIKE @searchtext      
          OR SM.[NCAddress]                LIKE @searchtext      
          OR SM.[Email]                    LIKE @searchtext      
          OR SM.[NCHandlerName]            LIKE @searchtext      
          OR SM.[NCPartnerName]            LIKE @searchtext      
          OR SM.[DeptDescription]          LIKE @searchtext      
          OR SM.[WTypeDescription]         LIKE @searchtext      
          OR SM.[FileColourDescription]    LIKE @searchtext      
          OR SM.[MatterStatusDescription]  LIKE @searchtext'      
          END      
        ELSE      
          BEGIN      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Code]                  LIKE @searchtext'      
          END      
      
      END      
    ELSE      
      BEGIN      
        IF (@includeaddress = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCAddress]             LIKE @searchtext'      
          END      
      
        IF (@includecode = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Code]                  LIKE @searchtext'      
          END      
      
        IF (@includedescription = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]         LIKE @searchtext'      
          END      
      
        IF (@includename = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[NCName]                LIKE @searchtext'      
          END      
      
        IF (@includeoldref = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[OldRef]                LIKE @searchtext'      
          END      
      
        IF (@includeuser1 = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[User1]                 LIKE @searchtext'      
          END      
      
        IF (@includeemail = 1)      
          BEGIN      
            IF @SearchIncludes <> N''      
              BEGIN      
                SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
              END      
      
            SET @SearchIncludes = @SearchIncludes + N'SM.[Email]                 LIKE @searchtext'      
          END      
      
      END      
                  
  END      
IF @andoraddress = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoraddressvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = '%' + @andoraddressvalue       
      END      
      
    IF SUBSTRING(@andoraddressvalue, LEN(@andoraddressvalue), 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = @andoraddressvalue + '%'      
      END      
      
    SET @andoraddressvalue = @andoraddressvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCAddress]					LIKE @andoraddressvalue'      
  END      
      
IF @andorcode = 'OR'      
  BEGIN      
    IF CHARINDEX('%', @andorcodevalue, 1) = 0      
      BEGIN      
        IF SUBSTRING(@andorcodevalue, 1, 1) <> '%'      
          BEGIN      
            SET @andorcodevalue = '%' + @andorcodevalue       
          END      
      
        IF SUBSTRING(@andorcodevalue, LEN(@andorcodevalue), 1) <> '%'      
          BEGIN      
            SET @andorcodevalue = @andorcodevalue + '%'      
          END      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[Code]							LIKE @andorcodevalue'      
  END      
      
IF @andordept = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[Dept]= @andordeptvalue'      
  END      
      
IF @andordescription = 'OR'      
  BEGIN      
    IF SUBSTRING(@andordescriptionvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = '%' + @andordescriptionvalue       
      END      
      
    IF SUBSTRING(@andordescriptionvalue, LEN(@andordescriptionvalue), 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = @andordescriptionvalue + '%'      
      END      
      
    SET @andordescriptionvalue = @andordescriptionvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCDescription]			LIKE @andordescriptionvalue'      
  END      
      
IF @andorfeecode = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[FECode] = @andorfeecodevalue'      
  END      
      
IF @andorname = 'OR'      
  BEGIN      
    IF SUBSTRING(@andornamevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andornamevalue = '%' + @andornamevalue       
      END      
      
    IF SUBSTRING(@andornamevalue, LEN(@andornamevalue), 1) <> '%'      
      BEGIN      
        SET @andornamevalue = @andornamevalue + '%'      
      END      
      
    SET @andornamevalue = @andornamevalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[NCName]							LIKE @andornamevalue'      
  END      
      
IF @andoroldref = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoroldrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = '%' + @andoroldrefvalue       
      END      
      
    IF SUBSTRING(@andoroldrefvalue, LEN(@andoroldrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = @andoroldrefvalue + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[OldRef]							LIKE @andoroldrefvalue'      
  END      
      
IF @andoruser1 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser1value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser1value = '%' + @andoruser1value       
      END      
      
   IF SUBSTRING(@andoruser1value, LEN(@andoruser1value), 1) <> '%'      
      BEGIN      
        SET @andoruser1value = @andoruser1value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User1]						  LIKE @andoruser1value'      
  END      
      
IF @andoruser2 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser2value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser2value = '%' + @andoruser2value       
      END      
      
    IF SUBSTRING(@andoruser2value, LEN(@andoruser2value), 1) <> '%'      
      BEGIN      
        SET @andoruser2value = @andoruser2value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User2]						   LIKE @andoruser2value'      
  END      
      
IF @andoruser3 = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoruser3value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser3value = '%' + @andoruser3value       
      END      
      
    IF SUBSTRING(@andoruser3value, LEN(@andoruser3value), 1) <> '%'      
      BEGIN      
        SET @andoruser3value = @andoruser3value + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[User3]						   LIKE @andoruser3value'      
  END      
      
IF @andorwtype = 'OR'      
  BEGIN      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[WType] = @andorwtypevalue'      
  END      
      
IF @andoryourref = 'OR'      
  BEGIN      
    IF SUBSTRING(@andoryourrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = '%' + @andoryourrefvalue       
      END      
      
    IF SUBSTRING(@andoryourrefvalue, LEN(@andoryourrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = @andoryourrefvalue + '%'      
      END      
      
    IF @SearchIncludes <> N''      
      BEGIN      
        SET @SearchIncludes = @SearchIncludes + N'      
          OR '      
      END      
      
    SET @SearchIncludes = @SearchIncludes + N'SM.[YourRef]							LIKE @andoryourrefvalue'      
  END      
      
--SELECT @SearchIncludes      
      
IF @SearchIncludes <> ''      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND (   ' + @SearchIncludes + N')'      
  END      
      
IF @andoraddress = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoraddressvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = '%' + @andoraddressvalue       
      END      
      
    IF SUBSTRING(@andoraddressvalue, LEN(@andoraddressvalue), 1) <> '%'      
      BEGIN      
        SET @andoraddressvalue = @andoraddressvalue + '%'      
      END      
      
    SET @andoraddressvalue = @andoraddressvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCAddress]             LIKE @andoraddressvalue'      
  END      
      
IF @andorcode = 'AND'      
  BEGIN      
    IF SUBSTRING(@andorcodevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andorcodevalue = '%' + @andorcodevalue       
      END      
      
    IF SUBSTRING(@andorcodevalue, LEN(@andorcodevalue), 1) <> '%'      
      BEGIN      
        SET @andorcodevalue = @andorcodevalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Code]                  LIKE @andorcodevalue'      
  END      
      
IF @andordept = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[Dept]              = @andordeptvalue'      
  END      
      
IF @andordescription = 'AND'      
  BEGIN      
    IF SUBSTRING(@andordescriptionvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = '%' + @andordescriptionvalue       
      END      
      
    IF SUBSTRING(@andordescriptionvalue, LEN(@andordescriptionvalue), 1) <> '%'      
      BEGIN      
        SET @andordescriptionvalue = @andordescriptionvalue + '%'      
      END      
      
    SET @andordescriptionvalue = @andordescriptionvalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCDescription]         LIKE @andordescriptionvalue'      
  END      
      
IF @andorfeecode = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[FECode]                = @andorfeecodevalue'      
  END      
      
IF @andorname = 'AND'      
  BEGIN      
    IF SUBSTRING(@andornamevalue, 1, 1) <> '%'      
      BEGIN      
        SET @andornamevalue = '%' + @andornamevalue       
      END      
      
IF SUBSTRING(@andornamevalue, LEN(@andornamevalue), 1) <> '%'      
      BEGIN      
        SET @andornamevalue = @andornamevalue + '%'      
      END      
      
    SET @andornamevalue = @andornamevalue COLLATE SQL_Latin1_General_Cp1251_CS_AS      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[NCName]                LIKE @andornamevalue'      
  END      
      
IF @andoroldref = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoroldrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = '%' + @andoroldrefvalue       
      END      
      
    IF SUBSTRING(@andoroldrefvalue, LEN(@andoroldrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoroldrefvalue = @andoroldrefvalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[OldRef]                LIKE @andoroldrefvalue'      
  END      
      
IF @andoruser1 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser1value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser1value = '%' + @andoruser1value       
      END      
      
    IF SUBSTRING(@andoruser1value, LEN(@andoruser1value), 1) <> '%'      
      BEGIN      
        SET @andoruser1value = @andoruser1value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User1]                 LIKE @andoruser1value'      
  END      
      
IF @andoruser2 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser2value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser2value = '%' + @andoruser2value       
      END      
      
    IF SUBSTRING(@andoruser2value, LEN(@andoruser2value), 1) <> '%'      
      BEGIN      
        SET @andoruser2value = @andoruser2value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User2]                 LIKE @andoruser2value'      
  END      
      
IF @andoruser3 = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoruser3value, 1, 1) <> '%'      
      BEGIN      
        SET @andoruser3value = '%' + @andoruser3value       
      END      
      
    IF SUBSTRING(@andoruser3value, LEN(@andoruser3value), 1) <> '%'      
      BEGIN      
        SET @andoruser3value = @andoruser3value + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[User3]      LIKE @andoruser3value'      
  END      
      
IF @andorwtype = 'AND'      
  BEGIN      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[WType]                 = @andorwtypevalue'      
  END      
      
IF @andoryourref = 'AND'      
  BEGIN      
    IF SUBSTRING(@andoryourrefvalue, 1, 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = '%' + @andoryourrefvalue       
      END      
      
    IF SUBSTRING(@andoryourrefvalue, LEN(@andoryourrefvalue), 1) <> '%'      
      BEGIN      
        SET @andoryourrefvalue = @andoryourrefvalue + '%'      
      END      
      
    SET @NCOMMAND = @NCOMMAND + N'      
     AND SM.[YourRef]               LIKE @andoryourrefvalue'      
  END      
      

SET @NCOMMAND = @NCOMMAND + N'      
ORDER BY ' + CASE @orderby      
                  WHEN N'description'      
                       THEN N'CASE WHEN SM.[Description] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Description] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Code'      
                       THEN N'CASE WHEN SM.[Code] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Code] ' + @order      
                  WHEN N'Name'      
                       THEN N'CASE WHEN SM.[Name] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Name] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Address'      
                       THEN N'CASE WHEN SM.[Address] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Address] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Email'      
                       THEN N'CASE WHEN SM.[Email] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[Email] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'PhoneNumber'      
                       THEN N'CASE WHEN SM.[PhoneNumber] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[PhoneNumber] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'user1'      
                      THEN N'CASE WHEN SM.[User1] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User1] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'user2'      
                       THEN N'CASE WHEN SM.[User2] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User2] ' + @order + N',      
         SM.[Code] ' + @order      
    WHEN N'user3'      
                       THEN N'CASE WHEN SM.[User3] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[User3] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'yourref'      
                       THEN N'CASE WHEN SM.[YourRef] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[YourRef] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'OldRef'      
                       THEN N'CASE WHEN SM.[OldRef] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[OldRef] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileNum'      
                       THEN N'CASE WHEN SM.[FileNum] = 0      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileNum] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'department'      
                       THEN N'CASE WHEN SM.[DeptDescription] = ''''      
                   THEN 1      
  ELSE 0 END,      
         SM.[DeptDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'Dept'      
                       THEN N'CASE WHEN SM.[DeptDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[DeptDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'worktype'      
                       THEN N'CASE WHEN SM.[WTypeDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[WTypeDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FeeCode'      
                       THEN N'CASE WHEN SM.[FECode] = ''''      
                   THEN 2      
              WHEN SM.[FECode] = ''ADM''      
                   THEN 1      
 ELSE 0 END,      
         SM.[FECode] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FeeEarner'      
                       THEN N'CASE WHEN SM.[HandlerName] = '''' AND SM.[FECode] = ''''      
                   THEN 3      
              WHEN SM.[HandlerName] = ''''      
                   THEN 2      
              WHEN SM.[HandlerName] = ''Admin''      
                   THEN 1      
              ELSE 0 END,      
         SM.[HandlerName] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileColour_Fld'      
                       THEN N'CASE WHEN SM.[FileColourDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileColourDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'FileColour'      
                       THEN N'CASE WHEN SM.[FileColourDescription] = ''''      
                   THEN 1      
              ELSE 0 END,      
         SM.[FileColourDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'started'      
                       THEN N'SM.[Started] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'LastAccessed'      
                       THEN N'CASE WHEN RML.[DateField] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         RML.[DateField] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'closedate'      
                       THEN N'CASE WHEN SM.[CloseDate] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[CloseDate] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'orgcloseddate'      
                       THEN N'CASE WHEN SM.[orgcloseddate] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[orgcloseddate] ' + @order + N',      
         SM.[Code] ' + @order      
                  WHEN N'casestatusdesc'      
                       THEN N'CASE WHEN SM.[MatterStatusDescription] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         SM.[MatterStatusDescription] ' + @order + N',      
         SM.[Code] ' + @order      
                  ELSE CASE WHEN @Which <> 2      
                                 THEN N'SM.[Code] ' + @order      
                            ELSE N'CASE WHEN RML.[DateField] IS NULL      
                   THEN 1      
              ELSE 0 END,      
         RML.[DateField] DESC,      
         SM.[Code] ' + @order END END      
      
SET @NCOMMAND = @NCOMMAND + N'    
 IF(@Mode <>''Dashboard'')  
 	BEGIN
  SELECT ROW_NUMBER() OVER(ORDER BY [Res].[id]) AS [RowNumber],    
		 [RES].[id],      
         [RES].[Time],      
         [RES].[Code],      
         [RES].[FileColour],      
         [RES].[FileColour_Fld],      
         [RES].[BackgroundColour],      
         [RES].[TextColour],      
         [RES].[Name],    
         [RES].[Description],      
         [RES].[Fe],      
         [RES].[FeeCode],      
         [RES].[FeeEarner],      
         [RES].[User1],      
         [RES].[User2],      
         [RES].[User3],      
         [RES].[Started],      
         [RES].[Dept],      
         [RES].[WorkType],      
         [RES].[Privileges],      
         [RES].[OldRef],      
         [RES].[Address],      
         [RES].[Email],      
         [RES].[Closed],      
         [RES].[OrgCloseDate],      
         [RES].[CloseDate],      
         [RES].[FileRGBColour],      
         [RES].[LastAccessed],      
         [RES].[PhoneNumber],      
         [RES].[FileNum],      
         [RES].[ClientCode],      
         [RES].[DepartmentCode],      
         [RES].[FeeEarnerTeam],      
         [RES].[TeamName],      
         [RES].[YourRef],      
         [RES].[CaseStatusCode],      
         [RES].[CaseStatusDesc] ,
		 [RES].[OutlayBal],
		 [RES].[ClientCurBal],
		 [RES].[ClientDepBal],
		 [RES].[Comment],
		 [RES].[Branch],
		 [RES].[OpenInvoiceNo],
		 [RES].[ContactName],
		 [RES].[MatterDesc] 
    FROM @Result [RES]
   WHERE [RES].[id] BETWEEN @StartRow AND @EndRow
ORDER BY [RES].[id] ASC
	SELECT  
		COUNT(1) AS [TotalRecord]  
	FROM  
		@Result [RES]  
	  
    SELECT
		USERPROMPT1 AS [UserPrompt1],
		USERPROMPT2 AS [UserPrompt2],
		USERPROMPT3 AS [UserPrompt3],
		YourRef     AS [YourRef]
    FROM
	    [Control]
	END	
	ELSE
		BEGIN
		SELECT   
		 [RES].[ClientCode],  
         [RES].[Code],
		 [RES].[Name],         
         [RES].[Description],        
         [RES].[FeeCode] AS [FECode],      
         [RES].[FeeEarner],      
         [RES].[DepartmentCode] AS [Dept]       
    FROM @Result [RES]
   WHERE [RES].[id] BETWEEN @StartRow AND @EndRow
ORDER BY [RES].[id] ASC
		END
		'

EXECUTE sp_executesql @NCOMMAND,      
                      N'@HowMany               INT,      
                        @BitWiseID             BIGINT,      
                        @Handler               VARCHAR(10),      
                        @WorkType              VARCHAR(5),      
                        @department            VARCHAR(5),      
                        @filecolour            VARCHAR(3),      
                        @feecode               VARCHAR(10),      
                        @searchtext            VARCHAR(MAX),      
                        @andoraddressvalue     VARCHAR(200),      
                        @andorcodevalue        VARCHAR(200),      
                        @andordeptvalue        VARCHAR(200),      
                        @andordescriptionvalue VARCHAR(200),      
                        @andorfeecodevalue     VARCHAR(200),      
                        @andornamevalue        VARCHAR(200),      
                        @andoroldrefvalue      VARCHAR(200),      
                        @andoruser1value       VARCHAR(200),      
                        @andoruser2value       VARCHAR(200),      
                        @andoruser3value       VARCHAR(200),      
                        @andorwtypevalue       VARCHAR(200),      
                        @andoryourrefvalue     VARCHAR(200),    
					    @StartRow			   INT,    
					    @EndRow                INT,
					    @ColumnNames           VARCHAR(50),
					    @FilterValues          VARCHAR(50),
						@DefaultDate		   VARCHAR(8),
						@DefaultDaybookDate	   VARCHAR(8),
						@Mode				   VARCHAR(10)
						',      
                      @Howmany,      
                      @BitWiseID,      
                      @handler,      
                      @worktype,      
                      @department,      
                      @filecolour,      
                      @feecode,      
                      @searchtext,      
                      @andoraddressvalue,      
                      @andorcodevalue,      
                      @andordeptvalue,      
                      @andordescriptionvalue,      
                      @andorfeecodevalue,      
                     @andornamevalue,      
                      @andoroldrefvalue,      
                      @andoruser1value,      
                      @andoruser2value,      
                      @andoruser3value,      
                      @andorwtypevalue,      
                      @andoryourrefvalue,    
					  @StartRow,    
					  @EndRow,
					  @ColumnNames,
					  @FilterValues,
					  @DefaultDate,
					  @DefaultDaybookDate,
					  @Mode	

SET NOCOUNT OFF

END

GO

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

CREATE PROCEDURE [dbo].[KAAS_PostSAMUpdateChangeAssociateDetails] 
	   (
			@Code			VARCHAR(20) = NULL,
			@Name			VARCHAR(20) = NULL,
			@Email			VARCHAR(90) = NULL,
			@BankType		CHAR(1)     = NULL,
			@BankName		VARCHAR(60) = NULL,
			@BankAddress	VARCHAR(150)= NULL,
			@BankSortCode	VARCHAR(20) = NULL,
			@BankAccNo		VARCHAR(20) = NULL,
			@IBAN			VARCHAR(50) = NULL,
			@BIC			VARCHAR(20) = NULL,
			@EFTAddress		VARCHAR(90) = NULL,
			@HandlerCode    VARCHAR(10) = NULL
	   ) 
AS 
/*******************************************************************************************************
* Stored Procedure Name : [dbo].[KAAS_PostSAMUpdateChangeAssociateDetails]		                       *
*																                                       *	
* Description: Update details of Change associates party based on Code                                 *	
*																                                       *					  
* Modification History:                                                                                *
* 2021-09-02   Vinodhkumar M      Created															   *
* 2022-03-08   Balamurugan.C      Modified - Handled TCL Statements and Formatting                     *   
*******************************************************************************************************/
BEGIN
  BEGIN TRY
	BEGIN TRANSACTION
	 DECLARE @CASEASSOCIATES TABLE
		(    [Email]		   VARCHAR(90),
			 [BankType]		   CHAR(1),
			 [BankName]		   VARCHAR(60),
			 [BankAddress]	   VARCHAR(150),
			 [BankSortCode]	   VARCHAR(20),
			 [BankAccNo]	   VARCHAR(20),
			 [IBAN]			   VARCHAR(50),
			 [BIC]			   VARCHAR(20),
			 [EFTEmailAddress] VARCHAR(90))
	  INSERT 
	    INTO @CASEASSOCIATES
      SELECT [Email],
			 [BankType],
			 [BankName],
			 [BankAddress],
			 [BankSortCode],
			 [BankAccNo],
			 [IBAN],
			 [BIC],
			 [EFTEmailAddress]
	    FROM [dbo].[CaseAssociatesNames]
	   WHERE [CODE]=@Code

      UPDATE [dbo].[CaseAssociatesNames]
		 SET [Code]			   =	@Code,
			 [Name]			   =	@Name,
			 [Email]		   =	@Email,
			 [BankType]		   =	@BankType,
			 [BankName]		   =	@BankName,
			 [BankAddress]     =	@BankAddress,
			 [BankSortCode]    =	@BankSortCode,
			 [BankAccNo]	   =	@BankAccNo,
			 [IBAN]			   =	@IBAN,
			 [BIC]			   =	@BIC,
			 [EFTEmailAddress] =	@EFTAddress
	   WHERE [CODE]=@Code

			--Insert the Changes into Logs
			IF(@Email != (SELECT Email FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed Email from ' + (SELECT Email FROM @CASEASSOCIATES) + ' to '+@Email, GETUTCDATE())
			 END
			IF(@BankName != (SELECT BankName FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed Bank Name from '+(SELECT BankName FROM @CASEASSOCIATES)+' to '+@BankName, GETUTCDATE())
			 END
			IF(@BankAddress != (SELECT BankAddress FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed Bank Address from '+(SELECT BankAddress FROM @CASEASSOCIATES)+' to '+@BankAddress, GETUTCDATE())
			 END
			IF(@BankSortCode != (SELECT BankSortCode FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed Bank Sort Code from '+  (SELECT BankSortCode FROM @CASEASSOCIATES) +' to '+@BankSortCode, GETUTCDATE())
			 END
			IF(@BankAccNo != (SELECT BankAccNo FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed Bank Account Number Code from '+(SELECT BankAccNo FROM @CASEASSOCIATES)+' to '+@BankAccNo, GETUTCDATE())
			 END
			IF(@IBAN != (SELECT IBAN FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed IBAN from '+(SELECT IBAN FROM @CASEASSOCIATES)+' to '+@IBAN, GETUTCDATE())
			 END
			IF(@BIC != (SELECT BIC FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed BIC from'+  (SELECT BIC FROM @CASEASSOCIATES) +' to '+@BIC, GETUTCDATE())
			 END
			IF(@EFTAddress != (SELECT EFTEmailAddress FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed EFT Email address from '+(SELECT EFTEmailAddress FROM @CASEASSOCIATES)+' to '+@EFTAddress, GETUTCDATE())
			 END
			IF(@BankType != (SELECT BankType FROM @CASEASSOCIATES))
			 BEGIN
				INSERT INTO dbo.EFTTableChangeLog (LOGON,TABLENAME,CODE,DESCRIPTION,DATE) 
				VALUES (@HandlerCode,'CaseAssociatesNames',@Code,'Changed Bank Type from '+(SELECT BankType FROM @CASEASSOCIATES)+' to '+@BankType, GETUTCDATE())
			 END
	
			COMMIT TRANSACTION
   END TRY
   BEGIN CATCH
   	   DECLARE @ErrorMsg      NVARCHAR(4000), 
   	   		   @ErrorSeverity INT,
   	   		   @ErrorState    INT; 
   	   
   	    SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
   	   		   @ErrorSeverity = ERROR_SEVERITY(), 
   	   		   @ErrorState    = ERROR_STATE()

   	 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
   	   	 IF @@TRANCOUNT > 0  
   	   		BEGIN
   	   			ROLLBACK TRANSACTION;
   	   		END 
   END CATCH
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_ProcessBankReconciliationTransaction' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_ProcessBankReconciliationTransaction] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_ProcessBankReconciliationTransaction]
	( 
		@BankAc	           VARCHAR(10)   = '',
		@ReconDate	       DATE          = NULL,
		@RecordId          INT           = 0,
		@Mode			   VARCHAR(20)   = '',
		@BankBal           DECIMAL(17,2) = 0
	)
AS
/*******************************************************************************************************
* Ticked Procees of Bank Reconciliation																   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_CreateBankReconciliationTransaction]   			               *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-01-27    Balamurugan C        Created                                                           *
* 2022-01-31    Balamurugan C        Modified - Formula changed for Difference field                   *
* 2022-02-02    Balamurugan C        Modified - Handled Lodgement,Cheque Balance using OsReqNo         *
* 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
*******************************************************************************************************/
BEGIN

BEGIN TRY
		BEGIN TRAN
/*UPDATE TICKED STAUS FOR Bank Rec Transaction*/

		DECLARE @ReconValue DECIMAL(17,2) = 0,
				@SumOfLodgementValue               DECIMAL(17,2) = 0,
			    @SumOfChequeValue                  DECIMAL(17,2) = 0,
			    @SumOfOutstandingLodgementValue    DECIMAL(17,2) = 0,
			    @SumOfOutstandingChequeValue       DECIMAL(17,2) = 0;

IF(@Mode = 'TICKED' OR @Mode = 'UNTICKED')
BEGIN
IF(@Mode = 'TICKED')
	BEGIN
					UPDATE [dbo].[BankRecTransactions]
					   SET [Ticked]   = 'R'
					 WHERE [BankAc]   = @BankAc
					   AND [RecordId] = @RecordId

					SELECT @ReconValue = [Value] 
					  FROM [dbo].[BankRecTransactions]
					 WHERE [BankAc]   = @BankAc
					   AND [RecordId] = @RecordId
	END

/*UPDATE Revert TICKED STAUS FOR Bank Rec Transaction*/

IF(@Mode = 'UNTICKED')
	BEGIN

		UPDATE [dbo].[BankRecTransactions]
		   SET [Ticked]   = ''
		 WHERE [BankAc]   = @BankAc
		   AND [RecordId] = @RecordId

		SELECT @ReconValue = [Value] 
		  FROM [dbo].[BankRecTransactions]
		 WHERE [BankAc]   = @BankAc
		   AND [RecordId] = @RecordId
	END
	/* Update Bank Ren History table for lodgement value */
					SELECT @SumOfOutstandingLodgementValue = SUM([BRT].[VALUE])
					  FROM [dbo].[BankRecTransactions] [BRT]
					  JOIN [BankRecHistory] [BRH]
						ON [BRH].[BankAc]  = [BRT].[BankAc]
					   AND [BRT].[RecNo]  = [BRH].[RecNo]
					   AND [BRH].[DateComplete] IS NULL
					 WHERE [BRT].[BankAc] = @BankAc
					   AND [BRT].[Type]   = 'R'
					   AND ISNULL([BRT].[Ticked],'') <> 'R'
	
					SELECT @SumOfOutstandingChequeValue = SUM([BRT].[VALUE])
					  FROM [dbo].[BankRecTransactions] [BRT]
					  JOIN [BankRecHistory] [BRH]
					    ON [BRH].[BankAc]  = [BRT].[BankAc]
					   AND [BRT].[RecNo]  = [BRH].[RecNo]
					   AND [BRH].[DateComplete] IS NULL
					 WHERE [BRT].[BankAc] = @BankAc
					   AND [BRT].[Type]   = 'P'
					   AND ISNULL([BRT].[Ticked],'') <> 'R'

					SELECT @SumOfLodgementValue = SUM([BRT].[VALUE])
					  FROM [dbo].[BankRecTransactions] [BRT]
					  JOIN [BankRecHistory] [BRH]
					    ON [BRH].[BankAc]  = [BRT].[BankAc]
					   AND [BRH].[DateComplete] IS NULL
					   AND [BRT].[RecNo]   = [BRH].[RecNo]
					 WHERE [BRT].[BankAc]  = @BankAc
					   AND [BRT].[Type]    = 'R'
					   AND [BRT].[OsRecNo] = 0
	
					SELECT @SumOfChequeValue = SUM([BRT].[VALUE])
					  FROM [dbo].[BankRecTransactions] [BRT]
					  JOIN [BankRecHistory] [BRH]
					    ON [BRH].[BankAc]  = [BRT].[BankAc]
					   AND [BRH].[DateComplete] IS NULL
					   AND [BRT].[RecNo]  = [BRH].[RecNo]
					 WHERE [BRT].[BankAc] = @BankAc
					   AND [BRT].[Type]   = 'P'
					   AND [BRT].[OsRecNo] = 0
	

					UPDATE [BRH]
					   SET [BRH].[OsLodgements] = ISNULL(@SumOfOutstandingLodgementValue,0),
					       [BRH].[OsCheques]    = ISNULL(@SumOfOutstandingChequeValue,0),
						   [BRH].[Lodgements] = ISNULL(@SumOfLodgementValue,0),
						   [BRH].[Cheques]    = ISNULL(@SumOfChequeValue,0)
					  FROM [dbo].[BankRecHistory] [BRH]
					 WHERE [BRH].[BankAc]    = @BankAc
					   AND [DateComplete] IS NULL 

					UPDATE [BRH]
					   SET [BRH].[Diff] = [BRH].[OpeningBalance] + [BRH].[Lodgements] - ISNULL([BRH].[OsLodgements],0) - [BRH].[Cheques] + ISNULL([BRH].[OsCheques],0) - ISNULL([BRH].[BankBal],0)
					  FROM [dbo].[BankRecHistory] [BRH]
					 WHERE [BRH].[BankAc]    = @BankAc
					   AND [DateComplete] IS NULL 	

END



IF(@Mode = 'BANKBAL')
	BEGIN
		UPDATE [BRH]
		   SET [BRH].[Diff]	   = [BRH].[OpeningBalance] + [BRH].[Lodgements] - ISNULL([BRH].[OsLodgements],0) - [BRH].[Cheques] + ISNULL([BRH].[OsCheques],0) - ISNULL(@BankBal,0),
			   [BRH].[BankBal] = ISNULL(@BankBal,0)
		  FROM [dbo].[BankRecHistory] [BRH]
		 WHERE [BRH].[BankAc]    = @BankAc
		   AND [DateComplete] IS NULL 	
	END

		SELECT [RecNo],
    		   RTRIM([BankAc])	 AS [BankAc],
    		   [RecDate],
    		   [DateComplete],
    		   [LastRec],
    		   RTRIM([Currency]) AS [Currency],
    		   [OpeningBalance],
    		   [Lodgements],
    		   [Cheques],
    		   [OsLodgements],
    		   [OsCheques],
    		   [BankBal],
    		   [ClosingBal],
    		   [Diff]
		  FROM [dbo].[BankRecHistory]
		 WHERE [BankAc] = @BankAc
		   AND [DateComplete] IS NULL 
    
IF(@Mode <>'BANKBAL')
	BEGIN
		SELECT RTRIM([BRT].[BankAc]) AS [BankAc],
    		   RTRIM([BRT].[Type])	 AS [Type],
    		   [BRT].[Date],
    		   RTRIM([BRT].[Ref])    AS [Ref],
    		   [BRT].[Batch],
    		   [BRT].[Pref],
    		   RTRIM([BRT].[Narr])	 AS [Narr],
    		   [BRT].[Value],
    		   [BRT].[OsRecNo],
    		   [BRT].[RecNo],
    		   RTRIM([BRT].[Ticked]) AS [Ticked],
    		   [RecordId],
    		   [BRT].[NomTransId]
		  FROM [dbo].[BankRecTransactions] [BRT]
		  JOIN [dbo].[BankRecHistory] [BRH]
			ON [BRH].[RecNo]  = [BRT].[RecNo]
		 WHERE [BRT].[BankAc] = @BankAc
	END


	COMMIT TRAN
END TRY

BEGIN CATCH
	DECLARE @ErrorMsg      NVARCHAR(4000), 
			@ErrorSeverity INT,
			@ErrorState    INT; 

	SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
		   @ErrorSeverity = ERROR_SEVERITY(), 
		   @ErrorState    = ERROR_STATE()

 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
		  IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
END CATCH

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_RebuildBalances' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_RebuildBalances] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_RebuildBalances] (
       @XML NVARCHAR(MAX) = '')
AS
/*******************************************************************
 * [KAAS_RebuildBalances]
 *
 * Rebuild all balances in SAM: Matter, nominal, supplier
 * This code is based on the original clarion code in find.app
 *
 * The following will rebuild all matters:
 * <Data>
 *     <matters target="*"/>
 * </Data>
 *
 * The following will rebuild only specific records:
 * <data>
 *     <matters>
 *         <matter code="ABC123/0001"/>
 *         <matter code="TEST01/0002"/>
 *     </matters>
 *     <clients target="*"/>
 *     <nominals>
 *         <nominal code="CLCONTROL"/>
 *     </nominals>
 *     <suppliers>
 *         <supplier code="EIR"/>
 *     </suppliers>
 * </data>
 *
 * Modification History:
 * 2022-02-17   John Ginnane   Created
 * 2022-02-18   John Ginnane   Fixed forward balance for suppliers
 * 2022-02-25   John Ginnane   Copied into new KAAS procedure
 * 2022-03-31   John Ginnane   Added optional parameter to specify
 *                             which items to rebuild
 * 2023-08-16   John Ginnane   Use distinct for codes to avoid duplication
 *
 *******************************************************************/
BEGIN
    SET NOCOUNT ON;

    IF [dbo].[ISSAM4]() = 1
    BEGIN
        RETURN
    END

    DECLARE @SQL NVARCHAR(MAX)
    
    SET @SQL = N'
DECLARE @YEAR      INT
DECLARE @PER       INT
DECLARE @IECONVERT DECIMAL(19, 6)

SELECT @YEAR      = [CON].[YEAR],
       @PER       = [CON].[CURPER],
       @IECONVERT = [CON].[IECONVERT]
  FROM [dbo].[control] AS [CON]


DECLARE @MATTERS   TABLE ([Code] VARCHAR(20) PRIMARY KEY)
DECLARE @CLIENTS   TABLE ([Code] VARCHAR(20) PRIMARY KEY)
DECLARE @NOMINALS  TABLE ([Code] VARCHAR(10) PRIMARY KEY)
DECLARE @SUPPLIERS TABLE ([Code] VARCHAR(10) PRIMARY KEY)
    
    /* Parse the input and put them records into their own tables */
    /* If there was no input then rebuild all balances */

IF ISNULL(@XML, '''') = ''''
BEGIN
    INSERT INTO @MATTERS ([Code])
    SELECT [MAT].[Code] FROM [dbo].[matters] AS [MAT]

    INSERT INTO @CLIENTS ([Code])
    SELECT [CNT].[Code] FROM [dbo].[Contacts] AS [CNT]

    INSERT INTO @NOMINALS ([Code])
    SELECT [NOM].[CODE] FROM [dbo].[Nominal] AS [NOM]

    INSERT INTO @SUPPLIERS ([Code])
    SELECT [SUP].[CODE] FROM [dbo].[Suppliers] AS [SUP]
END
ELSE
BEGIN    
    DECLARE @iSL INT

    BEGIN TRY
    EXEC sp_xml_preparedocument @iSL OUTPUT, @XML
    END TRY
    BEGIN CATCH
    EXEC sp_xml_preparedocument @iSL OUTPUT, N''<data />''
    END CATCH

    DECLARE @TABLES TABLE (
            [name] VARCHAR(100),
            [target] VARCHAR(1))
    INSERT INTO @TABLES (
            [name],
            [target])
    SELECT [XML].[name],
           ISNULL([XML].[target], '''')
      FROM OPENXML(@iSL, N''data/*'')
                WITH([name]   VARCHAR(20) ''@mp:localname'',
                    [target] VARCHAR(10) ''@target'') AS [XML]

    IF EXISTS (SELECT TOP 1 1
                     FROM @TABLES
                    WHERE [name] = ''matters''
                      AND [target] = ''*'')
    BEGIN
        INSERT INTO @MATTERS ([Code])
        SELECT DISTINCT [MAT].[Code] FROM [dbo].[matters] AS [MAT]
        
        INSERT INTO @CLIENTS ([Code])
        SELECT DISTINCT [CNT].[Code] FROM [dbo].[Contacts] AS [CNT]
    END
    ELSE
    BEGIN
        INSERT INTO @MATTERS ([Code])
        SELECT DISTINCT [XML].[code]
          FROM OPENXML(@iSL, N''data/matters/*'')
                  WITH([code] VARCHAR(20) ''@code'') AS [XML]

        INSERT INTO @CLIENTS ([Code])
        SELECT DISTINCT [CNT].[Code]
          FROM [dbo].[Contacts] AS [CNT]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [CNT].[Code] = [MAT].[ClientCode]
               INNER JOIN @MATTERS AS [TMP]
                       ON [TMP].[Code] = [MAT].[Code]
    END
    
    IF EXISTS (SELECT TOP 1 1
                     FROM @TABLES
                    WHERE [name] = ''contacts''
                      AND [target] = ''*'')
    BEGIN
        INSERT INTO @CLIENTS ([Code])
        SELECT DISTINCT [CNT].[Code]
          FROM [dbo].[Contacts] AS [CNT]
               LEFT OUTER JOIN @CLIENTS AS [TMP]
                            ON [TMP].[Code] = [CNT].[Code]
         WHERE [TMP].[Code] IS NULL
    END
    ELSE
    BEGIN
        INSERT INTO @CLIENTS ([Code])
        SELECT DISTINCT [XML].[code]
          FROM OPENXML(@iSL, N''data/clients/*'')
                  WITH([code] VARCHAR(20) ''@code'') AS [XML]
    END
    
    IF EXISTS (SELECT TOP 1 1
                     FROM @TABLES
                    WHERE [name] = ''nominals''
                      AND [target] = ''*'')
    BEGIN
        INSERT INTO @NOMINALS ([Code])
        SELECT DISTINCT [NOM].[CODE] FROM [dbo].[Nominal] AS [NOM]
    END
    ELSE
    BEGIN
        INSERT INTO @NOMINALS ([Code])
        SELECT DISTINCT [XML].[code]
          FROM OPENXML(@iSL, N''data/nominals/*'')
                  WITH([code] VARCHAR(20) ''@code'') AS [XML]
    END
    
    IF EXISTS (SELECT TOP 1 1
                     FROM @TABLES
                    WHERE [name] = ''suppliers''
                      AND [target] = ''*'')
    BEGIN
        INSERT INTO @SUPPLIERS ([Code])
        SELECT DISTINCT [SUP].[CODE] FROM [dbo].[Suppliers] AS [SUP]
    END
    ELSE
    BEGIN
        INSERT INTO @SUPPLIERS ([Code])
        SELECT DISTINCT [XML].[code]
          FROM OPENXML(@iSL, N''data/suppliers/*'')
                  WITH([code] VARCHAR(20) ''@code'') AS [XML]
    END
END

/* Matter Balances */
;WITH [MTL] ([Matter],
             [DebtBal],
             [DebtBalFwd],
             [OutlayBal],
             [OutlayBalFwd],
             [ClientBal],
             [ClientBalFwd],
             [ClientCurBal],
             [ClientCurBalFwd],
             [ClientDepBal],
             [ClientDepBalFwd]) AS (
SELECT [MTL2].[MATTER],
       SUM([MTL2].[VALUED]),
       SUM(CASE WHEN [MTL2].[YEAR] = @YEAR
                 AND [MTL2].[PER] = @PER + 1
                     THEN [MTL2].[VALUED]
                ELSE 0 END),
       SUM([MTL2].[VALUEO]),
       SUM(CASE WHEN [MTL2].[YEAR] = @YEAR
                 AND [MTL2].[PER] = @PER + 1
                     THEN [MTL2].[VALUEo]
                ELSE 0 END),
       SUM([MTL2].[VALUEC]),
       SUM(CASE WHEN [MTL2].[YEAR] = @YEAR
                 AND [MTL2].[PER] = @PER + 1
                     THEN [MTL2].[VALUEC]
                ELSE 0 END),
       SUM([MTL2].[VALUECC]),
       SUM(CASE WHEN [MTL2].[YEAR] = @YEAR
                 AND [MTL2].[PER] = @PER + 1
                     THEN [MTL2].[VALUECC]
                ELSE 0 END),
       SUM([MTL2].[VALUECD]),
       SUM(CASE WHEN [MTL2].[YEAR] = @YEAR
                 AND [MTL2].[PER] = @PER + 1
                     THEN [MTL2].[VALUECD]
                ELSE 0 END)
  FROM [dbo].[MatterLedger] AS [MTL2]
       INNER JOIN @MATTERS AS [MAT]
               ON [MAT].[Code] = [MTL2].[MATTER]
       GROUP BY [MTL2].[MATTER]),
      [MTLCUR] ([Matter],
                [CurDebtBal],
                [CurOutlayBal],
                [CurClientBal],
                [CurClientCBal],
                [CurClientDBal],
                [CurDebtBalFwd],
                [CurOutlayBalFwd],
                [CurClientBalFwd],
                [CurClientCBalFwd],
                [CurClientDBalFwd]) AS (
SELECT [MTL].[Matter],
       [MTL].[DebtBal]         * @IECONVERT,
       [MTL].[OutlayBal]       * @IECONVERT,
       [MTL].[ClientBal]       * @IECONVERT,
       [MTL].[ClientCurBal]    * @IECONVERT,
       [MTL].[ClientDepBal]    * @IECONVERT,
       [MTL].[DebtBalFwd]      * @IECONVERT,
       [MTL].[OutlayBalFwd]    * @IECONVERT,
       [MTL].[ClientBalFwd]    * @IECONVERT,
       [MTL].[ClientCurBalFwd] * @IECONVERT,
       [MTL].[ClientDepBalFwd] * @IECONVERT
  FROM [MTL]),
      [TIE] ([Matter],
             [TimeBal],
             [ChargeBal]) AS (
SELECT [TIE2].[Matter],
       SUM(CASE WHEN [TIE2].[Charge] <> 0
                     THEN [TIE2].[TIME] * (1 - ([TIE2].[BilledAmount] / [TIE2].[Charge]))
                WHEN [TIE2].[InvoiceNo] <> 0
                     THEN 0
                ELSE [TIE2].[TIME] END),
       SUM([TIE2].[Charge] - ISNULL([TIE2].[BilledAmount], 0))
  FROM [dbo].[TimeEntry] AS [TIE2]
       INNER JOIN @MATTERS AS [MAT]
               ON [MAT].[Code] = [TIE2].[Matter]
 WHERE [TIE2].[Rec_Irr] <> ''N''
   AND [TIE2].[TimeOrCharge] <> ''B''
   AND [TIE2].[IncludeInBill] <> 2
       GROUP BY [TIE2].[Matter])
UPDATE [MAT]
   SET [MAT].[DebtBal]          = ISNULL([MTL].[DebtBal],             0),
       [MAT].[DebtBalFwd]       = ISNULL([MTL].[DebtBalFwd],          0),
       [MAT].[ClientBal]        = ISNULL([MTL].[ClientBal],           0),
       [MAT].[ClientBalFwd]     = ISNULL([MTL].[ClientBalFwd],        0),
       [MAT].[OutlayBal]        = ISNULL([MTL].[OutlayBal],           0),
       [MAT].[OutlayBalFwd]     = ISNULL([MTL].[OutlayBalFwd],        0),
       [MAT].[ClientCurBal]     = ISNULL([MTL].[ClientCurBal],        0),
       [MAT].[ClientCurBalFwd]  = ISNULL([MTL].[ClientCurBalFwd],     0),
       [MAT].[ClientDepBal]     = ISNULL([MTL].[ClientDepBal],        0),
       [MAT].[ClientDepBalFwd]  = ISNULL([MTL].[ClientDepBalFwd],     0),
       [MAT].[TimeBal]          = ISNULL([TIE].[TimeBal],             0),
       [MAT].[ChargeBal]        = ISNULL([TIE].[ChargeBal],           0),
       [MAT].[CurDebtBal]       = ISNULL([MTLCUR].[CurDebtBal],       0),
       [MAT].[CurOutlayBal]     = ISNULL([MTLCUR].[CurOutlayBal],     0),
       [MAT].[CurClientBal]     = ISNULL([MTLCUR].[CurClientBal],     0),
       [MAT].[CurClientCBal]    = ISNULL([MTLCUR].[CurClientCBal],    0),
       [MAT].[CurClientDBal]    = ISNULL([MTLCUR].[CurClientDBal],    0),
       [MAT].[CurDebtBalFwd]    = ISNULL([MTLCUR].[CurDebtBalFwd],    0),
       [MAT].[CurOutlayBalFwd]  = ISNULL([MTLCUR].[CurOutlayBalFwd],  0),
       [MAT].[CurClientBalFwd]  = ISNULL([MTLCUR].[CurClientBalFwd],  0),
       [MAT].[CurClientCBalFwd] = ISNULL([MTLCUR].[CurClientCBalFwd], 0),
       [MAT].[CurClientDBalFwd] = ISNULL([MTLCUR].[CurClientDBalFwd], 0)
  FROM [dbo].[matters] AS [MAT]
       INNER JOIN @MATTERS AS [MAT2]
               ON [MAT].[Code] = [MAT2].[Code]
       LEFT OUTER JOIN [MTL]
                    ON [MAT].[Code] = [MTL].[Matter]
       LEFT OUTER JOIN [MTLCUR]
                    ON [MAT].[Code] = [MTLCUR].[Matter]
       LEFT OUTER JOIN [TIE]
                    ON [MAT].[Code] = [TIE].[Matter]

/* Client Balances */
;WITH [MAT] ([ClientCode],
             [DebtBal],
             [OutlayBal],
             [ClientCurBal],
             [ClientDepBal],
             [CurDebtBal],
             [CurOutlayBal],
             [CurClientCBal],
             [CurClientDBal]) AS (
SELECT [MAT].[ClientCode],
       SUM([MAT].[DebtBal]),
       SUM([MAT].[OutlayBal]),
       SUM([MAT].[ClientCurBal]),
       SUM([MAT].[ClientDepBal]),
       SUM([MAT].[CurDebtBal]),
       SUM([MAT].[CurOutlayBal]),
       SUM([MAT].[CurClientCBal]),
       SUM([MAT].[CurClientDBal])
  FROM [dbo].[matters] AS [MAT]
       INNER JOIN @MATTERS AS [MAT2]
               ON [MAT].[Code] = [MAT2].[Code]
       GROUP BY [MAT].[ClientCode])
UPDATE [CNT]
   SET [CNT].[BillBal]       = ISNULL([MAT].[DebtBal], 0),
       [CNT].[OutlayBal]     = ISNULL([MAT].[OutlayBal], 0),
       [CNT].[ClientCur]     = ISNULL([MAT].[ClientCurBal], 0),
       [CNT].[ClientDep]     = ISNULL([MAT].[ClientDepBal], 0),
       [CNT].[CurBillBal]    = ISNULL([MAT].[CurDebtBal], 0),
       [CNT].[CurOutlayBal]  = ISNULL([MAT].[CurOutlayBal], 0),
       [CNT].[CurClientCBal] = ISNULL([MAT].[CurClientCBal], 0),
       [CNT].[CurClientDBal] = ISNULL([MAT].[CurClientDBal], 0)
  FROM [dbo].[Contacts] AS [CNT]
       INNER JOIN @CLIENTS AS [CNT2]
               ON [CNT].[Code] = [CNT2].[Code]
       LEFT OUTER JOIN [MAT] 
                    ON [CNT].[Code] = [MAT].[ClientCode]

/* Nominal Balances */
;WITH [NML] ([Code],
             [Balance],
             [CurrencyBal],
             [BalanceFwd],
             [CurrencyBalFwd],
             [Month1],
             [Month2],
             [Month3],
             [Month4],
             [Month5],
             [Month6],
             [Month7],
             [Month8],
             [Month9],
             [Month10],
             [Month11],
             [Month12]) AS (
SELECT [NML2].[CODE],
       SUM([NML2].[VALUE]),
       SUM([NML2].[VALUE]) * @IECONVERT,
       SUM(CASE WHEN [NML2].[PER] = @PER + 1 THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = @PER + 1 THEN [NML2].[VALUE] ELSE 0 END) * @IECONVERT,
       SUM(CASE WHEN [NML2].[PER] = 1  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 2  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 3  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 4  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 5  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 6  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 7  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 8  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 9  THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 10 THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 11 THEN [NML2].[VALUE] ELSE 0 END),
       SUM(CASE WHEN [NML2].[PER] = 12 THEN [NML2].[VALUE] ELSE 0 END)
  FROM [dbo].[NominalLedger] AS [NML2]
       INNER JOIN @NOMINALS AS [NOM]
               ON [NML2].[CODE] = [NOM].[Code]
 WHERE [NML2].[YEAR] = @YEAR
       GROUP BY [NML2].[CODE])
UPDATE [NOM]
   SET [NOM].[BALANCE]        = ISNULL([NML].[Balance], 0),
       [NOM].[CURRENCYBAL]    = ISNULL([NML].[CurrencyBal], 0),
       [NOM].[BALANCEFWD]     = ISNULL([NML].[BalanceFwd], 0),
       [NOM].[CURRENCYBALFWD] = ISNULL([NML].[CurrencyBalFwd], 0),
       [NOM].[MONTH1]         = ISNULL([NML].[Month1], 0),
       [NOM].[MONTH2]         = ISNULL([NML].[Month2], 0),
       [NOM].[MONTH3]         = ISNULL([NML].[Month3], 0),
       [NOM].[MONTH4]         = ISNULL([NML].[Month4], 0),
       [NOM].[MONTH5]         = ISNULL([NML].[Month5], 0),
       [NOM].[MONTH6]         = ISNULL([NML].[Month6], 0),
       [NOM].[MONTH7]         = ISNULL([NML].[Month7], 0),
       [NOM].[MONTH8]         = ISNULL([NML].[Month8], 0),
       [NOM].[MONTH9]         = ISNULL([NML].[Month9], 0),
       [NOM].[MONTH10]        = ISNULL([NML].[Month10], 0),
       [NOM].[MONTH11]        = ISNULL([NML].[Month11], 0),
       [NOM].[MONTH12]        = ISNULL([NML].[Month12], 0)
  FROM [dbo].[Nominal] AS [NOM]
       INNER JOIN @NOMINALS AS [NOM2]
               ON [NOM2].[CODE] = [NOM].[Code]
       LEFT OUTER JOIN [NML]
                    ON [NML].[Code] = [NOM].[CODE]

;WITH [SPL] ([Code],
             [Balance],
             [BalanceFwd]) AS (
SELECT [SPL2].[SUPP],
       SUM([SPL2].[OSVALUE]),
       SUM(CASE WHEN [SPL2].[YEAR] = @YEAR
                 AND [SPL2].[PER] = @PER + 1
                     THEN [SPL2].[OSVALUE]
                ELSE 0 END)
  FROM [dbo].[SupplierLedger] AS [SPL2]
       INNER JOIN @SUPPLIERS AS [SUP]
               ON [SUP].[Code] = [SPL2].[SUPP]
       GROUP BY [SPL2].[SUPP]),
      [BAH] ([Code],
             [TPBal]) AS (
SELECT [BAH2].[SUPP],
       SUM([BAH2].[VALUE])
  FROM [dbo].[BatchH] AS [BAH2]
 WHERE [BAH2].[POSTED] = ''Y''
   AND [BAH2].[THIRDPARTY] = ''Y''
   AND [BAH2].[YEAR] = @YEAR
       GROUP BY [BAH2].[SUPP])
UPDATE [SUP]
   SET [SUP].[BALANCE]    = ISNULL([SPL].[Balance], 0),
       [SUP].[BALANCEFWD] = ISNULL([SPL].[BalanceFwd], 0),
       [SUP].[TPBAL]      = ISNULL([BAH].[TPBal], 0)
  FROM [dbo].[Suppliers] AS [SUP]
       INNER JOIN @SUPPLIERS AS [SUP2]
               ON [SUP].[Code] = [SUP2].[CODE]
       LEFT OUTER JOIN [SPL]
                    ON [SUP].[CODE] = [SPL].[Code]
       LEFT OUTER JOIN [BAH]
                    ON [SUP].[CODE] = [BAH].[Code]'

EXEC sp_executesql @SQL, N'@XML NVARCHAR(MAX)', @XML = @XML

END
GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_RemoveBlockers' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_RemoveBlockers] 
  END 
GO
CREATE PROCEDURE
       [dbo].[KAAS_RemoveBlockers]
AS
/******************************************************************************
 *
 * [dbo].[KAAS_RemoveBlockers]
 * Kills transactions that have been asleep for over 10 minutes, and processes
 * that have been blocking other processes for over 10 minutes.
 *
 * Copied from			: [dbo].[ky_NETSPRemoveBlockers]
* Modification History	:                               
* 2022-02-04	Vignesh.M		Created
 ******************************************************************************/
BEGIN

DECLARE @blocker INT
DECLARE @COMMAND VARCHAR(100)

SET @blocker = 0

SELECT TOP 1 @blocker = SPS.[spid]
  FROM [sys].[sysprocesses] SPS
 WHERE SPS.[open_tran] = 1
   and (   SPS.[status] = 'sleeping'
        or SPS.[cmd] = 'AWAITING COMMAND')
   and DATEDIFF(MI, last_batch, GetDate()) > 10
WHILE ISNULL(@blocker, 0) > 0
BEGIN

  SET @COMMAND = 'KILL ' + CONVERT(VARCHAR(20), @blocker)

  EXEC (@COMMAND)

  SET @blocker = 0

  SELECT TOP 1 @blocker = SPS.[spid]
    FROM [sys].[sysprocesses] SPS
   WHERE SPS.[open_tran] = 1
     and (   SPS.[status] = 'sleeping'
          or SPS.[cmd] = 'AWAITING COMMAND')
     and DATEDIFF(MI, last_batch, GetDate()) > 10
END

SELECT TOP 1 @blocker = SPS.[blocked]
  FROM [sys].[sysprocesses] SPS
 WHERE SPS.[blocked] > 0
   AND SPS.[waittime] > 600000
WHILE ISNULL(@blocker, 0) > 0
BEGIN

  SET @COMMAND = 'KILL ' + CONVERT(VARCHAR(20), @blocker)

  EXEC (@COMMAND)

  SET @blocker = 0

  SELECT TOP 1 @blocker = SPS.[blocked]
    FROM [sys].[sysprocesses] SPS
   WHERE SPS.[blocked] > 0
     AND SPS.[waittime] > 60000
END

END
GO

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

CREATE PROCEDURE
       [dbo].[KAAS_ReopenMatterClosable]
      (@MATTER VARCHAR(20))
AS
/**************************************************************************************
* Process to reopen closed matter records from archive enquiry                      *
*																					                                          *
* Stored Procedure Name : [dbo].[KAAS_ReopenMatterClosable] 
* Copied From : [dbo].[ky_NETPMatterClosable]
*                                                                                    *
* Modification History:                                                              *
* 2022-05-31     Ghayathri.S.V        Created  
 **************************************************************************************/
BEGIN

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

DECLARE @HasUnallocatedReceipts BIT
DECLARE @CheckUnallocatedReceipts BIT

DECLARE @HasDraftBills BIT
DECLARE @CheckDraftBillsClosingMatter BIT

DECLARE @IsSAM4 bit

SELECT @CheckDraftBillsClosingMatter = CASE WHEN [SET].[KeyName] = 'CheckDraftBillsClosingMatter'
                                             AND [SET].[KeyValue] = 'True'
                                                 THEN 1
                                            ELSE ISNULL(@CheckDraftBillsClosingMatter, 0) END,
       @CheckUnallocatedReceipts     = CASE WHEN [SET].[KeyName] = 'CheckUnallocatedReceipts'
                                             AND [SET].[KeyValue] = 'True'
                                                 THEN 1
                                            ELSE ISNULL(@CheckUnallocatedReceipts, 0) END
  FROM [dbo].[Settings] AS [SET]
 WHERE [SET].[KeyName] IN ('CheckDraftBillsClosingMatter', 'CheckUnallocatedReceipts')

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

-- Please see also: ky_NETCaseSummaryPageLoad. If you change any of these calculations,
--                                             ensure the ones in there are changed as well.
--                  ky_NETTLFetchTimeEntry. If you change any of these calculations,
--                                          ensure the ones in there are changed as well.
DECLARE @TimeBal      INT
DECLARE @ChargeBal    DECIMAL(19, 2)
DECLARE @TotalCharge  Decimal(19, 2)
DECLARE @TotalTime    INT
DECLARE @TimeEntryTotalCharge         DECIMAL(19, 2)
DECLARE @TimeEntryTotalTime           INT

SELECT @TimeEntryTotalCharge = ISNULL(SUM(ISNULL(TIE.[Charge], 0)), 0),
       @TimeEntryTotalTime = ISNULL(SUM(ISNULL(TIE.[TIME], 0)), 0),
       @TotalCharge = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                      THEN 0
                                 ELSE ISNULL(TIE.[Charge], 0) END), 0),
       @ChargeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                         THEN 0
                                    WHEN [TIE].[IncludeInBill] = 2
                                         THEN 0
                                    WHEN @IsSAM4 = 1
                                     AND ISNULL(TIE.[InvoiceNo], 0) <> 0
                                         THEN 0
                                    WHEN @IsSAM4 = 1
                                         THEN ISNULL(TIE.[Charge], 0)
                                    ELSE ISNULL(TIE.[Charge], 0) - ISNULL(TIE.[BilledAmount], 0) END), 0),
       @TimeBal = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                       THEN 0
                                  WHEN [TIE].[IncludeInBill] = 2
                                       THEN 0
                                  WHEN @IsSAM4 = 1
                                   AND ISNULL(TIE.[InvoiceNo], 0) <> 0
                                       THEN 0
                                  WHEN @IsSAM4 = 0
                                       THEN CASE WHEN TIE.[Charge] = 0
                                                      THEN 0
                                                 ELSE CONVERT(INT,
                                                              FLOOR(CONVERT(DECIMAL(18, 2), TIE.[TIME])
                                                                    * (  (TIE.[Charge] - TIE.[BilledAmount])
                                                                       /
                                                                       TIE.[Charge]))) END
                                  ELSE ISNULL(TIE.[Time], 0) END), 0),
       @TotalTime = ISNULL(SUM(CASE WHEN ISNULL(TIE.[Rec_Irr], '') = 'N'
                                         THEN 0
                                    ELSE ISNULL(TIE.[Time], 0) END), 0)
  FROM [dbo].[TimeEntry] TIE
 WHERE TIE.[Matter] = @MATTER
   AND (   (TIE.[TimeOrCharge] = 'T')
        OR (TIE.[TimeOrCharge] = 'C'))  --**Changed fetch condition JIRA 1081 - arun

DECLARE @DebtBal        DECIMAL(19, 2)
DECLARE @OutlayBal      DECIMAL(19, 2)
DECLARE @DebtBalDate    DATETIME
DECLARE @OutlayBalDate  DATETIME
DECLARE @ClientCurrent  DECIMAL(19, 2)
DECLARE @ClientDeposit  DECIMAL(19, 2)

DECLARE @NCOMMAND NVARCHAR(MAX)
-- To ensure SAM3 will retrieve these from [dbo].[matters]
SET @DebtBal = 0 
SET @OutlayBal = 0
SET @ClientCurrent = 0
SET @ClientDeposit = 0
IF @IsSAM4 = 1
  BEGIN
    SET @NCOMMAND = N'
SELECT @DebtBal = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[DebtorsValue], 0)), 0)),
       @DebtBalDate = MAX(CASE WHEN ISNULL(TRN.[DebtorsValue], 0) = 0 THEN NULL ELSE TRN.[TransDate] END),
       @OutlayBal = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[OutlayValue], 0)), 0)),
       @OutlayBalDate = MAX(CASE WHEN ISNULL(TRN.[OutlayValue], 0) = 0 THEN NULL ELSE TRN.[TransDate] END),
       @ClientCurrent = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[ClientCurrent], 0)), 0)),
       @ClientDeposit = CONVERT(DECIMAL(19, 2), ISNULL(SUM(ISNULL(TRN.[ClientDeposit], 0)), 0))
  FROM [dbo].[Transactions] TRN 
 WHERE TRN.[MatterCode] = @MATTER
   AND TRN.[Posted] = ''Y''
   AND TRN.[RecType] <> ''V''
   AND TRN.[CorrectionInd] = ''L'''
EXECUTE sp_executesql @NCOMMAND, 
                      N'@MATTER VARCHAR(20),
                        @DebtBal DECIMAL(19, 2) OUTPUT,
                        @DebtBalDate DATETIME OUTPUT,
                        @OutlayBal DECIMAL(19, 2) OUTPUT,
                        @OutlayBalDate DATETIME OUTPUT,
                        @ClientCurrent DECIMAL(19, 2) OUTPUT,
                        @ClientDeposit DECIMAL(19, 2) OUTPUT',
                      @MATTER        = @MATTER,
                      @DebtBal       = @DebtBal OUTPUT,
                      @DebtBalDate   = @DebtBalDate OUTPUT,
                      @OutlayBal     = @OutlayBal OUTPUT,
                      @OutlayBalDate = @OutlayBalDate OUTPUT,
                      @ClientCurrent = @ClientCurrent OUTPUT,
                      @ClientDeposit = @ClientDeposit OUTPUT
  END

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

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

DECLARE @YEAR INT

IF @IsSAM4 = 0
  BEGIN
    SET @NCOMMAND = N'SELECT @YEAR = ISNULL(CTL.[YEAR], DATEPART(YEAR, GetDate()))
  FROM [dbo].[Control] CTL

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

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

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

  END

EXEC sp_executesql @NCOMMAND, N'@YEAR INT OUTPUT', @YEAR OUTPUT

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

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

  END

EXEC sp_executesql @NCOMMAND, N'@MATTER VARCHAR(20), @YEAR INT, @HasOutstandingRec INT OUTPUT', @MATTER, @YEAR, @HasOutstandingRec OUTPUT

IF @CheckUnallocatedReceipts = 1
  BEGIN
    IF @IsSAM4 = 0
      BEGIN
        SET @NCOMMAND = N'SELECT @HasUnallocatedReceipts = 
       CASE WHEN COUNT(1) = 0
                 THEN CONVERT(BIT, 0)
            ELSE CONVERT(BIT, 1) END
  FROM [dbo].[DebtorsLedger] [DL]
 WHERE [DL].[MATTER] = @MATTER
   AND [DL].[TYPE] = ''R''
   AND [DL].[OSVALUE] <> 0'
      END
    ELSE
      BEGIN
        SET @NCOMMAND = N'SELECT @HasUnallocatedReceipts =
       CASE WHEN COUNT(1) = 0
                 THEN CONVERT(BIT, 0)
            ELSE CONVERT(BIT, 1) END
  FROM [dbo].[DebtorsLedger] [DL]
 WHERE [DL].[MatterCode] = @MATTER
   AND [DL].[RecType] = ''R''
   AND [DL].[OSValue] <> 0'
      END

    EXEC sp_executesql @NCOMMAND, N'@MATTER VARCHAR(20), @HasUnallocatedReceipts INT OUTPUT', @MATTER, @HasUnallocatedReceipts OUTPUT
  END
ELSE
  BEGIN
    SET @HasUnallocatedReceipts = 0
  END

IF @CheckDraftBillsClosingMatter = 1
BEGIN
    IF @IsSAM4 = 0
    BEGIN
        SET @NCOMMAND = N'SELECT @HasDraftBills = CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END
                            FROM [dbo].[BillHeader] AS [BH]
                           WHERE [BH].[MATTER] = @MATTER
                             AND [BH].[BILLNO] = 0'
    END
    ELSE
    BEGIN
        SET @NCOMMAND = N'SELECT @HasDraftBills = CASE WHEN COUNT(1) > 0 THEN 1 ELSE 0 END
                            FROM [dbo].[Billhead] AS [BH]
                           WHERE [BH].[MatterCode] = @MATTER
                             AND [BH].[InvoiceNo] = 0'
    END

    EXEC sp_executesql @NCOMMAND, N'@MATTER VARCHAR(20), @HasDraftBills BIT OUTPUT', @MATTER, @HasDraftBills OUTPUT
END
ELSE
BEGIN
    SET @HasDraftBills = 0
END

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

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

SELECT @AlreadyClosed                       AS [AlreadyClosed],
       @HasOutstandingBal                   AS [HasOutstandingBal],
       @HasOutstandingTimeBal               AS [HasOutstandingTimeBal],
       @HasOutstandingChargeBal             AS [HasOutstandingChargeBal],
       @HasOutstandingRec                   AS [HasOutstandingRec],
       @HasOutstandingDiary                 AS [HasOutstandingDiary],
       @HasOutstandingUndertakings          AS [HasOutstandingUndertakings],
       @HasUnallocatedReceipts              AS [HasUnallocatedReceipts],
       @HasDraftBills                       AS [HasDraftBills]

END

GO



IF OBJECT_ID(N'KAAS_SAMApproveReturnChequeRequisition',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_SAMApproveReturnChequeRequisition]
GO
CREATE PROCEDURE [dbo].[KAAS_SAMApproveReturnChequeRequisition]
	   (
		  @ReqNo  INT,
		  @Status CHAR 
	   )				
AS
/*******************************************************************************************************
* To return cheque requisitions															               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SAMReturnChequeRequisition]        					           *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-20   Revathy D           Created                                                             *
 *******************************************************************************************************/
 BEGIN 
  SET NOCOUNT ON

   UPDATE [dbo].[ChequeRequisitionHeader]
      SET [STATUS] =  @Status
    WHERE [REQNO]  =  @ReqNo  

  SET NOCOUNT OFF

 END

 GO


IF OBJECT_ID(N'KAAS_SAMApproveReturnDraftBills',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_SAMApproveReturnDraftBills]
GO
CREATE PROCEDURE [dbo].[KAAS_SAMApproveReturnDraftBills]
	   (
		  @BillNo    INT,
		  @BatchNo   INT = 0,
		  @Matter    VARCHAR(20),
		  @DraftNo   INT,
		  @Released  CHAR,
		  @IsApprove CHAR 
	   )				
AS
/*******************************************************************************************************
* To approve/return draft bills															               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SAMApproveReturnDraftBills]        					           *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-21   Revathy D           Created                                                             *
* 2022-03-08   Balamurugan.C       Modified - Handled TCL Statements and Formatting                    *
 *******************************************************************************************************/
 BEGIN 
  SET NOCOUNT ON
    BEGIN TRY
	 BEGIN TRANSACTION
	 IF(@IsApprove = 'Y')
		  BEGIN
		   UPDATE [dbo].[BillHeader]
			  SET [BILLNO]  = @BillNo, 
				  [BATCHNO] = @BatchNo 
			WHERE [MATTER]  = @Matter 
			  AND [DRAFTNO] = @DraftNo 
			  AND [BILLNO]  = 0 
		  END
	 ELSE
		  BEGIN
			UPDATE [dbo].[BillHeader]
			  SET [RELEASED]  = @Released
			WHERE [MATTER]    = @Matter 
			  AND [DRAFTNO]   = @DraftNo 
			  AND [BILLNO]    = 0 
		  END
        COMMIT TRANSACTION
	 END TRY
	 BEGIN CATCH
		   DECLARE @ErrorMsg      NVARCHAR(4000), 
  				   @ErrorSeverity INT,
  				   @ErrorState    INT; 
  
			SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
  				   @ErrorSeverity = ERROR_SEVERITY(), 
  				   @ErrorState    = ERROR_STATE()

		RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
  				 IF @@TRANCOUNT > 0  
  					BEGIN
  						ROLLBACK TRANSACTION;
  					END 
	 END CATCH
  SET NOCOUNT OFF

 END


 GO

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

CREATE PROCEDURE [dbo].[KAAS_SamBGBillAllItems]
	   (
			@GroupIDString	       VARCHAR(38)  = '',
			@Action			       INT          = 0
	   )
AS
/*******************************************************************************************************
* Billing guide Bill All Items     			                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBGBillAllItems]           									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-25    Vinodhkumar M        Created                                                           *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/
BEGIN 

	/* Actions:
	1 - Don't bill
	2 - Bill
	3 - Exclude from all bills
	*/
  BEGIN TRY
	BEGIN TRAN
		UPDATE [BGD]
		   SET [BGD].[BillNow]       = CASE WHEN @Action = 1
											THEN [BGD].[CHARGE] - [BGD].[BilledAmount]
											ELSE 0 END,
			   [BGD].[IncludeInBill] = CASE WHEN @Action = 3
											THEN 2
											ELSE 1 END
		  FROM [dbo].[BGGroups] [BGG]
			   INNER JOIN [dbo].[BGDetail] [BGD]
					   ON BGD.[BGGroupID] = [BGG].[ID]
		 WHERE [BGG].[ID] = CONVERT(uniqueidentifier, @GroupIDString)

		UPDATE [BGD2]
		   SET [BGD2].[BillNow]       = 0,
			   [BGD2].[IncludeInBill] = 0
		  FROM [dbo].[BGGroups] [BGG]
			   INNER JOIN [dbo].[BGDetail] [BGD]
					   ON [BGD].[BGGroupID] = [BGG].[ID]
			   INNER JOIN [dbo].[BGDetail] [BGD2]
					   ON [BGD2].[Type]        = BGD.[Type]
					  AND [BGD2].[OriginalID]  = [BGD].[OriginalID]
					  AND [BGD2].[BGControlID] <> [BGD].[BGControlID]
					  AND [BGD2].[InvoiceNo]   = 0
		 WHERE [BGG].[ID] = CONVERT(uniqueidentifier, @GroupIDString)
		 
  	COMMIT TRAN
	END TRY
		BEGIN CATCH 
			   DECLARE @ErrorMsg      NVARCHAR(4000), 
					   @ErrorSeverity INT,
					   @ErrorState    INT; 

				SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					   @ErrorSeverity = ERROR_SEVERITY(), 
					   @ErrorState    = ERROR_STATE()

			RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
					 IF @@TRANCOUNT > 0  
						BEGIN
							ROLLBACK TRANSACTION;
						END 
		END CATCH
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SamBillingGuideAddToInvoice' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SamBillingGuideAddToInvoice] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SamBillingGuideAddToInvoice]
		(@DraftNo	      INT = 0,
		 @DeleteExisting  VARCHAR(10) = NULL)
AS
/*******************************************************************************************************
* add to invoice							                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBillingGuideAddToInvoice]        	     				       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-22    vinodhkumar M        Created                                                           *
* 2021-10-27    vinodhkumar M        Modifed - added Delete Draft Bill Detail SP with Flag             *
* 2022-03-08    Balamurugan.C        Modified - Handled TCL Statements and Formatting                  *
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRAN
		SET NO_BROWSETABLE ON
		IF(@DeleteExisting = 'CLEAR')
		  BEGIN
			EXEC [dbo].[KAAS_DeleteDraftBillDetail] 0,@DraftNo
		  END
		EXEC ky_BGAddToInvoice @DraftNo

		INSERT 
			 INTO [dbo].[BillFeeBreakdown]
				 ([MATTER],
				  [DRAFTNO],
				  [BILLNO],
				  [FECODE],
				  [TYPE],
				  [PERCENT],
				  [CALCULATION],
				  [VALUE],
				  [VATCODE],
				  [VATAMT])
		   SELECT [NBFB].[MATTER],
				  [NBFB].[DRAFTNO],
				  [NBFB].[BILLNO],
				  [NBFB].[FECODE],
				  [NBFB].[TYPE],
				  [NBFB].[PERCENT],
				  [NBFB].[CALCULATION],
				  [NBFB].[VALUE],
				  [NBFB].[VATCODE],
				  [NBFB].[VATAMT]
			 FROM ky_BGNewBillFeeBreakdown(@DraftNo) [NBFB]
  LEFT OUTER JOIN [dbo].[BillFeeBreakdown] [BFB]
			   ON [BFB].[DRAFTNO] = [NBFB].[DRAFTNO]
			  AND [BFB].[FECODE]  = [NBFB].[FECODE]
			WHERE [BFB].[RECORDID] IS NULL

		UPDATE [BFB]
			  SET [BFB].[VALUE]  = [BFB].[VALUE] + [NBFB].[VALUE],
				  [BFB].[VATAMT] = [BFB].[VATAMT] + [NBFB].[VATAMT]
			 FROM [dbo].[BillFeeBreakDown] [BFB]
	   INNER JOIN ky_BGNewBillFeeBreakdown(@DraftNo) [NBFB]
			   ON [NBFB].[FECODE] = [BFB].[FECODE]
			WHERE [BFB].[DRAFTNO] = @DraftNo

			SET NO_BROWSETABLE OFF
		COMMIT TRAN
	END TRY

	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
			   @ErrorSeverity = ERROR_SEVERITY(), 
			   @ErrorState    = ERROR_STATE()

	 RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			  IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END 
	END CATCH

END

GO

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

CREATE PROCEDURE [dbo].[KAAS_SamBillingGuideControl]
	   (@DraftNo  INT = 0)
AS
/*******************************************************************************************************
* Get control details based on DraftNo				                                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBillingGuideControl]        								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-20    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN


	SELECT 
		  [ID]				AS   [Id],
		  [Date]			AS   [Date],
		  [TDate]			AS   [TDate],
		  [ODate]			AS	 [ODate],
		  [Description]		AS	 [Description],
		  [DRAFTNO]			AS	 [DraftNo],
		  [BATCHNO]			AS	 [BatchNo],
		  [ADDRESSEE]		AS	 [Addressee],
		  [OURREF]			AS	 [OurRef],
		  [YOURREF]			AS   [YourRef],
		  [MATTER]			AS	 [Matter],
		  [IsAdhoc]			AS   [IsAdhoc],
		  [OAmount]			AS   [OAmount],
		  [TAmount]			AS   [TAmount]
	FROM  
		  [dbo].[BGControl]
	WHERE 
		 [DRAFTNO] = @DraftNo

END
GO

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

CREATE PROCEDURE [dbo].[KAAS_SamBillingGuideDrillList]
	   (
			@GroupId VARCHAR(38)
	   )
AS
/*******************************************************************************************************
* List for Billing Guide				                                                               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBillingGuideDrillList]        								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2024-01-02    Ghayathri.S.V        Created                                                           *                                 *
*******************************************************************************************************/
BEGIN 

   SELECT	  [BGDE].[IncludeInBill]	        AS 	IncludeInBill,
			  [BGDE].[Type]				    AS  Type,
			  [BGDE].[MATTER]			    AS	Matter,
			  [BGDE].[FEEEARN]			    AS	FE,
			  [BGDE].[OUTLAYCODE]		    AS	OutlayCode,
			  [BGDE].[OUTLAYDESCRIPTION]	    AS  OutlayDescription,
			  [BGDE].[HANDLERNAME]			AS  HandlerName,
			  [BGDE].[TEAMNAME]				AS  TeamName,
			  [BGDE].[DATE]					AS  Date,
			  [BGDE].[COMMENT]				AS  Comment,
			  [BGDE].[InvoiceNo]			    AS  InvoiceNo,
			  [BGDE].[CHARGE]				AS  Charge,
			  [BGDE].[ORIGINALCHARGE]		AS  OriginalCharge,
			  [BGDE].[BilledAmount]			AS  BilledAmount,
			  [BGDE].[LeftToBill]			AS  LeftToBill,
			  [BGDE].[BillNow]				AS  BillNow,
          BGD.[DATE] AS [UNFDate],
          TIE.[task],
          RTRIM(IsNull(TT.[DESC], '')) AS [TaskDescription]
     FROM ky_BGListGroupDrillEntries(@GroupId) BGDE
          INNER JOIN [dbo].[BGDetail] BGD
                  ON BGD.[ID] = BGDE.[ItemID]
          LEFT OUTER JOIN [dbo].[TimeEntry] TIE
                          INNER JOIN [dbo].[TasksCodes] TT
                                  ON TT.[CODE] = TIE.[TASK] 
                       ON BGDE.[Type] = 'F'
                      AND TIE.[RECORDID] = BGD.[OriginalID]
 ORDER BY BGDE.[SeqNo]

END
GO

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

CREATE PROCEDURE [dbo].[KAAS_SamBillingGuideGroupConfig]
	   (@DraftNo			   INT = 0,
		@GroupType      VARCHAR(1) = NULL,
		@GroupHandler   VARCHAR(5) = NULL,
		@GroupOutlay   VARCHAR(10) = NULL,
		@GroupMatter   VARCHAR(17) = NULL,
		@GroupNarr    VARCHAR(255) = NULL,
		@NewGroupNarr VARCHAR(255) = NULL,
		@GroupingMode  VARCHAR(17) = NULL,
		@HandlerMode   VARCHAR(17) = NULL)
AS
/*******************************************************************************************************
* Billing Guide Grouping Cofiguration								                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBillingGuideGroupConfig]        							   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-21    Vinodhkumar M        Created                                                           *
* 2024-01-02    Ghayathri.S.V		Updated the code logic as per Framework  Version                   *
*******************************************************************************************************/
BEGIN


		DECLARE @ControlID	INT = 0

		SELECT @CONTROLID = [ID]
		  FROM [dbo].[BGControl]
		 WHERE [DRAFTNO] = @DraftNo

		 IF(@GroupingMode = 'SINGLE')
			BEGIN
				IF (@GroupType IS NOT NULL)
					SET @GroupType = substring(@GroupType, 1, 1)
    
				IF (@NEWGroupNarr IS NOT NULL)
					Set @NEWGroupNarr = SUBSTRING(@NEWGroupNarr, 1, 255)

				IF (@GroupNarr IS NOT NULL)
					SET @GroupNarr = SUBSTRING(@GroupNarr, 1, 255)

				IF (@GroupHandler IS NOT NULL)
					Set @GroupHandler = SubString(@GroupHandler, 1, 5)

				IF (@GroupOutlay IS NOT NULL)
					Set @GroupOutlay = SUBSTRING(@GroupOutlay, 1, 10)

				IF (@GroupMatter IS NOT NULL)
					SET @GroupMatter = SUBSTRING(@GroupMatter, 1, 17)

				EXEC [dbo].[ky_QuickGroupBG]
					 @ControlID,
					 @GroupType,
					 @GroupHandler,
					 @GroupOutlay,
					 @GroupMatter,
					 @GroupNarr,
					 @NEWGroupNarr

			 END

		 ELSE IF(@GroupingMode = 'GROUP')
			BEGIN
		 	    DECLARE @column1 VARCHAR(10), @column2 VARCHAR(10), @column3 VARCHAR(200)

				IF(@HandlerMode = 'OUTLAY')
					BEGIN
						DECLARE your_cursor CURSOR FOR
						SELECT @GroupType, UF.[OUTLAYCODE],
							Case WHEN RTRIM(IsNull(OLC.[DESCRIPTION], '')) = ''
								 THEN '(unspecified)'
								 ELSE RTrim(OLC.[Description]) END As [OutlayDescription]
						FROM ( SELECT DISTINCT BGD.[OUTLAYCODE]
							   FROM [dbo].[BGDetail] BGD
							   WHERE BGD.[BGControlID] = @CONTROLID
							   AND BGD.[Type] = 'O') UF
						       LEFT OUTER JOIN [dbo].[OutlayCode] OLC
							   ON OLC.[CODE] = UF.[OUTLAYCODE]
					END

				ELSE IF(@HandlerMode = 'FEE')
					BEGIN
						DECLARE your_cursor CURSOR FOR
						SELECT @GroupType, UF.[FEEEARN],
							   HAN.[Name] As [HandlerName]
						FROM ( SELECT DISTINCT BGD.[FEEEARN]
							   FROM [dbo].[BGDetail] BGD
							   WHERE BGD.[BGControlID] = 572
						       AND BGD.[Type] = 'F') UF
							   INNER JOIN [dbo].[HANDLERS] HAN
							   ON HAN.[CODE] = UF.[FEEEARN]
					END

				OPEN your_cursor;
				FETCH NEXT FROM your_cursor INTO @column1, @column2, @column3
				WHILE @@FETCH_STATUS = 0 
				BEGIN
					SET @GroupType = @column1
					SET @GroupHandler = NULL
					SET @GroupOutlay = @column2
					SET @GroupMatter = NULL
					SET @GroupNarr = NULL
					SET @NEWGroupNarr = 'Total ' + @column3

					IF (@GroupType IS NOT NULL)
						SET @GroupType = substring(@GroupType, 1, 1)
    
					IF (@NEWGroupNarr IS NOT NULL)
						Set @NEWGroupNarr = SUBSTRING(@NEWGroupNarr, 1, 255)

					IF (@GroupNarr IS NOT NULL)
						SET @GroupNarr = SUBSTRING(@GroupNarr, 1, 255)

					IF (@GroupHandler IS NOT NULL)
						Set @GroupHandler = SubString(@GroupHandler, 1, 5)

					IF (@GroupOutlay IS NOT NULL)
						Set @GroupOutlay = SUBSTRING(@GroupOutlay, 1, 10)

					IF (@GroupMatter IS NOT NULL)
						SET @GroupMatter = SUBSTRING(@GroupMatter, 1, 17)

					EXEC [dbo].[ky_QuickGroupBG]
						 @ControlID,
						 @GroupType,
						 @GroupHandler,
						 @GroupOutlay,                           
						 @GroupMatter,
					     @GroupNarr,
					     @NEWGroupNarr
																											
    
					FETCH NEXT FROM your_cursor INTO @column1,@column2, @column3
			   END
				CLOSE your_cursor;
				DEALLOCATE your_cursor;


			 END



END
GO



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

CREATE PROCEDURE [dbo].[KAAS_SamBillingGuideIDConfig]
	   (@DraftNo			INT = 0,
	    @TimrefDate			DATETIME   = NULL,
	    @OutlayRefDate		DATETIME   = NULL,
	    @TimeAmt			DECIMAL(19,2) = 0,
	    @OutlayAmt			DECIMAL(19,2) = 0)
AS
/*******************************************************************************************************
* Billing Guide ID incremental Cofiguration		                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBillingGuideIDConfig]        								   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-20    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN
	DECLARE @CONTROLID int
	DECLARE @TIMEREFAMOUNT money
	DECLARE @OUTLAYAMOUNT money

	SET @TIMEREFAMOUNT = Convert(MONEY,  @TimeAmt)
	SET @OUTLAYAMOUNT = Convert(MONEY,   @OutlayAmt)

	EXEC [dbo].[ky_InitialiseBG] @DraftNo, NULL, @TimrefDate, @OutlayRefDate, @TIMEREFAMOUNT, @OUTLAYAMOUNT

	SELECT @CONTROLID = [ID]
	  FROM [dbo].[BGControl]
	 WHERE [DRAFTNO] = @DraftNo
 
	EXEC [dbo].[ky_UngroupBG] @CONTROLID, 0
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_SamBillingGuideList]
	   (@Id	     INT = 0,
	    @DraftNo INT = 0)
AS
/*******************************************************************************************************
* List for Billing Guide				                                                               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamBillingGuideList]        									   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-20    Vinodhkumar M        Created                                                           *
* 2021-10-27    Vinodhkumar M        Modified- new parameter is added                                  *
*******************************************************************************************************/
BEGIN 
	   SELECT 
			  [BGE].[IncludeInBill]	        AS 	IncludeInBill,
			  [BGE].[Type]				    AS  Type,
			  [BGE].[MATTER]			    AS	Matter,
			  [BGE].[FEEEARN]			    AS	FE,
			  [BGE].[OUTLAYCODE]		    AS	OutlayCode,
			  [BGE].[OUTLAYDESCRIPTION]	    AS  OutlayDescription,
			  [BGE].[HANDLERNAME]			AS  HandlerName,
			  [BGE].[TEAMNAME]				AS  TeamName,
			  [BGE].[DATE]					AS  Date,
			  [BGE].[COMMENT]				AS  Comment,
			  [BGE].[InvoiceNo]			    AS  InvoiceNo,
			  [BGE].[CHARGE]				AS  Charge,
			  [BGE].[ORIGINALCHARGE]		AS  OriginalCharge,
			  [BGE].[BilledAmount]			AS  BilledAmount,
			  [BGE].[LeftToBill]			AS  LeftToBill,
			  [BGE].[BillNow]				AS  BillNow,
			  [BGE].[GroupNumber]			AS  GroupNumber,
			  [BGE].[NumberOfDetailItems]   AS  NumberOfDetailItems,
			  [BGE].[Grouped]				AS  Grouped,
			  [BGE].[GroupID]				AS	GroupId
    FROM 
			  [ky_BGListGroupedEntries](@Id) [BGE]
	ORDER BY  
	CASE WHEN [BGE].[Type] = 'F'
         THEN 0
         ELSE 1 END,
		 [BGE].[GroupNumber]

	SELECT [TotalFees]		AS   TotalFees,
		   [TotalOutlay]    AS   TotalOutlay,
		   [GrandTotal]		AS   GrandTotal
	FROM   ky_BGListTotals(@Id)

	SELECT [DraftNo]		AS   DraftNo,
		   [Matter]			AS   Matter,
		   [Total]			AS   Total,
		   [FEES]			AS	 Fees,
		   [OUTLAY]			AS   Outlay
    FROM   [dbo].[BillHeader]
	WHERE  [DRAFTNO] = @DraftNo 

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMBillingGuideProcess' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMBillingGuideProcess] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMBillingGuideProcess]
       (
	      @BatchNo INT
	   )
AS
  /*******************************************************************************************************
  * Update Posting Logic                                                                                 * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_SAMBillingGuideProcess]   			            				 *
  * Copied From           : [dbo].[ky_BGProcess]                                                         *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-11-25    Balamurugan C        Created                                                           *
  *******************************************************************************************************/
BEGIN

   DECLARE @ControlID int
   DECLARE @DefaultBilldate datetime
   DECLARE @AdHocBillingGuide int
   DECLARE @DraftNo int

   UPDATE BGC
      SET @ControlID = [ID],
          @DraftNo = IsNull(BIH.[DRAFTNO], BGC.[DraftNo]),
          BGC.[DraftNo] = IsNull(BIH.[DRAFTNO], BGC.[DraftNo]),
          BGC.[BatchNo] = IsNull(BIH.[BATCHNO], BGC.[BatchNo])
     FROM [dbo].[BillHeader] BIH
          INNER JOIN [dbo].[BGControl] BGC
                  ON BGC.[DraftNo] = BIH.[DraftNo]
    WHERE BIH.[BATCHNO] = @BatchNo

   SET @AdHocBillingGuide = 0

   IF (@ControlID is NULL)
      BEGIN
         -- Create an ungrouped Billing Guide for the writedown date, then process it as normal.
         -- This Billing Guide will be flagged as "ad hoc", as it was not generated and configured
         -- by the user. If the billing is subsequently reversed, this ad hoc billing guide will
         -- be deleted. Billing Guides that were generated and configured by the user will not be
         -- deleted when billing is reversed, and they can be used again.
         SET @AdHocBillingGuide = 1

         SELECT @DefaultBillDate = convert(datetime, [WRITEDOWN])
           FROM [dbo].[BatchH]
          WHERE [BATCHNO] = @BatchNo

         EXEC ky_InitialiseBG @DraftNo, @BatchNo, @DefaultBillDate, @DefaultBillDate, NULL, NULL

         UPDATE BGC
            SET IsAdHoc = 1,
                @ControlID = [ID]
           FROM [dbo].[BGControl] BGC
          WHERE [BATCHNO] = @BatchNo
      END

   UPDATE TEN
      SET TEN.[InvoiceNo] = Case When isnumeric(IsNull(BAH.[REF], '')) <> 1
                                      Then 0
                                 When convert(char(10), convert(decimal(10,0), IsNull(BAH.[REF], ''))) <> IsNull(BAH.[REF], '')
                                      Then 0
                                 ELSE convert(int, convert(decimal(10,0), IsNull(BAH.[REF], ''))) END,
          TEN.[BILLINGDATE] = BAH.[DATE],
          TEN.[BILLINGYEAR] = BAH.[YEAR],
          TEN.[BILLINGPERIOD] = BAH.[PERNO],
          TEN.[IncludeInBill] = CASE WHEN IsNull(BGD.[IncludeInBill], 1) <> 2
                                          THEN 1
                                     ELSE 2 END,
          TEN.[BilledAmount] =   IsNull(TEN.[BilledAmount], 0)
                               + IsNull(BGD.[BillNow], 0)
     FROM [dbo].[BGControl] BGC
          INNER JOIN [dbo].[BGGroups] BGG
                     INNER JOIN [dbo].[BGDetail] BGD
                                INNER JOIN [dbo].[TimeEntry] TEN
                                        ON TEN.[RECORDID] = BGD.[OriginalID]
                             ON BGD.[BGGroupID] = BGG.[ID]
                            AND BGD.[Type] = 'F'
                  ON BGG.[BGControlID] = BGC.[ID]
          INNER JOIN [dbo].[BATCHH] BAH
                  ON BAH.[BatchNo] = BGC.[BatchNo]
    WHERE BGC.[BatchNO] = @BatchNo
      --AND IsNull(TEN.[INVOICENO], 0) <> 0
      AND BGD.[BillNow] <> 0
      AND IsNull(BGD.[IncludeInBill], 1) <> 2

   UPDATE TEN
      SET TEN.[IncludeInBill] = 2
     FROM [dbo].[BGControl] BGC
          INNER JOIN [dbo].[BGGroups] BGG
                     INNER JOIN [dbo].[BGDetail] BGD
                                INNER JOIN [dbo].[TimeEntry] TEN
                                        ON TEN.[RECORDID] = BGD.[OriginalID]
                             ON BGD.[BGGroupID] = BGG.[ID]
                            AND BGD.[Type] = 'F'
                  ON BGG.[BGControlID] = BGC.[ID]
          INNER JOIN [dbo].[BATCHH] BAH
                  ON BAH.[BatchNo] = BGC.[BatchNo]
    WHERE BGC.[BatchNO] = @BatchNo
      AND IsNull(BGD.[IncludeInBill], 1) = 2

   UPDATE MAL
      SET MAL.[InvoiceNo] = Case When isnumeric(IsNull(BAH.[REF], '')) <> 1
                                      Then 0
                                 When convert(char(10), convert(decimal(10,0), IsNull(BAH.[REF], ''))) <> IsNull(BAH.[REF], '')
                                      Then 0
                                 ELSE convert(int, convert(decimal(10,0), IsNull(BAH.[REF], ''))) END,
          MAL.[BILLINGDATE] = BAH.[DATE],
          MAL.[BILLINGYEAR] = BAH.[YEAR],
          MAL.[BILLINGPERIOD] = BAH.[PERNO],
          MAL.[IncludeInBill] = CASE WHEN IsNull(BGD.[IncludeInBill], 1) <> 2
                                          THEN 1
                                     ELSE 2 END,
          MAL.[BilledOutlayValue] =   IsNull(MAL.[BilledOutlayValue], 0)
                                    + IsNull(BGD.[BillNow], 0)
     FROM [dbo].[BGControl] BGC
          INNER JOIN [dbo].[BGGroups] BGG
                     INNER JOIN [dbo].[BGDetail] BGD
                                INNER JOIN [dbo].[MatterLedger] MAL
                                        ON MAL.[LREF] = BGD.[OriginalID]
                             ON BGD.[BGGroupID] = BGG.[ID]
                            AND BGD.[Type] = 'O'
                  ON BGG.[BGControlID] = BGC.[ID]
          INNER JOIN [dbo].[BATCHH] BAH
                  ON BAH.[BatchNo] = BGC.[BatchNo]
    WHERE BGC.[BATCHNO] = @BatchNo
      --AND IsNull(MAL.[INVOICENO], 0) <> 0
      AND BGD.[BillNow] <> 0
      AND IsNull(BGD.[IncludeInBill], 1) <> 2

   UPDATE MAL
      SET MAL.[IncludeInBill] = 2
     FROM [dbo].[BGControl] BGC
          INNER JOIN [dbo].[BGGroups] BGG
                     INNER JOIN [dbo].[BGDetail] BGD
                                INNER JOIN [dbo].[MatterLedger] MAL
                                        ON MAL.[LREF] = BGD.[OriginalID]
                             ON BGD.[BGGroupID] = BGG.[ID]
                            AND BGD.[Type] = 'O'
                  ON BGG.[BGControlID] = BGC.[ID]
          INNER JOIN [dbo].[BATCHH] BAH
                  ON BAH.[BatchNo] = BGC.[BatchNo]
    WHERE BGC.[BATCHNO] = @BatchNo
      AND IsNull(BGD.[IncludeInBill], 1) = 2

   UPDATE MAT
      SET MAT.[CHARGEBAL] = GTOT.[BALAMOUNT],
          MAT.[TimeBal] = GTOT.[BALTIME]
     FROM (  SELECT GMAT.[code],
                    IsNull(SUM(  IsNull(TIE.[CHARGE], 0)
                               - IsNull(TIE.[BILLEDAMOUNT],
                           0)), 0) AS [BALAMOUNT],
                    IsNull(SUM(CASE WHEN IsNull(TIE.[CHARGE], 0) <> IsNull(TIE.[BILLEDAMOUNT], 0)
                                         THEN IsNull(TIE.[Time], 0)
                                    ELSE 0 END),
                           0) AS [BALTIME]
               FROM [dbo].[BatchH] BAH
                    INNER JOIN [dbo].[Matters] GMAT
                               LEFT OUTER JOIN [dbo].[TimeEntry] TIE
                                            ON TIE.[Matter] = GMAT.[code]
                                           AND TIE.[Charge] <> TIE.[BilledAmount]
                                           AND TIE.[Timeorcharge] IN ('T', 'C')
                                           AND TIE.[REC_IRR] <> 'N'
                                           AND IsNull(TIE.[IncludeInBill], 1) <> 2
                            ON GMAT.[code] = BAH.[MATTER]
                            OR GMAT.[CompBillingMatter] = BAH.[MATTER]
             WHERE BAH.[BATCHNO] = @BatchNo
                      GROUP BY GMAT.[code]) GTOT
          INNER JOIN [dbo].[Matters] MAT
                  ON MAT.[code] = GTOT.[code]

   INSERT
     INTO [dbo].[MatterLedger] 
         ([MATTER],
          [BATCHNO],
          [PREF],
          [DATE],
          [REF],
          [NARR],
          [VALUED],
          [VALUEO],
          [VALUEC],
          [FEE],
          [PER],
          [YEAR],
          [ENTRYDATE],
          [CLIENT],
          [VALUECC],
          [VALUECD],
          [DEPOSITTYPE],
          [CURVALUED],
          [CURVALUEO],
          [CURVALUEC],
          [CURVALUECC],
          [CURVALUECD],
          [BILLED],
          [BILLINGYEAR],
          [BILLINGPERIOD],
          [BILLINGDATE],
          [BilledOutlayValue],
          [InvoiceNo],
          [IncludeInBill])
   SELECT MLTOT.[MATTER],
          0 AS BATCHNO,
          0 AS PREF,
          convert(datetime, convert(varchar, getDate(), 106)) AS [DATE],
          LTrim(RTrim(IsNull(BAH.[REF], ''))),
          Substring(  'Invoice No: '
                    + LTrim(RTrim(IsNull(BAH.[REF], '')))
                    + '   Fee: '
                    + convert(varchar(20), MLTOT.[TOTALFEES])
                    + '   Outlay: '
                    + convert(varchar(20), MLTOT.[TOTALOUTLAY])
                    + '   See Matter: '
                    + LTrim(RTrim(MLTOT.[CompBillingMatter])),
                    1,
                    80) As [NARR],
          0 As [VALUED],
          0 As [VALUEO],
          0 As [VALUEC],
          '' AS [FEE],
          0 As [PER],
          0 As [YEAR],
          convert(datetime, NULL) AS [ENTRYDATE],
          MLTOT.[CLIENTCODE] AS [CLIENT],
          0 As [VALUECC],
          0 As [VALUECD],
          '' AS [DEPOSITTYPE],
          0 As [CURVALUED],
          0 As [CURVALUEO],
          0 As [CURVALUEC],
          0 As [CURVALUECC],
          0 As [CURVALUECD],
          '' AS [BILLED],
          NULL AS [BILLINGYEAR],
          NULL AS [BILLINGPERIOD],
          convert(datetime, NULL) AS [BILLINGDATE],
          0 AS [BilledOutlayValue],
          NULL AS [InvoiceNo],
          2 AS [IncludeInBill]
     FROM (   SELECT ML.[MATTER],
                     MAT.[ClientCode],
                     MAT.[CompBillingMatter],
                     IsNull(SUM(CASE WHEN BGD.[Type] = 'F'
                                          THEN IsNull(BGD.[BillNow], 0)
                                     ELSE 0 END), 0) As TOTALFEES,
                     IsNull(SUM(CASE WHEN BGD.[Type] = 'O'
                                          THEN IsNull(BGD.[BillNow], 0)
                                     ELSE 0 END), 0) As TOTALOutlay
                FROM (   SELECT DISTINCT
                                BGDML.[MATTER],
                                BGCML.[ID]
                           FROM [dbo].[BGControl] BGCML
                                INNER JOIN [dbo].[BGGroups] BGGML
                                           INNER JOIN [dbo].[BGDetail] BGDML
                                                   ON BGDML.[BGGroupID] = BGGML.[ID]
                                        ON BGGML.[BGControlID] = BGCML.[ID]
                          WHERE BGCML.[BatchNO] = @BatchNo
                            AND BGDML.[BillNow] <> 0
                            AND IsNull(BGDML.[IncludeInBill], 1) <> 2
                            AND BGDML.[MATTER] <> BGCML.[MATTER]) ML
                     INNER JOIN [dbo].[BGGroups] BGG
                                INNER JOIN [dbo].[BGDetail] BGD
                                        ON BGD.[BGGroupID] = BGG.[ID]
                                       AND BGD.[BillNow] <> 0
                                       AND IsNull(BGD.[IncludeInBill], 1) <> 2
                             ON BGG.[BGControlID] = ML.[ID]
                            AND BGD.[matter] = ML.[MATTER]
                     INNER JOIN [dbo].[MATTERS] MAT
                             ON MAT.[Code] = ML.[MATTER]
            GROUP BY ML.[Matter],
                     MAT.[ClientCode],
                     MAT.[CompBillingMatter]) MLTOT
          INNER JOIN [dbo].[BATCHH] BAH
                  ON BAH.[BATCHNO] = @BatchNo

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMBillingGuideReset' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMBillingGuideReset] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMBillingGuideReset]
      (
			@BatchNo INT
	  )
AS
  /*******************************************************************************************************
  * Reset Billing Guide                                                                                  * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_SAMBillingGuideReset]   			            				 *
  * Copied From           : [dbo].[ky_BGReset]                                                           *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-11-25    Balamurugan C        Created                                                           *
  *******************************************************************************************************/
BEGIN
   DECLARE @NCOMMAND NVARCHAR(MAX)

   IF [dbo].[ISSAM4]() = 0
     BEGIN
       SET @NCOMMAND = N'
   IF IsNull(@BatchNo, 0) <> 0
      BEGIN
         UPDATE TEN
            SET TEN.[InvoiceNo] = ISNULL(BGD.[ORGInvoiceNo], 0),
                TEN.[BILLINGDATE] = BGD.[ORGBILLINGDATE],
                TEN.[BILLINGYEAR] = BGD.[ORGBILLINGYEAR],
                TEN.[BILLINGPERIOD] = BGD.[ORGBILLINGPERIOD],
                TEN.[IncludeInBill] = BGD.[ORGIncludeInBill],
                TEN.[BilledAmount] = TEN.[BilledAmount] - BGD.[BillNow]
           FROM [dbo].[BGControl] BGC
                INNER JOIN [dbo].[BGGroups] BGG
                           INNER JOIN [dbo].[BGDetail] BGD
                                      INNER JOIN [dbo].[TimeEntry] TEN
                                              ON TEN.[RECORDID] = BGD.[OriginalID]
                                   ON BGD.[BGGroupID] = BGG.[ID]
                                  AND BGD.[Type] = ''F''
                        ON BGG.[BGControlID] = BGC.[ID]
          WHERE BGC.[BatchNO] = @BatchNo

         UPDATE MAL
            SET MAL.[InvoiceNo] = ISNULL(BGD.[ORGInvoiceNo], 0),
                MAL.[BILLINGDATE] = BGD.[ORGBILLINGDATE],
                MAL.[BILLINGYEAR] = BGD.[ORGBILLINGYEAR],
                MAL.[BILLINGPERIOD] = BGD.[ORGBILLINGPERIOD],
                MAL.[IncludeInBill] = BGD.[ORGIncludeInBill],
                MAL.[BilledOutlayValue] = MAL.[BilledOutlayValue] - BGD.[BillNow]
           FROM [dbo].[BGControl] BGC
                INNER JOIN [dbo].[BGGroups] BGG
                           INNER JOIN [dbo].[BGDetail] BGD
                                      INNER JOIN [dbo].[MatterLedger] MAL
                                              ON MAL.[LREF] = BGD.[OriginalID]
                                   ON BGD.[BGGroupID] = BGG.[ID]
                                  AND BGD.[Type] = ''O''
                        ON BGG.[BGControlID] = BGC.[ID]
          WHERE BGC.[BATCHNO] = @BatchNo

         -- If these items were billed without a billing guide, the Billing Guide that was 
         -- generated was an Ad Hoc billing guide that wasn''t configured by the user. In that
         -- case, delete it now.
         DELETE BGD
           from [dbo].[BGControl] BGC
                INNER JOIN [dbo].[BGGroups] BGG
                           INNER JOIN [dbo].[BGDetail] BGD
                                   ON BGD.[BGGroupID] = BGG.[ID]
                        ON BGG.[BGControlID] = BGC.[Id]
          WHERE BGC.[BatchNo] = @BatchNo
            AND BGC.[IsAdhoc] = 1

         DELETE BGG
           from [dbo].[BGControl] BGC
                INNER JOIN [dbo].[BGGroups] BGG
                        ON BGG.[BGControlID] = BGC.[Id]
          WHERE BGC.[BatchNo] = @BatchNo
            AND BGC.[IsAdhoc] = 1

         DELETE BGC
           from [dbo].[BGControl] BGC
          WHERE BGC.[BatchNo] = @BatchNo
            AND BGC.[IsAdhoc] = 1

         UPDATE MAT
            SET MAT.[CHARGEBAL] = GTOT.[BALAMOUNT],
                MAT.[TimeBal] = GTOT.[BALTIME]
           FROM (  SELECT GMAT.[code],
                          IsNull(SUM(  IsNull(TIE.[CHARGE], 0)
                                     - IsNull(TIE.[BILLEDAMOUNT],
                                 0)), 0) AS [BALAMOUNT],
                          IsNull(SUM(CASE WHEN IsNull(TIE.[CHARGE], 0) <> IsNull(TIE.[BILLEDAMOUNT], 0)
                                               THEN IsNull(TIE.[Time], 0)
                                          ELSE 0 END),
                                 0) AS [BALTIME]
                     FROM [dbo].[BatchH] BAH
                          INNER JOIN [dbo].[Matters] GMAT
                                     LEFT OUTER JOIN [dbo].[TimeEntry] TIE
                                                  ON TIE.[Matter] = GMAT.[code]
                                                 AND TIE.[Charge] <> TIE.[BilledAmount]
                                                 AND TIE.[Timeorcharge] IN (''T'', ''C'')
                                                 AND TIE.[REC_IRR] <> ''N''
                                                 AND IsNull(TIE.[IncludeInBill], 1) <> 2
                                  ON GMAT.[code] = BAH.[MATTER]
                                  OR GMAT.[CompBillingMatter] = BAH.[MATTER]
                   WHERE BAH.[BATCHNO] = @BatchNo
                            GROUP BY GMAT.[code]) GTOT
                INNER JOIN [dbo].[Matters] MAT
                        ON MAT.[code] = GTOT.[code]

          EXEC [dbo].[ky_BGPaid] NULL, @BatchNo, 0, 0, 0
      END'
       
       EXECUTE sp_executesql @NCOMMAND, N'@BatchNo INT', @BatchNo       
     END

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMBillingGuideReverseTransfer' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMBillingGuideReverseTransfer] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMBillingGuideReverseTransfer]
      (
		@BatchNo INT
	  )
AS
/*******************************************************************************************************
* Billing Guide Reverse Transfer                                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SAMBillingGuideReverseTransfer]   			            	   *
* Copied From           : [dbo].[ky_BGReverseTransfer]                                                 *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-25    Balamurugan C        Created                                                           *
*******************************************************************************************************/
BEGIN
   DECLARE @CRBatchNo int

   DECLARE @NewBatchNo int
   DECLARE @LastBatchHPREF int
   DECLARE @LastBatchDPREF int
   DECLARE @OUTLAY char(10)
   DECLARE @OVAT char(1)
   DECLARE @BASECUR char(1)
   DECLARE @IECONVERT decimal(9, 6)

   DECLARE @DETVALUE decimal(17, 2)
   DECLARE @DETMATTER char(11)
   DECLARE @DETNo int
   DECLARE @DETTotal int

   DECLARE @INVOICENO int

   DECLARE @DETs TABLE
          ([seqno]             int             identity(1, 1),
           [DETVALUE]          decimal(17, 2),
           [DETMATTER]         VARCHAR(20))

   SELECT @CRBatchNo = BHC.[CreditInvoiceNo]
     FROM [dbo].[BATCHH] BHC
    WHERE BHC.[BATCHNO] = @BatchNo

   SELECT @INVOICENO = CASE WHEN IsNumeric(BAH.[REF]) = 1
                            THEN convert(int, BAH.[REF])
                       ELSE 0 END
     FROM [dbo].[BATCHH] BAH
    WHERE BAH.[BATCHNO] = @BATCHNO

   UPDATE CON
      SET @NewBatchNo = IsNull(CON.[LASTBATCH], 0) + 1,
          CON.[LASTBATCH] = IsNull(CON.[LASTBATCH], 0) + 1,
          @LastBatchHPREF = IsNull(CON.[LASTPREF], 0) + 1,
          CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
     FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[BATCHH]
         ([BATCHNO],
          [POSTFWD],
          [TYPE],
          [CODE],
          [BRANCH],
          [PREF],
          [REF],
          [DATE],
          [FEE],
          [MATTER],
          [SUPP],
          [NARR],
          [VALUE],
          [SUBTOT],
          [POSTED],
          [CLIENTAC],
          [PERNO],
          [YEAR],
          [PAYEE],
          [OUTLAYTOT],
          [VATTOT],
          [FEETOT],
          [INVCR],
          [THIRDPARTY],
          [USERCODE],
          [HandlerCode],
          [ENTRYDATE],
          [CURRENCY],
          [CURRENCYVALUE],
          [CUROUTLAYTOT],
          [CURVATTOT],
          [CURFEETOT],
          [RECNO],
          [SINGLELINE],
          [TEMPLATE],
          [CHEQUEREQNO],
          [WRITEDOWN],
          [WRITEBACKHOURS],
          [WRITEBACKVALUE],
          [CORRECTCOPY])
   select @NewBatchNo As [BATCHNO],
          BAH.[POSTFWD] AS [POSTFWD],
          convert(char(1), 'J') AS [TYPE],
          convert(char(10), '') AS [CODE],
          convert(varchar(3), '') AS [BRANCH],
          @LastBatchHPREF AS [PREF],
          convert(char(10), 'xCompBill') AS [REF],
          BCN.[DATE] AS [DATE],
          BAH.[FEE] AS [FEE],
          BAH.[MATTER] AS [MATTER],
          convert(char(10), '') AS [SUPP],
          convert(char(150), 'Composite Bill Outlay Transfer') AS [NARR],
          convert(decimal(17,2), 0) As [VALUE],
          convert(decimal(17,2), 0) As [SUBTOT],
          convert(char(1), 'Y') AS [POSTED],
          convert(char(1), 'N') AS [CLIENTAC],
          BAH.[PERNO] AS [PERNO],
          BAH.[YEAR] AS [YEAR],
          convert(char(60), '') AS [PAYEE],
          convert(decimal(17,2), 0) AS [OUTLAYTOT],
          convert(decimal(17,2), 0) AS [VATTOT],
          convert(decimal(17,2), 0) AS [FEETOT],
          convert(char(1), 'I') AS [INVCR],
          convert(char(1), 'N') AS [THIRDPARTY],
          BAH.[USERCODE] AS [USERCODE],
          BAH.[HandlerCode] AS [HandlerCode],
          convert(datetime, convert(varchar, getDate(), 106)) AS [ENTRYDATE],
          BAH.[CURRENCY] AS [CURRENCY],
          convert(decimal(17,2), 0) AS [CURRENCYVALUE],
          convert(decimal(17,2), 0) AS [CUROUTLAYTOT],
          convert(decimal(17,2), 0) AS [CURVATTOT],
          convert(decimal(17,2), 0) AS [CURFEETOT],
          convert(int, 0) AS [RECNO],
          convert(char(1), '') AS [SINGLELINE],
          convert(char(10), '') AS [TEMPLATE],
          convert(int, 0) AS [CHEQUEREQNO],
          convert(datetime, NULL) AS [WRITEDOWN],
          convert(decimal(7,2), 0) AS [WRITEBACKHOURS],
          convert(decimal(13,2), 0) AS [WRITEBACKVALUE],
          convert(char(1), 0) AS [CORRECTCOPY]
     FROM [dbo].[BatchH] BAH
          INNER JOIN [dbo].[BatchH] BCN
                  ON BCN.[BATCHNO] = @CRBatchNo
    WHERE BAH.[BATCHNO] = @BatchNo

     INSERT
       INTO @DETs
           ([DETMATTER],
            [DETVALUE])
     SELECT BGM.[MATTER],
            -ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
       FROM [dbo].[ky_CompBillMatterByBatch](@CRBatchNo) BGM
            INNER JOIN [dbo].[BGDetail] BGD
                    ON BGD.[BGGroupID] = BGM.[ID]
                   AND BGD.[Matter] = BGM.[Matter]
   GROUP BY BGM.[Matter]

   SELECT @DETTotal = COUNT(1) FROM @DETs

   SET @DETNo = 1
   WHILE @DETNo <= @DETTotal
     BEGIN
       SET @DETMATTER = ''
       SET @DETVALUE = 0

       SELECT @DETMATTER = DET.[DETMATTER],
              @DETVALUE = DET.[DETVALUE]
         FROM @DETs DET
        WHERE DET.[seqno] = @DETNo

       SET @DETVALUE = ISNULL(@DETVALUE, 0)

       UPDATE CON
          SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
              CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1,
              @OUTLAY = CON.[OUTLAY],
              @OVAT = CON.[VATEXCLUDE],
              @BASECUR = CON.[BASECURRENCY],
              @IECONVERT = CON.[IECONVERT]
         FROM [dbo].[control] CON

       INSERT
         INTO [dbo].[BatchDetails]
             ([BATCHNO],
              [TYPE],
              [CODE],
              [PREF],
              [REF],
              [DATE],
              [FEE],
              [BRANCH],
              [SUPP],
              [NARR],
              [MATTER],
              [VALUE],
              [VATCODE],
              [VATVAL],
              [CLIENTYN],
              [OUTLAY],
              [PENDING],
              [YEAR],
              [PERNO],
              [ENTRYCURRENCY],
              [CURRENCYVALUE],
              [CURRENCYVAT],
              [OUTLAYCODE],
              [THIRDPARTY],
              [PAYEE],
              [HEADPREF],
              [HEADBATCH],
              [ALLOCBATCH],
              [ALLOCPREF],
              [ALLOCREF],
              [ALLOCVALUE],
              [ALLOCWRITEOFF],
              [PSUPP],
              [UNDETAKING])
       SELECT @NewBatchNo As [BATCHNO],
              convert(char(1), 'J') AS [TYPE],
              @OUTLAY AS [CODE],
              @LastBatchDPREF AS [PREF],
              convert(char(10), 'xCompTFer') AS [REF],
              BAH.[DATE] AS [DATE],
              convert(char(3), '') AS FEE,
              convert(varchar(3), '') AS BRANCH,
              convert(char(10), '') AS [SUPP],
              convert(char(150), 'COMP: CREDIT Outlay Transfer from ' + BAH.[MATTER]) AS [NARR],
              convert(char(11), @DETMATTER) AS [MATTER],
              -@DETVALUE As [VALUE],
              @OVAT AS [VATCODE],
              convert(decimal(17,2), 0) As [VATVAL],
              convert(char(1), 'N') AS [CLIENTYN],
              convert(char(1), 'O') AS [OUTLAY],
              convert(char(1), '') AS [PENDING],
              BAH.[YEAR] AS [YEAR],
              BAH.[PERNO] AS [PERNO],
              @BASECUR AS [ENTRYCURRENCY],
              convert(decimal(17, 2), round((-@DETVALUE) * @IECONVERT, 2)) AS [CURRENCYVALUE],
              convert(decimal(17,2), 0) As [CURRENCYVAT],
              convert(char(4), '') AS [OUTLAYCODE],
              convert(char(1), '') AS [THIRDPARTY],
              convert(char(60), '') AS [PAYEE],
              convert(int, 0) AS [HEADPREF],
              convert(int, 0) AS [HEADBATCH],
              convert(int, 0) AS [ALLOCBATCH],
              convert(int, 0) AS [ALLOCPREF],
              convert(char(10), '') AS [ALLOCREF],
              convert(decimal(17, 2), 0) AS [ALLOCVALUE],
              convert(char(1), '') AS [ALLOCWRITEOFF],
              convert(char(10), '') AS [PSUPP],
              convert(smallint, 0) AS [UNDETAKING]
         FROM [dbo].[BATCHH] BAH
        WHERE BAH.[PREF] = @LastBatchHPRef

       --UPDATE CON
       --   SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
       --       CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
       --  FROM [dbo].[control] CON

       INSERT
         INTO [dbo].[MatterLedger]
             ([MATTER],
              [BATCHNO],
              [PREF],
              [DATE],
              [REF],
              [NARR],
              [VALUED],
              [VALUEO],
              [VALUEC],
              [FEE],
              [PER],
              [YEAR],
              [ENTRYDATE],
              [CLIENT],
              [VALUECC],
              [VALUECD],
              [DEPOSITTYPE],
              [CURVALUED],
              [CURVALUEO],
              [CURVALUEC],
              [CURVALUECC],
              [CURVALUECD],
              [BILLED],
              [BILLINGYEAR],
              [BILLINGPERIOD],
              [BILLINGDATE],
              [BILLEDOUTLAYVALUE],
              [InvoiceNo],
              [IncludeInBill])
       SELECT convert(char(11), @DETMATTER) AS [MATTER],
              @NewBatchNo As [BATCHNO],
              @LastBatchDPREF AS [PREF],
              BAH.[DATE] AS [DATE],
              convert(char(10), 'xCompTFer') AS [REF],
              convert(char(80), 'COMP: CREDIT Outlay Transfer from ' + BAH.[MATTER]) AS [NARR],
              convert(decimal(17, 2), 0) AS [VALUED],
              convert(decimal(17, 2), -@DETVALUE) AS [VALUEO],
              convert(decimal(17, 2), 0) AS [VALUEC],
              convert(char(3), '') AS FEE,
              BAH.[PERNO] AS [PER],
              BAH.[YEAR] AS [YEAR],
              BAH.[DATE] AS [ENTRYDATE],
              MAT.[CLIENTCODE] AS [CLIENT],
              convert(decimal(17, 2), 0) AS [VALUECC],
              convert(decimal(17, 2), 0) AS [VALUECD],
              convert(char(4), '') AS [DEPOSITTYPE],
              convert(decimal(17, 2), 0) AS [CURVALUED],
              convert(decimal(17, 2), round((-@DETVALUE) * @IECONVERT, 2)) AS [CURVALUEO],
              convert(decimal(17, 2), 0) AS [CURVALUED],
              convert(decimal(17, 2), 0) AS [CURVALUECC],
              convert(decimal(17, 2), 0) AS [CURVALUECD],
              convert(char(1), '') AS [BILLED],
              BAH.[YEAR] AS [BILLINGYEAR],
              BAH.[PERNO] AS [BILLINGPERIOD],
              BAH.[DATE] AS [BILLINGDATE],
              convert(decimal(17, 2), -@DETVALUE) AS [BILLEDOUTLAYVALUE],
              @INVOICENO AS [Invoiceno],
              convert(int, 2) AS [IncludeInBill]
         FROM [dbo].[BATCHH] BAH
              INNER JOIN [dbo].[MATTERS] MAT
                      ON MAT.[CODE] = @DETMATTER
        WHERE BAH.[PREF] = @LastBatchHPRef

       --UPDATE CON
       --   SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
       --       CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
       --  FROM [dbo].[control] CON

       INSERT
         INTO [dbo].[NominalLedger]
             ([CODE],
              [BRANCH],
              [BATCHNO],
              [PREF],
              [DATE],
              [REF],
              [NARR],
              [MATTER],
              [SUPP],
              [FEE],
              [VALUE],
              [CURRENCYVALUE],
              [PER],
              [YEAR],
              [ENTRYDATE],
              [RECNO])
       SELECT @OUTLAY AS [CODE],
              convert(varchar(3), '') AS [BRANCH],
              @NewBatchNo As [BATCHNO],
              @LastBatchDPREF AS [PREF],
              BAH.[DATE] AS [DATE],
              convert(char(10), 'xCompTFer') AS [REF],
              convert(char(100), 'COMP: CREDIT Outlay Transfer from ' + BAH.[MATTER]) AS [NARR],
              convert(char(11), @DETMATTER) AS [MATTER],
              convert(char(10), '') AS [SUPP],
              convert(char(3), '') AS FEE,
              convert(decimal(17, 2), -@DETVALUE) AS [VALUE],
              convert(decimal(17, 2), round((-@DETVALUE) * @IECONVERT, 2)) AS [CURRENCYVALUE],
              BAH.[PERNO] AS [PER],
              BAH.[YEAR] AS [YEAR],
              BAH.[DATE] AS [ENTRYDATE],
              convert(int, 0) AS [RECNO]
         FROM [dbo].[BATCHH] BAH
              INNER JOIN [dbo].[MATTERS] MAT
                      ON MAT.[CODE] = @DETMATTER
        WHERE BAH.[PREF] = @LastBatchHPRef

       UPDATE MAT
          SET MAT.[OutlayBal] = MAT.[OutlayBal] - @DETVALUE,
              MAT.[CurOutlayBal] = round((MAT.[OutlayBal] - @DETVALUE) * @IECONVERT, 2),
              MAT.[OutlayBalFwd] = MAT.[OutlayBalFwd] - @DETVALUE,
              MAT.[CurOutlayBalFwd] = round((MAT.[OutlayBalFwd] - @DETVALUE) * @IECONVERT, 2)
         FROM [dbo].[matters] MAT
        WHERE MAT.[CODE] = @DETMATTER

       SET @DETNo = @DETNo + 1
     END

   UPDATE CON
      SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
          CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1,
          @OUTLAY = CON.[OUTLAY],
          @OVAT = CON.[VATEXCLUDE],
          @BASECUR = CON.[BASECURRENCY],
          @IECONVERT = CON.[IECONVERT]
     FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[BatchDetails]
         ([BATCHNO],
          [TYPE],
          [CODE],
          [PREF],
          [REF],
          [DATE],
          [FEE],
          [BRANCH],
          [SUPP],
          [NARR],
          [MATTER],
          [VALUE],
          [VATCODE],
          [VATVAL],
          [CLIENTYN],
          [OUTLAY],
          [PENDING],
          [YEAR],
          [PERNO],
          [ENTRYCURRENCY],
          [CURRENCYVALUE],
          [CURRENCYVAT],
          [OUTLAYCODE],
          [THIRDPARTY],
          [PAYEE],
          [HEADPREF],
          [HEADBATCH],
          [ALLOCBATCH],
          [ALLOCPREF],
          [ALLOCREF],
          [ALLOCVALUE],
          [ALLOCWRITEOFF],
          [PSUPP],
          [UNDETAKING])
   SELECT @NewBatchNo As [BATCHNO],
          convert(char(1), 'J') AS [TYPE],
          @OUTLAY AS [CODE],
          @LastBatchDPREF AS [PREF],
          convert(char(10), 'xCompTFer') AS [REF],
          BAH.[DATE] AS [DATE],
          convert(char(3), '') AS FEE,
          convert(varchar(3), '') AS BRANCH,
          convert(char(10), '') AS [SUPP],
          convert(char(150), 'Composite Billing') AS [NARR],
          BAH.[MATTER] AS [MATTER],
          TOT.[BILLNOW] As [VALUE],
          @OVAT AS [VATCODE],
          convert(decimal(17,2), 0) As [VATVAL],
          convert(char(1), 'N') AS [CLIENTYN],
          convert(char(1), 'O') AS [OUTLAY],
          convert(char(1), '') AS [PENDING],
          BAH.[YEAR] AS [YEAR],
          BAH.[PERNO] AS [PERNO],
          @BASECUR AS [ENTRYCURRENCY],
          convert(decimal(17, 2), round((TOT.[BILLNOW]) * @IECONVERT, 2)) AS [CURRENCYVALUE],
          convert(decimal(17,2), 0) As [CURRENCYVAT],
          convert(char(4), '') AS [OUTLAYCODE],
          convert(char(1), '') AS [THIRDPARTY],
          convert(char(60), '') AS [PAYEE],
          convert(int, 0) AS [HEADPREF],
          convert(int, 0) AS [HEADBATCH],
          convert(int, 0) AS [ALLOCBATCH],
          convert(int, 0) AS [ALLOCPREF],
          convert(char(10), '') AS [ALLOCREF],
          convert(decimal(17, 2), 0) AS [ALLOCVALUE],
          convert(char(1), '') AS [ALLOCWRITEOFF],
          convert(char(10), '') AS [PSUPP],
          convert(smallint, 0) AS [UNDETAKING]
     FROM [dbo].[BATCHH] BAH
          CROSS JOIN(  SELECT -ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@CRBatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

   --UPDATE CON
   --   SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
   --       CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
   --  FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[MatterLedger]
         ([MATTER],
          [BATCHNO],
          [PREF],
          [DATE],
          [REF],
          [NARR],
          [VALUED],
          [VALUEO],
          [VALUEC],
          [FEE],
          [PER],
          [YEAR],
          [ENTRYDATE],
          [CLIENT],
          [VALUECC],
          [VALUECD],
          [DEPOSITTYPE],
          [CURVALUED],
          [CURVALUEO],
          [CURVALUEC],
          [CURVALUECC],
          [CURVALUECD],
          [BILLED],
          [BILLINGYEAR],
          [BILLINGPERIOD],
          [BILLINGDATE],
          [BILLEDOUTLAYVALUE],
          [InvoiceNo],
          [IncludeInBill])
   SELECT convert(char(11), BAH.[MATTER]) AS [MATTER],
          @NewBatchNo As [BATCHNO],
          @LastBatchDPREF AS [PREF],
          BAH.[DATE] AS [DATE],
          convert(char(10), 'xCompTFer') AS [REF],
          convert(char(80), 'Composite Billing') AS [NARR],
          convert(decimal(17, 2), 0) AS [VALUED],
          convert(decimal(17, 2), ISNULL(TOT.[BILLNOW], 0)) AS [VALUEO],
          convert(decimal(17, 2), 0) AS [VALUEC],
          convert(char(3), '') AS FEE,
          BAH.[PERNO] AS [PER],
          BAH.[YEAR] AS [YEAR],
          BAH.[DATE] AS [ENTRYDATE],
          MAT.[CLIENTCODE] AS [CLIENT],
          convert(decimal(17, 2), 0) AS [VALUECC],
          convert(decimal(17, 2), 0) AS [VALUECD],
          convert(char(4), '') AS [DEPOSITTYPE],
          convert(decimal(17, 2), 0) AS [CURVALUED],
          convert(decimal(17, 2), round((TOT.[BILLNOW]) * @IECONVERT, 2)) AS [CURVALUEO],
          convert(decimal(17, 2), 0) AS [CURVALUED],
          convert(decimal(17, 2), 0) AS [CURVALUECC],
          convert(decimal(17, 2), 0) AS [CURVALUECD],
          convert(char(1), '') AS [BILLED],
          BAH.[YEAR] AS [BILLINGYEAR],
          BAH.[PERNO] AS [BILLINGPERIOD],
          BAH.[DATE] AS [BILLINGDATE],
          convert(decimal(17, 2), TOT.[BILLNOW]) AS [BILLEDOUTLAYVALUE],
          @INVOICENO AS [Invoiceno],
          convert(int, 2) AS [IncludeInBill]
     FROM [dbo].[BATCHH] BAH
          INNER JOIN [dbo].[MATTERS] MAT
                  ON MAT.[CODE] = BAH.[MATTER]
          CROSS JOIN(  SELECT -ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@CRBatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

--   UPDATE CON
--      SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
--          CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
--     FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[NominalLedger]
         ([CODE],
          [BRANCH],
          [BATCHNO],
          [PREF],
          [DATE],
          [REF],
          [NARR],
          [MATTER],
          [SUPP],
          [FEE],
          [VALUE],
          [CURRENCYVALUE],
          [PER],
          [YEAR],
          [ENTRYDATE],
          [RECNO])
   SELECT @OUTLAY AS [CODE],
          convert(varchar(3), '') AS [BRANCH],
          @NewBatchNo As [BATCHNO],
          @LastBatchDPREF AS [PREF],
          BAH.[DATE] AS [DATE],
          convert(char(10), 'xCompTFer') AS [REF],
          convert(char(100), 'Composite Billing') AS [NARR],
          convert(char(11), BAH.[MATTER]) AS [MATTER],
          convert(char(10), '') AS [SUPP],
          convert(char(3), '') AS FEE,
          convert(decimal(17, 2), TOT.[BILLNOW]) AS [VALUE],
          convert(decimal(17, 2), round((TOT.[BILLNOW]) * @IECONVERT, 2)) AS [CURRENCYVALUE],
          BAH.[PERNO] AS [PER],
          BAH.[YEAR] AS [YEAR],
          BAH.[DATE] AS [ENTRYDATE],
          convert(int, 0) AS [RECNO]
     FROM [dbo].[BATCHH] BAH
          INNER JOIN [dbo].[MATTERS] MAT
                  ON MAT.[CODE] = BAH.MATTER
          CROSS JOIN(  SELECT -ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@CRBatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

   UPDATE MAT
      SET MAT.[OutlayBal] = MAT.[OutlayBal] + ISNULL(TOT.[BILLNOW], 0),
          MAT.[CurOutlayBal] = round((MAT.[OutlayBal] + TOT.[BILLNOW]) * @IECONVERT, 2),
          MAT.[OutlayBalFwd] = MAT.[OutlayBalFwd] + TOT.[BILLNOW],
          MAT.[CurOutlayBalFwd] = round((MAT.[OutlayBalFwd] + TOT.[BILLNOW]) * @IECONVERT, 2)
     FROM [dbo].[BATCHH] BAH
          INNER JOIN [dbo].[matters] MAT
                  ON MAT.[Code] = BAH.[MATTER]
          CROSS JOIN(  SELECT -ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@CRBatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMBillingGuideTransfer' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMBillingGuideTransfer] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMBillingGuideTransfer]
      (
		@BatchNo INT
	  )
AS
  /*******************************************************************************************************
  * Transfer Billing Guide                                                                               * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_SAMBillingGuideTransfer]  			            				 *
  * Copied From           : [dbo].[ky_BGTransfer]                                                        *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-11-25    Balamurugan C        Created                                                           *
  *******************************************************************************************************/
BEGIN

   DECLARE @NewBatchNo int
   DECLARE @LastBatchHPREF int
   DECLARE @LastBatchDPREF int
   DECLARE @OUTLAY char(10)
   DECLARE @OVAT char(1)
   DECLARE @BASECUR char(1)
   DECLARE @IECONVERT decimal(9, 6)

   DECLARE @DETVALUE decimal(17, 2)
   DECLARE @DETMATTER VARCHAR(20)
   DECLARE @DETNo int
   DECLARE @DETTotal int

   DECLARE @INVOICENO int

   DECLARE @DETs TABLE
          ([seqno]             int             identity(1, 1),
           [DETVALUE]          decimal(17, 2),
           [DETMATTER]         VARCHAR(20))

   SELECT @INVOICENO = CASE WHEN IsNumeric(BAH.[REF]) = 1
                            THEN convert(int, BAH.[REF])
                       ELSE 0 END
     FROM [dbo].[BATCHH] BAH
    WHERE BAH.[BATCHNO] = @BATCHNO

   UPDATE CON
      SET @NewBatchNo = IsNull(CON.[LASTBATCH], 0) + 1,
          CON.[LASTBATCH] = IsNull(CON.[LASTBATCH], 0) + 1,
          @LastBatchHPREF = IsNull(CON.[LASTPREF], 0) + 1,
          CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
     FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[BATCHH]
         ([BATCHNO],
          [POSTFWD],
          [TYPE],
          [CODE],
          [BRANCH],
          [PREF],
          [REF],
          [DATE],
          [FEE],
          [MATTER],
          [SUPP],
          [NARR],
          [VALUE],
          [SUBTOT],
          [POSTED],
          [CLIENTAC],
          [PERNO],
          [YEAR],
          [PAYEE],
          [OUTLAYTOT],
          [VATTOT],
          [FEETOT],
          [INVCR],
          [THIRDPARTY],
          [USERCODE],
          [HandlerCode],
          [ENTRYDATE],
          [CURRENCY],
          [CURRENCYVALUE],
          [CUROUTLAYTOT],
          [CURVATTOT],
          [CURFEETOT],
          [RECNO],
          [SINGLELINE],
          [TEMPLATE],
          [CHEQUEREQNO],
          [WRITEDOWN],
          [WRITEBACKHOURS],
          [WRITEBACKVALUE],
          [CORRECTCOPY])
   select @NewBatchNo As [BATCHNO],
          BAH.[POSTFWD] AS [POSTFWD],
          convert(char(1), 'J') AS [TYPE],
          convert(char(10), '') AS [CODE],
          convert(varchar(3), '') AS [BRANCH],
          @LastBatchHPREF AS [PREF],
          convert(char(10), 'xCompBill') AS [REF],
          BAH.[DATE] AS [DATE],
          BAH.[FEE] AS [FEE],
          BAH.[MATTER] AS [MATTER],
          convert(char(10), '') AS [SUPP],
          convert(char(150), 'Composite Bill Outlay Transfer') AS [NARR],
          convert(decimal(17,2), 0) As [VALUE],
          convert(decimal(17,2), 0) As [SUBTOT],
          convert(char(1), 'Y') AS [POSTED],
          convert(char(1), 'N') AS [CLIENTAC],
          BAH.[PERNO] AS [PERNO],
          BAH.[YEAR] AS [YEAR],
          convert(char(60), '') AS [PAYEE],
          convert(decimal(17,2), 0) AS [OUTLAYTOT],
          convert(decimal(17,2), 0) AS [VATTOT],
          convert(decimal(17,2), 0) AS [FEETOT],
          convert(char(1), 'I') AS [INVCR],
          convert(char(1), 'N') AS [THIRDPARTY],
          BAH.[USERCODE] AS [USERCODE],
          BAH.[HandlerCode] AS [HandlerCode],
          convert(datetime, convert(varchar, getDate(), 106)) AS [ENTRYDATE],
          BAH.[CURRENCY] AS [CURRENCY],
          convert(decimal(17,2), 0) AS [CURRENCYVALUE],
          convert(decimal(17,2), 0) AS [CUROUTLAYTOT],
          convert(decimal(17,2), 0) AS [CURVATTOT],
          convert(decimal(17,2), 0) AS [CURFEETOT],
          convert(int, 0) AS [RECNO],
          convert(char(1), '') AS [SINGLELINE],
          convert(char(10), '') AS [TEMPLATE],
          convert(int, 0) AS [CHEQUEREQNO],
          convert(datetime, NULL) AS [WRITEDOWN],
          convert(decimal(7,2), 0) AS [WRITEBACKHOURS],
          convert(decimal(13,2), 0) AS [WRITEBACKVALUE],
          convert(char(1), 0) AS [CORRECTCOPY]
     FROM [dbo].[BatchH] BAH
    WHERE [BATCHNO] = @BatchNo

     INSERT
       INTO @DETs
           ([DETMATTER],
            [DETVALUE])
     SELECT BGM.[MATTER],
            ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
       FROM [dbo].[ky_CompBillMatterByBatch](@BatchNo) BGM
            INNER JOIN [dbo].[BGDetail] BGD
                    ON BGD.[BGGroupID] = BGM.[ID]
                   AND BGD.[Matter] = BGM.[Matter]
   GROUP BY BGM.[Matter]

   SELECT @DETTotal = COUNT(1) FROM @DETs

   SET @DETNo = 1
   WHILE @DETNo <= @DETTotal
     BEGIN
       SET @DETMATTER = ''
       SET @DETVALUE = 0

       SELECT @DETMATTER = DET.[DETMATTER],
              @DETVALUE = ISNULL(DET.[DETVALUE], 0)
         FROM @DETs DET
        WHERE DET.[seqno] = @DETNo

       SET @DETVALUE = ISNULL(@DETVALUE, 0)

       UPDATE CON
          SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
              CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1,
              @OUTLAY = CON.[OUTLAY],
              @OVAT = CON.[VATEXCLUDE],
              @BASECUR = CON.[BASECURRENCY],
              @IECONVERT = CON.[IECONVERT]
         FROM [dbo].[control] CON

        INSERT
          INTO [dbo].[BatchDetails]
              ([BATCHNO],
               [TYPE],
               [CODE],
               [PREF],
               [REF],
               [DATE],
               [FEE],
               [BRANCH],
               [SUPP],
               [NARR],
               [MATTER],
               [VALUE],
               [VATCODE],
               [VATVAL],
               [CLIENTYN],
               [OUTLAY],
               [PENDING],
               [YEAR],
               [PERNO],
               [ENTRYCURRENCY],
               [CURRENCYVALUE],
               [CURRENCYVAT],
               [OUTLAYCODE],
               [THIRDPARTY],
               [PAYEE],
               [HEADPREF],
               [HEADBATCH],
               [ALLOCBATCH],
               [ALLOCPREF],
               [ALLOCREF],
               [ALLOCVALUE],
               [ALLOCWRITEOFF],
               [PSUPP],
               [UNDETAKING])
        SELECT @NewBatchNo As [BATCHNO],
               convert(char(1), 'J') AS [TYPE],
               @OUTLAY AS [CODE],
               @LastBatchDPREF AS [PREF],
               convert(char(10), 'xCompTFer') AS [REF],
               BAH.[DATE] AS [DATE],
               convert(char(3), '') AS FEE,
               convert(varchar(3), '') AS BRANCH,
               convert(char(10), '') AS [SUPP],
               convert(char(150), 'COMP: Outlay Transfer to ' + BAH.[MATTER]) AS [NARR],
               convert(char(11), @DETMATTER) AS [MATTER],
               -@DETVALUE As [VALUE],
               @OVAT AS [VATCODE],
               convert(decimal(17,2), 0) As [VATVAL],
               convert(char(1), 'N') AS [CLIENTYN],
               convert(char(1), 'O') AS [OUTLAY],
               convert(char(1), '') AS [PENDING],
               BAH.[YEAR] AS [YEAR],
               BAH.[PERNO] AS [PERNO],
               @BASECUR AS [ENTRYCURRENCY],
               convert(decimal(17, 2), round((-@DETVALUE) * @IECONVERT, 2)) AS [CURRENCYVALUE],
               convert(decimal(17,2), 0) As [CURRENCYVAT],
               convert(char(4), '') AS [OUTLAYCODE],
               convert(char(1), '') AS [THIRDPARTY],
               convert(char(60), '') AS [PAYEE],
               convert(int, 0) AS [HEADPREF],
               convert(int, 0) AS [HEADBATCH],
               convert(int, 0) AS [ALLOCBATCH],
               convert(int, 0) AS [ALLOCPREF],
               convert(char(10), '') AS [ALLOCREF],
               convert(decimal(17, 2), 0) AS [ALLOCVALUE],
               convert(char(1), '') AS [ALLOCWRITEOFF],
               convert(char(10), '') AS [PSUPP],
               convert(smallint, 0) AS [UNDETAKING]
          FROM [dbo].[BATCHH] BAH
         WHERE BAH.[PREF] = @LastBatchHPRef

        --UPDATE CON
        --   SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
        --       CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
        --  FROM [dbo].[control] CON

        INSERT
          INTO [dbo].[MatterLedger]
              ([MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BILLEDOUTLAYVALUE],
               [InvoiceNo],
               [IncludeInBill])
        SELECT convert(char(11), @DETMATTER) AS [MATTER],
               @NewBatchNo As [BATCHNO],
               @LastBatchDPREF AS [PREF],
               BAH.[DATE] AS [DATE],
               convert(char(10), 'xCompTFer') AS [REF],
               convert(char(80), 'COMP: Outlay Transfer to ' + BAH.[MATTER]) AS [NARR],
               convert(decimal(17, 2), 0) AS [VALUED],
               convert(decimal(17, 2), -@DETVALUE) AS [VALUEO],
               convert(decimal(17, 2), 0) AS [VALUEC],
               convert(char(3), '') AS FEE,
               BAH.[PERNO] AS [PER],
               BAH.[YEAR] AS [YEAR],
               BAH.[DATE] AS [ENTRYDATE],
               MAT.[CLIENTCODE] AS [CLIENT],
               convert(decimal(17, 2), 0) AS [VALUECC],
               convert(decimal(17, 2), 0) AS [VALUECD],
               convert(char(4), '') AS [DEPOSITTYPE],
               convert(decimal(17, 2), 0) AS [CURVALUED],
               convert(decimal(17, 2), round((-@DETVALUE) * @IECONVERT, 2)) AS [CURVALUEO],
               convert(decimal(17, 2), 0) AS [CURVALUED],
               convert(decimal(17, 2), 0) AS [CURVALUECC],
               convert(decimal(17, 2), 0) AS [CURVALUECD],
               convert(char(1), '') AS [BILLED],
               BAH.[YEAR] AS [BILLINGYEAR],
               BAH.[PERNO] AS [BILLINGPERIOD],
               BAH.[DATE] AS [BILLINGDATE],
               convert(decimal(17, 2), -@DETVALUE) AS [BILLEDOUTLAYVALUE],
               @INVOICENO AS [Invoiceno],
               convert(int, 2) AS [IncludeInBill]
          FROM [dbo].[BATCHH] BAH
               INNER JOIN [dbo].[MATTERS] MAT
                       ON MAT.[CODE] = @DETMATTER
         WHERE BAH.[PREF] = @LastBatchHPRef

        --UPDATE CON
        --   SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
        --       CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
        --  FROM [dbo].[control] CON

        INSERT
          INTO [dbo].[NominalLedger]
              ([CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO])
        SELECT @OUTLAY AS [CODE],
               convert(varchar(3), '') AS [BRANCH],
               @NewBatchNo As [BATCHNO],
               @LastBatchDPREF AS [PREF],
               BAH.[DATE] AS [DATE],
               convert(char(10), 'xCompTFer') AS [REF],
               convert(char(100), 'COMP: Outlay Transfer to ' + BAH.[MATTER]) AS [NARR],
               convert(char(11), @DETMATTER) AS [MATTER],
               convert(char(10), '') AS [SUPP],
               convert(char(3), '') AS FEE,
               convert(decimal(17, 2), -@DETVALUE) AS [VALUE],
               convert(decimal(17, 2), round((-@DETVALUE) * @IECONVERT, 2)) AS [CURRENCYVALUE],
               BAH.[PERNO] AS [PER],
               BAH.[YEAR] AS [YEAR],
               BAH.[DATE] AS [ENTRYDATE],
               convert(int, 0) AS [RECNO]
          FROM [dbo].[BATCHH] BAH
               INNER JOIN [dbo].[MATTERS] MAT
                       ON MAT.[CODE] = @DETMATTER
         WHERE BAH.[PREF] = @LastBatchHPRef

        UPDATE MAT
           SET MAT.[OutlayBal] = MAT.[OutlayBal] - @DETVALUE,
               MAT.[CurOutlayBal] = round((MAT.[OutlayBal] - @DETVALUE) * @IECONVERT, 2),
               MAT.[OutlayBalFwd] = MAT.[OutlayBalFwd] - @DETVALUE,
               MAT.[CurOutlayBalFwd] = round((MAT.[OutlayBalFwd] - @DETVALUE) * @IECONVERT, 2)
          FROM [dbo].[matters] MAT
         WHERE MAT.[CODE] = @DETMATTER

       SET @DETNo = @DETNo + 1
     END

   UPDATE CON
      SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
          CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1,
          @OUTLAY = CON.[OUTLAY],
          @OVAT = CON.[VATEXCLUDE],
          @BASECUR = CON.[BASECURRENCY],
          @IECONVERT = CON.[IECONVERT]
     FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[BatchDetails]
         ([BATCHNO],
          [TYPE],
          [CODE],
          [PREF],
          [REF],
          [DATE],
          [FEE],
          [BRANCH],
          [SUPP],
          [NARR],
          [MATTER],
          [VALUE],
          [VATCODE],
          [VATVAL],
          [CLIENTYN],
          [OUTLAY],
          [PENDING],
          [YEAR],
          [PERNO],
          [ENTRYCURRENCY],
          [CURRENCYVALUE],
          [CURRENCYVAT],
          [OUTLAYCODE],
          [THIRDPARTY],
          [PAYEE],
          [HEADPREF],
          [HEADBATCH],
          [ALLOCBATCH],
          [ALLOCPREF],
          [ALLOCREF],
          [ALLOCVALUE],
          [ALLOCWRITEOFF],
          [PSUPP],
          [UNDETAKING])
   SELECT @NewBatchNo As [BATCHNO],
          convert(char(1), 'J') AS [TYPE],
          @OUTLAY AS [CODE],
          @LastBatchDPREF AS [PREF],
          convert(char(10), 'xCompTFer') AS [REF],
          BAH.[DATE] AS [DATE],
          convert(char(3), '') AS FEE,
          convert(varchar(3), '') AS BRANCH,
          convert(char(10), '') AS [SUPP],
          convert(char(150), 'Composite Billing') AS [NARR],
          BAH.[MATTER] AS [MATTER],
          TOT.[BILLNOW] As [VALUE],
          @OVAT AS [VATCODE],
          convert(decimal(17,2), 0) As [VATVAL],
          convert(char(1), 'N') AS [CLIENTYN],
          convert(char(1), 'O') AS [OUTLAY],
          convert(char(1), '') AS [PENDING],
          BAH.[YEAR] AS [YEAR],
          BAH.[PERNO] AS [PERNO],
          @BASECUR AS [ENTRYCURRENCY],
          convert(decimal(17, 2), round((TOT.[BILLNOW]) * @IECONVERT, 2)) AS [CURRENCYVALUE],
          convert(decimal(17,2), 0) As [CURRENCYVAT],
          convert(char(4), '') AS [OUTLAYCODE],
          convert(char(1), '') AS [THIRDPARTY],
          convert(char(60), '') AS [PAYEE],
          convert(int, 0) AS [HEADPREF],
          convert(int, 0) AS [HEADBATCH],
          convert(int, 0) AS [ALLOCBATCH],
          convert(int, 0) AS [ALLOCPREF],
          convert(char(10), '') AS [ALLOCREF],
          convert(decimal(17, 2), 0) AS [ALLOCVALUE],
          convert(char(1), '') AS [ALLOCWRITEOFF],
          convert(char(10), '') AS [PSUPP],
          convert(smallint, 0) AS [UNDETAKING]
     FROM [dbo].[BATCHH] BAH
          CROSS JOIN(  SELECT ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@BatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

   --UPDATE CON
   --   SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
   --       CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
   --  FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[MatterLedger]
         ([MATTER],
          [BATCHNO],
          [PREF],
          [DATE],
          [REF],
          [NARR],
          [VALUED],
          [VALUEO],
          [VALUEC],
          [FEE],
          [PER],
          [YEAR],
          [ENTRYDATE],
          [CLIENT],
          [VALUECC],
          [VALUECD],
          [DEPOSITTYPE],
          [CURVALUED],
          [CURVALUEO],
          [CURVALUEC],
          [CURVALUECC],
          [CURVALUECD],
          [BILLED],
          [BILLINGYEAR],
          [BILLINGPERIOD],
          [BILLINGDATE],
          [BILLEDOUTLAYVALUE],
          [InvoiceNo],
          [IncludeInBill])
   SELECT convert(char(11), BAH.[MATTER]) AS [MATTER],
          @NewBatchNo As [BATCHNO],
          @LastBatchDPREF AS [PREF],
          BAH.[DATE] AS [DATE],
          convert(char(10), 'xCompTFer') AS [REF],
          convert(char(80), 'Composite Billing') AS [NARR],
          convert(decimal(17, 2), 0) AS [VALUED],
          convert(decimal(17, 2), TOT.[BILLNOW]) AS [VALUEO],
          convert(decimal(17, 2), 0) AS [VALUEC],
          convert(char(3), '') AS FEE,
          BAH.[PERNO] AS [PER],
          BAH.[YEAR] AS [YEAR],
          BAH.[DATE] AS [ENTRYDATE],
          MAT.[CLIENTCODE] AS [CLIENT],
          convert(decimal(17, 2), 0) AS [VALUECC],
          convert(decimal(17, 2), 0) AS [VALUECD],
          convert(char(4), '') AS [DEPOSITTYPE],
          convert(decimal(17, 2), 0) AS [CURVALUED],
          convert(decimal(17, 2), round((TOT.[BILLNOW]) * @IECONVERT, 2)) AS [CURVALUEO],
          convert(decimal(17, 2), 0) AS [CURVALUED],
          convert(decimal(17, 2), 0) AS [CURVALUECC],
          convert(decimal(17, 2), 0) AS [CURVALUECD],
          convert(char(1), '') AS [BILLED],
          BAH.[YEAR] AS [BILLINGYEAR],
          BAH.[PERNO] AS [BILLINGPERIOD],
          BAH.[DATE] AS [BILLINGDATE],
          convert(decimal(17, 2), TOT.[BILLNOW]) AS [BILLEDOUTLAYVALUE],
          @INVOICENO AS [Invoiceno],
          convert(int, 2) AS [IncludeInBill]
     FROM [dbo].[BATCHH] BAH
          INNER JOIN [dbo].[MATTERS] MAT
                  ON MAT.[CODE] = BAH.[MATTER]
          CROSS JOIN(  SELECT ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@BatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

--   UPDATE CON
--      SET @LastBatchDPREF = IsNull(CON.[LASTPREF], 0) + 1,
--          CON.[LASTPREF] = IsNull(CON.[LASTPREF], 0) + 1
--     FROM [dbo].[control] CON

   INSERT
     INTO [dbo].[NominalLedger]
         ([CODE],
          [BRANCH],
          [BATCHNO],
          [PREF],
          [DATE],
          [REF],
          [NARR],
          [MATTER],
          [SUPP],
          [FEE],
          [VALUE],
          [CURRENCYVALUE],
          [PER],
          [YEAR],
          [ENTRYDATE],
          [RECNO])
   SELECT @OUTLAY AS [CODE],
          convert(varchar(3), '') AS [BRANCH],
          @NewBatchNo As [BATCHNO],
          @LastBatchDPREF AS [PREF],
          BAH.[DATE] AS [DATE],
          convert(char(10), 'xCompTFer') AS [REF],
          convert(char(100), 'Composite Billing') AS [NARR],
          convert(char(11), BAH.[MATTER]) AS [MATTER],
          convert(char(10), '') AS [SUPP],
          convert(char(3), '') AS FEE,
          convert(decimal(17, 2), TOT.[BILLNOW]) AS [VALUE],
          convert(decimal(17, 2), round((TOT.[BILLNOW]) * @IECONVERT, 2)) AS [CURRENCYVALUE],
          BAH.[PERNO] AS [PER],
          BAH.[YEAR] AS [YEAR],
          BAH.[DATE] AS [ENTRYDATE],
          convert(int, 0) AS [RECNO]
     FROM [dbo].[BATCHH] BAH
          INNER JOIN [dbo].[MATTERS] MAT
                  ON MAT.[CODE] = BAH.MATTER
          CROSS JOIN(  SELECT ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@BatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

   UPDATE MAT
      SET MAT.[OutlayBal] = MAT.[OutlayBal] + ISNULL(TOT.[BILLNOW], 0),
          MAT.[CurOutlayBal] = round((MAT.[OutlayBal] + TOT.[BILLNOW]) * @IECONVERT, 2),
          MAT.[OutlayBalFwd] = MAT.[OutlayBalFwd] + TOT.[BILLNOW],
          MAT.[CurOutlayBalFwd] = round((MAT.[OutlayBalFwd] + TOT.[BILLNOW]) * @IECONVERT, 2)
     FROM [dbo].[BATCHH] BAH
          INNER JOIN [dbo].[matters] MAT
                  ON MAT.[Code] = BAH.[MATTER]
          CROSS JOIN(  SELECT ISNULL(SUM(ISNULL(BGD.[BillNow], 0)), 0) AS [BILLNOW]
                         FROM [dbo].[ky_CompBillMatterByBatch](@BatchNo) BGM
                              INNER JOIN [dbo].[BGDetail] BGD
                                      ON BGD.[BGGroupID] = BGM.[ID]
                                     AND BGD.[Matter] = BGM.[Matter]) TOT
    WHERE BAH.[PREF] = @LastBatchHPRef

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMClearDownNominalLedger' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMClearDownNominalLedger] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMClearDownNominalLedger] 
	  (
		   @BANKACC  VARCHAR(50),
		   @UPTODATE DATETIME,
		   @USER     VARCHAR(20)
	  )
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_SAMClearDownNominalLedger]                                                                    *
 *                                                                                                           *
 * Description: This procedure is used to get new transactions and put them into a bank rec in progress      *
 * Copied From: [dbo].[ky_NETClearDownNominalLedger]											             *
 *                                                                                                           *
 * Modification history:                                                                                     *
 * 2022-02-15   Balamurugan          Created                                                                 *
 * 2022-03-09   Balamurugan.C        Modified - Handled TCL Statements                                       * 
 *************************************************************************************************************/
BEGIN
  BEGIN TRY
   BEGIN TRAN    
	SET @BANKACC = LTRIM(RTRIM(@BANKACC))

	DECLARE @TRANS TABLE 
        (
			[Code]    VARCHAR(20),
			[BatchNo] INT
	    )

	INSERT INTO @TRANS (
		   [Code],
		   [BatchNo])
	SELECT [NML].[CODE],
		   [NML].[BATCHNO]
	  FROM [dbo].[NominalLedger] AS [NML]
	 WHERE [NML].[CODE] = @BANKACC
	   AND [NML].[DATE] <= @UPTODATE
	   AND [NML].[RECNO] = 0

	UPDATE [NML]
	   SET [NML].[RECNO] = 1
	  FROM [dbo].[NominalLedger] AS [NML]
		   INNER JOIN @TRANS AS [TMP]
				   ON [NML].[CODE] = [TMP].[Code]
				  AND [NML].[BATCHNO] = [TMP].[BatchNo]

	/* Update BatchH so you can't correct/copy it */
	UPDATE [BAH]
	   SET [BAH].[RECNO] = 1
	  FROM [dbo].[BatchH] AS [BAH]
		   INNER JOIN @TRANS AS [TMP]
				   ON [BAH].[BATCHNO] = [TMP].[BatchNo]

	INSERT INTO [dbo].[Log] (
		   [DATE],
		   [USER],
		   [EVENT])
	VALUES (DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
			@USER,
			'Clear Down: ' + @BANKACC + ' for date: ' + CONVERT(VARCHAR(10), @UPTODATE, 103))
   	       
		   COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_SamConvertDateToClarion]
			(@Date		 VARCHAR(20) = '',
			 @Result	 INT  OUTPUT) 
AS
/*******************************************************************************************************
* This SP is used to get the Clarion Number from Date												   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamConvertDateToClarion]										   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-18		Vinodhkumar.M           Created                                                    *
 *******************************************************************************************************/ 
BEGIN
		SELECT @Result = dbo.KAAS_FN_ConvertDateToClarion(@Date)
END

GO



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

GO

CREATE PROCEDURE [dbo].[KAAS_SamCostTransferGathering] 
	(
		 @REF 			   CHAR(10),
		 @DATE 			   DATETIME,
		 @MATTER 		   VARCHAR(20),
		 @VALUE 		   DECIMAL(17,2),
		 @ENTERCURRENCY	   CHAR(1)		  = '',
	     @CURRENCYVALUE    DECIMAL(17,2)  = 0.00,
		 @CURRENCYVAT	   DECIMAL(17,2)  = 0.00,
		 @HEADPREF		   INT			  = 0,
		 @HEADBATCH		   INT			  = 0,
		 @ALLOCBATCH 	   INT,
    	 @ALLOCPREF 	   INT,   
    	 @ALLOCREF 		   CHAR(10)       = '',
    	 @ALLOCVALUE 	   DECIMAL(17,2)  = 0.00,
    	 @ALLOCWRITEOFF    CHAR(1)        = ''
	)
AS
/*******************************************************************************************************
* Save the Cost Transfer Details                                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamCostTransferGathering]   			            	     	   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-19    Vinodhkumar M    Created									                           *
* 2022-02-25    Balamurugan.C    Modified - Handled TCL Statements                                     *
*******************************************************************************************************/
BEGIN
  SET NOCOUNT ON 
   BEGIN TRY
     BEGIN TRAN

	   INSERT INTO 
			[dbo].[CostTransGathering](
			  [REF],
			  [DATE],			
			  [MATTER],
			  [VALUE],
			  [ENTRYCURRENCY],
			  [CURRENCYVALUE],
			  [CURRENCYVAT], 
			  [HEADBATCH],
			  [HEADPREF],
			  [ALLOCBATCH],
			  [ALLOCPREF],
			  [ALLOCREF],
			  [ALLOCVALUE],
			  [ALLOCWRITEOFF]) 
	  VALUES
			 (@REF,
			  @DATE,
			  @MATTER,
			  @VALUE,
			  @ENTERCURRENCY,
			  @CURRENCYVALUE,
			  @CURRENCYVAT, 
			  @HEADBATCH,
			  @HEADPREF,
			  @ALLOCBATCH,
			  @ALLOCPREF,
			  @ALLOCREF,
			  @ALLOCVALUE,
			  @ALLOCWRITEOFF)
     COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END   
	 END CATCH
 SET NOCOUNT OFF
END

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SamCreateMemoriseBatch' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SamCreateMemoriseBatch] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SamCreateMemoriseBatch]
	   (
			@BATCHNO			INT,
			@DATE				DATE  = NULL,
			@TYPE				CHAR(1),
			@Handler            VARCHAR(30) = '',
			@Result	            TINYINT OUTPUT
	   )
AS
/*******************************************************************************************************
* Create Batch	for memorise transaction	                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamCreateMemoriseBatch]        	     				           *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-02    vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRAN
				 SET NOCOUNT ON 
	  SET @DATE  = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@DATE, @Handler)), 0)

	  IF(1 = (SELECT COUNT(1) FROM dbo.[RBatchH] WHERE [BatchNo] = @BATCHNO AND [DATE]=@DATE))
		BEGIN
			SET @Result = 0
		END

      ELSE 
		BEGIN
		         INSERT 
				   INTO [dbo].[RBatchH] 
				   (
						[BATCHNO],
						[TYPE],
						[CODE],
						[PREF],
						[DATE],
						[FEE],
						[MATTER],
						[SUPP],
						[NARR],
						[VALUE],
						[SUBTOT],
						[POSTED],
						[CLIENTAC],
						[PERNO],
						[YEAR],
						[PAYEE],
						[OUTLAYTOT],
						[VATTOT],
						[FEETOT],
						[INVCR],
						[THIRDPARTY],
						[USERCODE],
						[ENTRYDATE],
						[CLIENTBANK],
						[CURRENCY],
						[CURRENCYVALUE],
						[CUROUTLAYTOT],
						[CURVATTOT],
						[CURFEETOT],
						[RECNO],
						[SINGLELINE],
						[TEMPLATE],
						[CHEQUEREQNO],
						[WRITEDOWN],
						[WRITEBACKHOURS],
						[WRITEBACKVALUE],
						[CORRECTCOPY],
						[CREDITINVOICENO],
						[DRAFTBILLNO],
						[EFTSENT],
						[EFTDATE],
						[EFTFILENUMBER],
						[EFTFILENAME],
						[EFTYORN],
						[CLIENTCODE],
						[PAYCLIENT],
						[ONCEOFFPAYMENT],
						[CASEASSCODE]
					) 
				SELECT 	[BATCHNO],
						@TYPE,
						[CODE],
						[PREF],
						@DATE,
						[FEE],
						[MATTER],
						[SUPP],
						[NARR],
						[VALUE],
						[SUBTOT],
						[POSTED],
						[CLIENTAC],
						[PERNO],
						[YEAR],
						[PAYEE],
						[OUTLAYTOT],
						[VATTOT],
						[FEETOT],
						[INVCR],
						[THIRDPARTY],
						[USERCODE],
						[ENTRYDATE],
						[CLIENTBANK],
						[CURRENCY],
						[CURRENCYVALUE],
						[CUROUTLAYTOT],
						[CURVATTOT],
						[CURFEETOT],
						[RECNO],
						[SINGLELINE],
						[TEMPLATE],
						[CHEQUEREQNO],
						[WRITEDOWN],
						[WRITEBACKHOURS],
						[WRITEBACKVALUE],
						[CORRECTCOPY],
						[CREDITINVOICENO],
						[DRAFTBILLNO],
						[EFTSENT],
						[EFTDATE],
						[EFTFILENUMBER],
						[EFTFILENAME],
						[EFTYORN],
						[CLIENTCODE],
						[PAYCLIENT],
						[ONCEOFFPAYMENT],
						[CASEASSCODE]
				FROM    [dbo].[BatchH] 
				WHERE   BATCHNO=@BATCHNO
				
				INSERT INTO 
					[dbo].[RBatchD] (
					  [BATCHNO],
					  [TYPE],
					  [CODE],
					  [PREF],
					  [DATE],			
					  [NARR],
					  [MATTER],
					  [VALUE],
					  [VATCODE],
					  [VATVAL],
					  [OUTLAY],
					  [YEAR],
					  [PERNO],
					  [ENTRYCURRENCY],
					  [CURRENCYVALUE],
					  [CURRENCYVAT], 
					  [ALLOCREF],
					  [ALLOCVALUE],
					  [ALLOCBATCH],
					  [ALLOCPREF],
					  [ALLOCWRITEOFF],			 
					  [CASEASSCODE],
					  [ONCEOFFPAYMENT],
					  [PAYCLIENT],
					  [CLIENTCODE],
					  [SUPP],
					  [OUTLAYCODE],
					  [FEE],
					  [PAYEE],
					  [THIRDPARTY])
	 
			SELECT	  [BATCHNO],
					  @Type,
					  [CODE],
					  [PREF],
					  @DATE,
					  [NARR],
					  [MATTER],
					  [VALUE],
					  [VATCODE],
					  [VATVAL],
					  [OUTLAY],
					  [YEAR],
					  [PERNO],
					  [ENTRYCURRENCY],
					  [CURRENCYVALUE],
					  [CURRENCYVAT], 
					  [ALLOCREF],
					  [ALLOCVALUE],
					  [ALLOCBATCH],
					  [ALLOCPREF],
					  [ALLOCWRITEOFF],			 
					  [CASEASSCODE],
					  [ONCEOFFPAYMENT],
					  [PAYCLIENT],
					  [CLIENTCODE],
					  [SUPP],
					  [OUTLAYCODE],
					  [FEE],
					  [PAYEE],
					  [THIRDPARTY]
			FROM [DBO].[BatchDetails]
			WHERE BATCHNO=@BATCHNO

			SET @Result = 1
		END
				 SET NOCOUNT OFF
		COMMIT TRAN
	END TRY

	BEGIN CATCH
	       SET @Result = 0;
	   DECLARE @ErrorMsg      NVARCHAR(4000), 
			   @ErrorSeverity INT,
			   @ErrorState    INT; 

		SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
			   @ErrorSeverity = ERROR_SEVERITY(), 
			   @ErrorState    = ERROR_STATE()

	RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END 
	END CATCH

END

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMDashboardAccountDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMDashboardAccountDetails] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMDashboardAccountDetails]
AS
  /*******************************************************************************************************
  * Dashboard Details                                                                                    * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[SAMDashboardAccountDetails]   			            				 *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-12-20    Balamurugan C        Created                                                           *
  * 2021-12-27    Balamurugan C        Modified - Added Select condition to check log is inserted or not *
  *******************************************************************************************************/
BEGIN
DECLARE @tempTable TABLE
		(
		    [Id]			INT           NULL,
			[ColumnName]	VARCHAR(30)	  NULL,
			[Client A/c]	DECIMAL(17,2) NULL,
			[Outlay A/c]	DECIMAL(17,2) NULL,
			[Billing A/c]   DECIMAL(17,2) NULL,
			[Supplier A/c]	DECIMAL(17,2) NULL
		)
DECLARE @FinalTable TABLE
		(
			[RowNum]			INT           NULL,
			[ColumnName]		VARCHAR(30)	  NULL,
			[MatterBalances]	DECIMAL(17,2) NULL,
			[ControlAccounts]	DECIMAL(17,2) NULL,
			[Difference]		DECIMAL(17,2) NULL
		)
INSERT INTO @tempTable (
			[Id],
			[ColumnName],
			[Client A/c],	
			[Outlay A/c],	
			[Billing A/c],
			[Supplier A/c]
)

SELECT [Id],
	   [ColumnName],
	   [Client A/c],
	   [Outlay A/c],
	   [Billing A/c],
	   [Supplier A/c]
			FROM (
SELECT 1									AS 'Id',
	   'Matter Balances'					AS 'ColumnName',
	   SUM(ClientBal)						AS 'Client A/c',
	   SUM(OutlayBal)						AS 'Outlay A/c',
	   SUM(DebtBal)							AS 'Billing A/c',
	   (SELECT SUM(SupplierLedger.ORIGINAL) 
			AS Creditors 
	      FROM [dbo].[SupplierLedger] )		AS 'Supplier A/c' 
  FROM [dbo].[Matters]
UNION ALL
SELECT 2 AS Id,
	  'Control Accounts' AS 'ColumnName',
	  t1.ClientControlAc,
	  t2.OutlayControlAc,
	  t3.DebtorsControlAc,
	  t4.CreditorsControlAc 
 FROM (
	SELECT SUM(ISNULL(VALUE,0)) AS ClientControlAc 
	 FROM [dbo].[NominalLedger] 
	WHERE [CODE]=(SELECT [CNT].[CLIENT] 
	                FROM [dbo].[Control] [CNT]) 
					 AND YEAR=(SELECT [CNT].[YEAR] 
					FROM [dbo].[Control] [CNT])) AS t1,
	 (
	 SELECT ISNULL(SUM(ISNULL(VALUE,0)),0) AS OutlayControlAc  
	  FROM [dbo].[NominalLedger] 
	  WHERE[CODE]=(SELECT [CNT].[OUTLAY] 
	                 FROM [dbo].[Control] [CNT]) 
					  AND YEAR=(SELECT [CNT].[YEAR] 
								FROM [dbo].[Control] [CNT])) AS t2,
	(
	SELECT ISNULL(SUM(ISNULL(VALUE,0)),0) AS DebtorsControlAc 
	FROM [dbo].[NominalLedger]
	WHERE CODE=(SELECT [CNT].[DEBTORS] FROM [dbo].[Control] [CNT]) 
	            AND YEAR=(SELECT [CNT].[YEAR] 
				          FROM [dbo].[Control] [CNT])) AS t3,
	(SELECT ISNULL(SUM(ISNULL(VALUE,0)),0) AS CreditorsControlAc 
	   FROM [dbo].[NominalLedger] 
	  WHERE [CODE]=(SELECT [CNT].[CREDITOR] 
	                  FROM [dbo].[Control] [CNT]) 
					   AND YEAR=(SELECT [CNT].[YEAR] 
					               FROM [dbo].[Control] [CNT])) AS t4

	) AS balances

	INSERT INTO @FinalTable
			(
			    [ColumnName],
			    [MatterBalances],
			    [ControlAccounts],
			    [Difference]	
			)

		 SELECT PIV.NAME					AS [ColumnName],
				MAX(PIV.[Matter Balances])  AS [MatterBalances],
				MAX(PIV.[Control Accounts]) AS [ControlAccounts],
				MAX(0)						AS [Difference]
		   FROM @tempTable
		UNPIVOT (VALUE FOR NAME IN ([Client A/c],[Outlay A/c],[Billing A/c],[Supplier A/c])) up
		  PIVOT (MAX(VALUE) FOR [ColumnName] IN ([Matter Balances],[Control Accounts])) PIV
	   GROUP BY PIV.NAME

		SELECT [ColumnName],
			   ISNULL([MatterBalances],0)		AS [MatterBalances],
			   ISNULL([ControlAccounts],0)		AS [ControlAccounts],
			   ISNULL([MatterBalances] - [ControlAccounts],0) AS [Difference]
		  FROM @FinalTable
	  ORDER BY CASE [ColumnName]
			   WHEN 'Client A/c'  THEN 1
			   WHEN 'Outlay A/c'  THEN 2
			   WHEN 'Billing A/c' THEN 3
			   ELSE  4 END 

/* CLIENT BANK ACCOUNTS */
		SELECT [NOM].[CODE]	AS [Code],
			   [NOM].[DESC] AS [BankAc],
			   ISNULL(SUM(ISNULL([NOL].[VALUE],0)),0) AS Balance
	      FROM [dbo].[NominalLedger] [NOL] 
	INNER JOIN [dbo].[Nominal] [NOM] 
	        ON [NOL].[CODE] = [NOM].[CODE]
         WHERE ([NOM].[TYPE] = 'Bank') 
		   AND ([NOM].[CLIENTAC] = 'Y') 
		   AND YEAR=(SELECT [CNT].[YEAR] FROM [dbo].[Control] [CNT])
	   GROUP BY [NOM].[CODE],
	            [NOM].[DESC]

/* OFFICE BANK ACCOUNTS */
		SELECT [NOM].[CODE]	AS [Code],
			   [NOM].[DESC] AS [BankAc],
			   ISNULL(SUM(ISNULL([NOL].[VALUE],0)),0) AS Balance
	      FROM [dbo].[NominalLedger] [NOL] 
	INNER JOIN [dbo].[Nominal] [NOM] 
	        ON [NOL].[CODE] = [NOM].[CODE]
         WHERE ([NOM].[TYPE] = 'Bank') 
		   AND ([NOM].[CLIENTAC] <> 'Y') 
		   AND YEAR=(SELECT [CNT].[YEAR] FROM [dbo].[Control] [CNT])
	   GROUP BY [NOM].[CODE],
	            [NOM].[DESC]

/* NOMINAL CONTROL TOTAL */
		SELECT SUM([Value]) AS NominalControlTotal 
		  FROM [dbo].[NominalLedger] 
		 WHERE YEAR=(SELECT [CNT].[YEAR] 
		  FROM [dbo].[Control] [CNT])

/* TO CHECK LOG IS INSERTED OR NOT*/
		SELECT CASE WHEN COUNT(*) > 0 
		       THEN 'N' ELSE 'Y' 
			   END AS [InsertDailyLog]
		  FROM [dbo].[ControlAccountLog]
			   WHERE CAST([EntryDate] AS DATE) = CAST(dbo.KEYHM_FNConvertDateToUTC(GETDATE(), '') AS DATE)

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


CREATE PROCEDURE
       [dbo].[KAAS_SAMDashboardDebitClientAcc]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'ClientCode',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 * Stored Procedure Name : [dbo].[KAAS_SAMDashboardDebitClientAcc]   			    *  
 * Copied From           : [dbo].[KAAS_GetSAMDashboardDetails]
 * Modification History:  															*
 * 2021-06-29   Ghayathri S.V	Created to Fetch the Debit Client Records           * 
 ************************************************************************************/
BEGIN

DECLARE		   @sql        NVARCHAR(max)
DECLARE	    @search		   NVARCHAR(500) = ''
DECLARE		@offset		   INT = @PageSize * (@PageNumber -1)




SET			@sql =		'WITH [ClientDebitAccounts] ([Code], [ClientBalance]) AS (
						SELECT [MAT].[Code], ISNULL(SUM([MTL].[VALUEC]), 0) AS [ClientBalance]
						FROM [dbo].[matters] AS [MAT]
						INNER JOIN [dbo].[MatterLedger] AS [MTL]
						ON [MTL].[MATTER] = [MAT].[Code]
						GROUP BY [MAT].[Code]
						HAVING ISNULL(SUM([MTL].[VALUEC]), 0) > 0)
						SELECT    COALESCE([CNT].[Name], [MAT].[ClientCode], '''') AS [Client],
								   ISNULL([MAT].[ClientCode], '''') AS [ClientCode],
								   [CDA].[Code] AS [Matter],
								   ISNULL([MAT].[Description], '''') AS [MatterDescription],
								   [CDA].[ClientBalance]
								   FROM [ClientDebitAccounts] AS [CDA]
								   LEFT OUTER JOIN [dbo].[matters] AS [MAT]
								   ON [MAT].[Code] = [CDA].[Code]
								   LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
								   ON [CNT].[COde] = [MAT].[ClientCode]
								   WHERE  ( 
											[CNT].[Name]		LIKE' + '''%' + @SearchString + '%' + '''' +
											'OR
											[MAT].[ClientCode]	LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[CDA].[Code]		LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[MAT].[Description] LIKE ' + '''%' + @SearchString + '%' + '''' +'

										  )
					 ORDER BY ' +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET ' +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT ' +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';


EXEC Sp_executesql @sql

				;WITH [ClientDebitAccounts] ([Code], [ClientBalance]) AS (
				SELECT [MAT].[Code], ISNULL(SUM([MTL].[VALUEC]), 0) AS [ClientBalance]
				FROM [dbo].[matters] AS [MAT]
				INNER JOIN [dbo].[MatterLedger] AS [MTL]
                ON [MTL].[MATTER] = [MAT].[Code]
				GROUP BY [MAT].[Code]
				HAVING ISNULL(SUM([MTL].[VALUEC]), 0) > 0)
				SELECT      COUNT(*)  'TotalRecord'
				FROM [ClientDebitAccounts] AS [CDA]
				LEFT OUTER JOIN [dbo].[matters] AS [MAT]
				ON [MAT].[Code] = [CDA].[Code]
				LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
				ON [CNT].[COde] = [MAT].[ClientCode]
				WHERE		( 
								[CNT].[Name] LIKE '%' + @SearchString + '%' 
								OR
								[MAT].[ClientCode] LIKE '%' + @SearchString + '%' 
								OR
								[CDA].[Code] LIKE '%' + @SearchString + '%' 
								OR
								[MAT].[Description] LIKE '%' + @SearchString + '%'
							)
END

GO


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


CREATE PROCEDURE
       [dbo].[KAAS_SAMDashboardOfficeCreditAcc]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'ClientCode',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 * Stored Procedure Name : [dbo].[KAAS_SAMDashboardOfficeCreditAcc]   			    *  
 * Copied From           : [dbo].[KAAS_GetSAMDashboardDetails]
 * Modification History:  															*
 * 2024-02-07   Ghayathri S.V	Created to Fetch the Office Credit Records          * 
 ************************************************************************************/
BEGIN

DECLARE		   @sql        NVARCHAR(max)
DECLARE	    @search		   NVARCHAR(500) = ''
DECLARE		@offset		   INT = @PageSize * (@PageNumber -1)




SET			@sql =		'WITH [OfficeCreditAccounts] ([Code], [OfficeBalance]) AS (
						SELECT [MAT].[Code],
						ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) AS [OfficeBalance]
						FROM [dbo].[matters] AS [MAT]
						INNER JOIN [dbo].[MatterLedger] AS [MTL]
						ON [MAT].[Code] = [MTL].[MATTER]
						GROUP BY [MAT].[Code]
						HAVING ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) < 0)

						SELECT COALESCE([CNT].[Name], [MAT].[ClientCode], '''') AS [Client],
						ISNULL([MAT].[ClientCode], '''') AS [ClientCode],
						[OCA].[Code] AS [Matter],
						ISNULL([MAT].[Description], '''') AS [MatterDescription],
						[OCA].[OfficeBalance]
						FROM [OfficeCreditAccounts] AS [OCA]
						LEFT OUTER JOIN [dbo].[matters] AS [MAT]
						ON [MAT].[Code] = [OCA].[Code]
						LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
						ON [CNT].[COde] = [MAT].[ClientCode]
						WHERE  ( 
									[CNT].[Name]		LIKE' + '''%' + @SearchString + '%' + '''' +
									'OR
									[MAT].[ClientCode]	LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[OCA].[Code]		LIKE ' + '''%' + @SearchString + '%' + '''' +
									'OR
									[MAT].[Description] LIKE ' + '''%' + @SearchString + '%' + '''' +'

							   )
					 ORDER BY ' +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET ' +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT ' +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';


EXEC Sp_executesql @sql

				;WITH [OfficeCreditAccounts] ([Code], [OfficeBalance]) AS (
				SELECT [MAT].[Code],
				ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) AS [OfficeBalance]
				FROM [dbo].[matters] AS [MAT]
				INNER JOIN [dbo].[MatterLedger] AS [MTL]
				ON [MAT].[Code] = [MTL].[MATTER]
				GROUP BY [MAT].[Code]
				HAVING ISNULL(SUM(ISNULL([MTL].[VALUED], 0) + ISNULL([MTL].[VALUEO], 0)), 0) < 0)

				SELECT      COUNT(*)  'TotalRecord'
				FROM [OfficeCreditAccounts] AS [OCA]
				LEFT OUTER JOIN [dbo].[matters] AS [MAT]
                ON [MAT].[Code] = [OCA].[Code]
				LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
                ON [CNT].[COde] = [MAT].[ClientCode]
				WHERE	( 
							[CNT].[Name] LIKE '%' + @SearchString + '%' 
							OR
							[MAT].[ClientCode] LIKE '%' + @SearchString + '%' 
							OR
							[OCA].[Code] LIKE '%' + @SearchString + '%' 
							OR
							[MAT].[Description] LIKE '%' + @SearchString + '%'
						)
END

GO


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


CREATE PROCEDURE
       [dbo].[KAAS_SAMDashboardOutstandingDebt]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Date',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 * Stored Procedure Name : [dbo].[KAAS_SAMDashboardOutstandingDebt]   			    *
 * Copied From           : [dbo].[KAAS_GetSAMDashboardDetails]
 * Modification History:  															*
 * 2024-02-06   Ghayathri S.V	Created to Fetch the Oustanding Debtors             *
 * 2024-02-12  Ghayathri S.V	Modified to fetch the matter description            *
 * 2024-02-14  Ghayathri S.V	Modified to fetch the Client Contact Name           *
 ************************************************************************************/
BEGIN

DECLARE		   @sql        NVARCHAR(max)
DECLARE	    @search		   NVARCHAR(500) = ''
DECLARE		@offset		   INT = @PageSize * (@PageNumber -1)




SET			@sql =		'SELECT     ISNULL([DTL].[MATTER], '''')  AS [Matter],
									ISNULL([MAT].[DESCRIPTION], '''')  AS [MatterName],
									ISNULL([CT].[NAME], '''')  AS [Name],
									[DTL].[DATE] AS [Date],
									ISNULL([DTL].[REF], '''')     AS [Ref],
									ISNULL([DTL].[NARR], '''')    AS [Narr], 
									ISNULL([DTL].[ORIGINAL], 0) AS [Amount],
									ISNULL([DTL].[OSVALUE], 0)  AS [AmountOS],
									ISNULL([DTL].[BATCHNO], 0)  AS [BatchNo],
									ISNULL([DTL].[PREF], 0)     AS [PRef]
									FROM [dbo].[DebtorsLedger] AS [DTL]
									JOIN [dbo].[Matters] MAT ON MAT.CODE = DTL.MATTER
									JOIN [dbo].[Contacts] CT ON MAT.CLIENTCODE = CT.CODE
									WHERE [DTL].[OSVALUE] <> 0 '  +  
									'AND ( 
											DTL.[Matter] LIKE' + '''%' + @SearchString + '%' + '''' +
											'OR
											DTL.[REF] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											DTL.[NARR] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											DTL.[BATCHNO] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											DTL.[PREF] LIKE ' + '''%' + @SearchString + '%' + '''' +'

										  )
					 ORDER BY ' +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET ' +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT ' +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

EXEC Sp_executesql @sql

						SELECT      COUNT(*)  'TotalRecord'
						  FROM      [dbo].[DebtorsLedger] AS [DTL]
						 WHERE 	    [DTL].[OSVALUE] <> 0 
						AND			( 
										DTL.[Matter] LIKE '%' + @SearchString + '%' 
										OR
										DTL.[REF] LIKE '%' + @SearchString + '%' 
										OR
										DTL.[NARR] LIKE '%' + @SearchString + '%' 
										OR
										DTL.[BATCHNO] LIKE '%' + @SearchString + '%'
										OR
										DTL.[PREF] LIKE '%' + @SearchString + '%'
									)
END

GO


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


CREATE PROCEDURE
       [dbo].[KAAS_SAMDashboardUnallocatedPayments]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Date',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 * Stored Procedure Name : [dbo].[KAAS_SAMDashboardUnallocatedPayments]   			*
 * Copied From           : [dbo].[KAAS_GetSAMDashboardDetails]
 * Modification History:  															*
 * 2024-02-06   Ghayathri S.V	Created to Fetch the Unallocated Payment Grid       *
* 2024-02-16   Ghayathri S.V	Modified to fetch type      						*
 ************************************************************************************/
BEGIN

DECLARE		   @sql        NVARCHAR(max)
DECLARE	    @search		   NVARCHAR(500) = ''
DECLARE		@offset		   INT = @PageSize * (@PageNumber -1)




SET			@sql =		'SELECT     COALESCE([SUP].[NAME], [SPL].[SUPP], '''') AS [Supp],
									[SPL].[DATE] AS [Date],
									[SPL].[TYPE] AS [Type],
									ISNULL([SPL].[REF], '''')		AS [Ref],
									ISNULL([SPL].[NARR], '''')		AS [Narr], 
									ISNULL([SPL].[ORIGINAL], 0)		AS [Original],
									ISNULL([SPL].[OSVALUE], 0)		AS [OSValue],
									ISNULL([SPL].[SUPP], '''')		AS [SupplierCode],
									ISNULL([SPL].[BATCHNO], 0)		AS [BatchNo],
									ISNULL([SPL].[PREF], 0)			AS [PRef]
									FROM [dbo].[SupplierLedger]		AS [SPL]
									LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
									ON [SPL].[SUPP] = [SUP].[CODE]
									WHERE [SPL].[TYPE] = ''P''
									AND [SPL].[OSVALUE] <> 0' +  
									'AND ( 
											[SUP].[NAME] LIKE' + '''%' + @SearchString + '%' + '''' +
											'OR
											[SPL].[REF] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[SPL].[NARR] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[SPL].[SUPP] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[SPL].[BATCHNO] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[SPL].[PREF] LIKE ' + '''%' + @SearchString + '%' + '''' +'

										  )
					 ORDER BY ' +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET ' +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT ' +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

EXEC Sp_executesql @sql

						SELECT      COUNT(*)  'TotalRecord'
						FROM [dbo].[SupplierLedger]		AS [SPL]
						LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
						ON [SPL].[SUPP] = [SUP].[CODE]
						WHERE [SPL].[TYPE] = 'P'
						AND [SPL].[OSVALUE] <> 0
						AND			( 
										[SUP].[NAME] LIKE '%' + @SearchString + '%' 
										OR
										[SPL].[REF] LIKE '%' + @SearchString + '%' 
										OR
										[SPL].[NARR] LIKE '%' + @SearchString + '%' 
										OR
										[SPL].[SUPP] LIKE '%' + @SearchString + '%'
										OR
										[SPL].[BATCHNO] LIKE '%' + @SearchString + '%'
										OR
										[SPL].[PREF] LIKE '%' + @SearchString + '%'
									)
END

GO


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


CREATE PROCEDURE
       [dbo].[KAAS_SAMDashboardUnallocatedReceipts]
	    ( 
			@PageNumber    INT,
			@PageSize	   INT,
			@SearchString  VARCHAR(500) = '',
			@SortColumn	   VARCHAR(100) = 'Date',
			@SortOrder     VARCHAR(100) = 'ASC'
		 )
AS
/************************************************************************************
 * Fetching Closed Matter Details													*
 * Stored Procedure Name : [dbo].[KAAS_SAMDashboardUnallocatedReceipts]   			*
 * Copied From           : [dbo].[KAAS_GetSAMDashboardDetails]
 * Modification History:  															*
 * 2024-02-07   Ghayathri S.V	Created to Fetch the Unallocated Receipts Grid      *
 * 2024-02-16   Ghayathri S.V	Modified to fetch matter code      					*
 ************************************************************************************/
BEGIN

DECLARE		   @sql        NVARCHAR(max)
DECLARE	    @search		   NVARCHAR(500) = ''
DECLARE		@offset		   INT = @PageSize * (@PageNumber -1)




SET			@sql =		'SELECT     COALESCE([CNT].[Name], [MAT].[ClientCode], '''') AS [Client],
									ISNULL([MAT].[Code], '''') AS [Matter],
									ISNULL([MAT].[DESCRIPTION], '''')  AS [MatterName],
									[DTL].[DATE] AS [Date],
									[DTL].[TYPE] AS [Type],
									ISNULL([DTL].[REF], '''') AS [Ref],
									ISNULL([DTL].[BATCHNO], 0) AS [BatchNo],
									ISNULL([DTL].[PREF], 0) AS [PRef],
									ISNULL([DTL].[NARR], '''') AS [Narr],
									ISNULL([DTL].[ORIGINAL], 0) AS [Original],
									ISNULL([DTL].[OSVALUE], 0) AS [OSValue]
									FROM [dbo].[DebtorsLedger] AS [DTL]
									LEFT OUTER JOIN [dbo].[matters] AS [MAT]
									ON [MAT].[Code] = [DTL].[MATTER]
									LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
									ON [CNT].[Code] = [MAT].[ClientCode]
									WHERE [DTL].[TYPE] = ''R''
									AND [DTL].[OSVALUE] <> 0' +  
								    'AND ( 
											[CNT].[Name] LIKE' + '''%' + @SearchString + '%' + '''' +
											'OR
											[MAT].[Code] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[DTL].[REF] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[DTL].[BATCHNO] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[DTL].[PREF] LIKE ' + '''%' + @SearchString + '%' + '''' +
											'OR
											[DTL].[NARR] LIKE ' + '''%' + @SearchString + '%' + '''' +'

										  )
					 ORDER BY ' +    @SortColumn + ' '  + @SortOrder + ' ' +
	                  'OFFSET ' +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT ' +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

EXEC Sp_executesql @sql

						SELECT      COUNT(*)  'TotalRecord'
						FROM [dbo].[DebtorsLedger] AS [DTL]
						LEFT OUTER JOIN [dbo].[matters] AS [MAT]
						ON [MAT].[Code] = [DTL].[MATTER]
						LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
						ON [CNT].[Code] = [MAT].[ClientCode]
						WHERE [DTL].[TYPE] = 'R'
						AND [DTL].[OSVALUE] <> 0
						AND			( 
										[CNT].[Name] LIKE '%' + @SearchString + '%' 
										OR
										[MAT].[Code] LIKE '%' + @SearchString + '%' 
										OR
										[DTL].[REF] LIKE '%' + @SearchString + '%' 
										OR
										[DTL].[BATCHNO] LIKE '%' + @SearchString + '%'
										OR
										[DTL].[PREF] LIKE '%' + @SearchString + '%'
										OR
										[DTL].[NARR] LIKE '%' + @SearchString + '%'
									)
END

GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SamDeleteCategoryContact' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SamDeleteCategoryContact] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SamDeleteCategoryContact]
		(@RecordId	      INT = 0)
AS
/*******************************************************************************************************
* delete Contact Categories					                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamDeleteCategoryContact]        	     				           *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-01    vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN
	BEGIN TRY
		BEGIN TRAN
			
			DELETE FROM ContactCategories 
			WHERE       RECORDID=@RecordId

		COMMIT TRAN
	END TRY

	BEGIN CATCH
		ROLLBACK TRAN
	END CATCH

END

GO

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

CREATE PROCEDURE [dbo].[KAAS_SamDesktopControl]			
AS
/*******************************************************************************************************
* This SP is used to get Config from Desktop Control												   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamDesktopControl]											   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-18		Vinodhkumar.M           Created                                                    *
 *******************************************************************************************************/ 
BEGIN
																	
				SELECT  [DEFAULTTASK]	 AS Defaulttask,
						[REQUESTER]		 AS Requester,
						[SPLITCHEQUES]   AS Splitcheques,
						[INDICATOR3]	 AS Indicator3,
						[INDICATOR4]	 AS Indicator4,
						[INDICATOR5]	 AS Indicator5,
						[INDICATOR6]	 AS Indicator6,
						[INDICATOR7]	 AS Indicator7,
						[INDICATOR8]	 AS Indicator8,
						[INDICATOR9]	 AS Indicator9,
						[INDICATOR10]	 AS Indicator10,
						[ENQUIRY]		 AS Enquiry,
						[TIMECOSTING]	 AS Timecosting,
						[BILLING]		 AS Billing,
						[CHEQUEREQ]		 AS Chequereq,
						[CLIENTREQ]		 AS Clientreq,
						[CASEMAN]		 AS Caseman,
						[RECORDID]		 AS Recordid
				FROM	[dbo].[DesktopControl]
					
END

GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMFetchApproveReturnMailDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMFetchApproveReturnMailDetails] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMFetchApproveReturnMailDetails]
	   (
		  @DraftNo			INT         = 0,
		  @HandlerCode      VARCHAR(20) = '',
		  @ReqNo			INT			= 0,
		  @Mode				VARCHAR(20) = ''
	   )				
AS
/*******************************************************************************************************
* To fetch draft invoice approve/return mail details											       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SAMFetchApproveReturnMailDetails]                                *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-29   Balamurugan C           Created                                                         *
* 2022-01-11   balamurugan C		   Modified - Fetch My Cheque Details							   *
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
	IF(@Mode = 'Invoice')
		BEGIN
			SELECT [BIH].[Matter],
				   [BIH].[ReturnReason],
				   [MAT].[Description],
				   [CON].[Name]	    AS [Name],
				   [SET].[KeyValue] AS [ApproverMailID],
				   [HAN].[Name]     AS [HandlerName],
				   [BIH].[User]		AS [RequestedUser],
				   [TOH].[Email]    AS [ToMailAddress]
			  FROM [dbo].[BillHeader] [BIH]
			  JOIN [dbo].[Matters] [MAT]
				ON [MAT].[Code] = [BIH].[Matter]
			  JOIN [dbo].[Settings] [SET]
				ON [SET].KeyName = 'InvoiceApprover'
			  JOIN [dbo].[Handlers] [HAN]
			    ON [HAN].[Code] = @HandlerCode
			  JOIN [dbo].[Handlers] [TOH]
			    ON [TOH].[Code] =[BIH].[User]
			  JOIN [dbo].[Contacts] [CON]
			    ON [CON].[Code] = [MAT].[ClientCode]
			 WHERE [DraftNo] =  @DraftNo
		END
	IF(@Mode = 'Cheque')
		BEGIN
			SELECT [MAT].[Code]				AS [Code],
				   [CON].[Name]				AS [Name],
				   [MAT].[Description]		As [Description],
				   [CRH].[ReturnReason]		AS [ReturnReason],
				   [HAN].[Email]			AS [ToMailAddress],
				   [SET].[KeyValue]			AS [ChequeApproverFromMail],
				   [CRH].[Who]				AS [RequestedUser]
			  FROM [dbo].[ChequeRequisitionHeader] [CRH]
			  JOIN [dbo].[ChequeRequisitionDetail] [CRD]
				ON [CRH].[ReqNo] = [CRD].[ReqNo]
			  JOIN [dbo].[Matters] [MAT]
			    ON [MAT].[Code] = [CRD].[Matter]
			  JOIN [dbo].[Settings] [SET]
			    ON [SET].[KeyName] = 'ChequeApprover'
			  JOIN [dbo].[Handlers] [HAN]
			    ON [HAN].[Code] =[CRH].[Who]
			  JOIN [dbo].[Contacts] [CON]
			    ON [CON].[Code] = [MAT].[ClientCode]
			 WHERE [CRH].[ReqNo] = @ReqNo
		END
	SET NOCOUNT OFF
END
GO

IF OBJECT_ID(N'KAAS_SamGetCategory', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_SamGetCategory]
END
GO
CREATE PROCEDURE [dbo].[KAAS_SamGetCategory]
AS
/*******************************************************************************************************
* This SP used to Fetch category                                                                      * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamGetCategory]   	            								   *
*                                                                                                      *
* Modification History:                                                                                *
* 29 July 2021    Revathy D        Created															   *                                          
 *******************************************************************************************************/ 
BEGIN
 SET NOCOUNT ON
		 SELECT
			   [CGR].[CATTYPE]       AS [CatType],
	           [CGR].[CODE]          AS [Code],
		       [CGR].[DESC$]         AS [CodeDescription],
		       [CGT].[CATEGORYTYPE]  AS [CategoryType],
		       [CGT].[DESCRIPTION]   AS [CategoryTypeDescription]
	       FROM 
		       [dbo].[Category] CGR
LEFT OUTER JOIN 
		       [dbo].[CategoryType] CGT
	         ON 
		       [CGR].[CATTYPE] = [CGT].[CATEGORYTYPE]
       ORDER BY 
		       [CGR].[CATTYPE] ASC, 
		       [CGR].[CODE]    ASC
 SET NOCOUNT OFF
END
GO








IF EXISTS
(SELECT TOP 1 1
     FROM SYS.[objects] SO
    WHERE SO.[name] = N'KAAS_SAMGetRowBatchDetails'
      AND SO.[type] = 'P')
  BEGIN
    DROP PROCEDURE [dbo].[KAAS_SAMGetRowBatchDetails]
  END
GO
CREATE PROCEDURE [dbo].[KAAS_SAMGetRowBatchDetails]  
   ( 
     @BatchNo     INT,
	 @KeyId       INT,
     @HandlerCode VARCHAR(10) = ''
   )

AS

/********************************************************************************************************
* Fetches the row details of specific batch                                                             * 
*                                                                                                       *
* Stored Procedure Name : [dbo].[KAAS_SAMGetRowBatchDetails]7423,5039,null  							*
*                                                                                                       *
* Modification History:                                                                                 *
* 2021-01-09    Vinodhkumar M        Created                                                            *
* 2024-03-04    Ghayathri S V        Modified to Fetch Prebilled Outlay value                           *
* 2024-04-23    Balamurugan.C        Modified - Added head batch and headpref column					*
**********************************************************************************************************/

BEGIN

	 SELECT 
			[BTD].[BatchNo], 
			[BTD].[Type], 
			[BTD].[Code], 
			[BTD].[Pref], 
			[BTD].[Ref], 
			[dbo].KEYHM_FNConvertUTCDateToTargetTimeZone(BTD.[Date], @HandlerCode)  AS [Date], 
			[BTD].[Narr], 
			[BTD].[Matter], 
			[BTD].[Fee],
			[BTD].[Supp], 
			[BTD].[Value], 
			[BTD].[VatCode],
			[BTD].[VatVal],
			[BTD].[Outlay], 
			[BTD].[Year], 
			[BTD].[PerNo], 
			[BTD].[OutlayCode], 
			[BTD].[HeadBatch], 
			[BTD].[AllocBatch], 
			[BTD].[AllocPref], 
			[BTD].[KeyId] ,
			[BTD].[ClientYN],
			[BTD].[AllocRef],
			[BTD].[AllocValue],
			[BTD].[AllocWriteOff],
			[BTD].[Payee],
			[BTD].[Branch],
			[BTD].[ThirdParty],
			[BTD].[PayClient],
			[BTD].[OnceOffPayment],
			[BTD].[ClientCode],
			[BTD].[EFTEmailYorN],
			[BTD].[CaseAssCode],
			[BTD].[PreBilledOutlay],
			[BTD].[HeadBatch],
			[BTD].[HeadPref]
	   FROM 
			[dbo].[BatchDetails] [BTD] 
	  WHERE 
			[BTD].[BATCHNO] = @BatchNo AND
			[BTD].[KEYID]=@KeyId
   ORDER BY 
			[BTD].[BATCHNO] ASC, 
		    [BTD].[PREF] ASC, 
		    [BTD].[KEYID] ASC
 END


 GO





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

CREATE PROCEDURE [dbo].[KAAS_SamGroupBGSelectedItems]
	   (@ControlID	       INT  = 0,
	    @OLDGuid    VARCHAR(38) = '',
		@NEWGuid    VARCHAR(38) = '',
		@GroupName	VARCHAR(38) = '')
AS
/*******************************************************************************************************
* Group selected Billing Guide items	                                                               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamGroupBGSelectedItems]           							   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-25    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN 
		EXEC [dbo].[ky_NewGroupBG] @ControlID, @GroupName

		SELECT @NEWGuid = convert(varchar(38), BGG.[ID])
		  FROM (  SELECT MAX([SeqNo]) As [SeqNo]
					FROM [dbo].[BGGroups] BGMAX
				   WHERE [BGControlID] = @ControlID) MX
			   INNER JOIN [dbo].[BGGroups] BGG
					   on BGG.[BGControlID] = @ControlID
					  AND BGG.[SeqNo] = MX.[SeqNo]

		EXEC [dbo].[ky_MoveGroupBG] @ControlID, @NEWGuid, @OLDGuid

END
GO

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

CREATE PROCEDURE [dbo].[KAAS_SamGroupBGSelectedNarrative]
	   (@ControlID	   INT = 0,
	    @GroupIDString VARCHAR(38))
AS
/*******************************************************************************************************
* group select Billing Guide to narative		                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamGroupBGSelectedNarrative]               					   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-25    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN 
		EXEC [dbo].[ky_GroupGroupNARRBG] @ControlID, @GroupIDString
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMInitiateBankRec' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMInitiateBankRec] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMInitiateBankRec] (
       @RECNO     INT,
       @BANKAC    VARCHAR(20),
       @RECDATE   DATETIME,
       @LASTRECNO INT)
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_SAMInitiateBankRec]                                                                           *
 *                                                                                                           *
 * Description : This procedure is used to create a new bank reconciliation                                  *
 * Copied From : [dbo].[ky_NETInitiateBankRec]                                                               *
 *                                                                                                           *
 * Modification history:                                                                                     *
 * 2022-02-11   Balamurugan    - Created                                                                     *
 *************************************************************************************************************/
BEGIN
    IF EXISTS (SELECT TOP 1 1
                 FROM [BankRecHistory] AS [BRH]
                WHERE [BRH].[RECNO] = @RECNO
                  AND [BRH].[BANKAC] = @BANKAC)
    BEGIN
        RETURN
    END

    -- If we come across any errors then dont keep any changes
    BEGIN TRY

    -- Pick up outstandings from before recs
    INSERT INTO [dbo].[BankRecTransactions] (
           [BANKAC],
           [TYPE],
           [DATE],
           [REF],
           [BATCH],
           [PREF],
           [NARR],
           [VALUE],
           [OSRECNO],
           [RECNO],
           [TICKED],
           [NomTransId])
    SELECT [BROT].[BANKAC],
           [BROT].[TYPE],
           [BROT].[DATE],
           [BROT].[REF],
           [BROT].[BATCH],
           [BROT].[PREF],
           [BROT].[NARR],
           [BROT].[VALUE],
           -1,
           @RECNO,
           '',
           [BROT].[RECORDID]
      FROM [dbo].[BankRecOutstandingTrans] AS [BROT]
     WHERE [BROT].[BANKAC] = @BANKAC

    DECLARE @TRANS TABLE (
            [RecordID] INT        PRIMARY KEY,
            [Type]     VARCHAR(1))
    
   -- Find list of transactions and figure out whether its a receipt or payment         
   INSERT INTO @TRANS (
           [RecordID],
           [Type])
    SELECT [NML].[RECORDID],
           CASE WHEN [BAH].[BATCHNO] IS NULL
                     THEN 'P' -- If no BatchH found then this is an EFT batch
                WHEN [BAH].[TYPE] IN ('T', 'R')
                 AND [NML].[CODE] = [BAH].[CLIENTBANK]
                     THEN 'P'
                WHEN [BAH].[TYPE] NOT IN ('P', 'R', 'T')
                  OR [NML].[BATCHNO] = 0
                     THEN CASE WHEN [NML].[VALUE] < 0
                                    THEN 'P'
                               ELSE 'R' END
                WHEN [BAH].[TYPE] = 'T'
                     THEN 'R'
                ELSE [BAH].[TYPE] END AS [Type]
      FROM [dbo].[NominalLedger] AS [NML]
           LEFT OUTER JOIN [dbo].[BatchH] AS [BAH]
                        ON [NML].[BATCHNO] = [BAH].[BATCHNO]
           LEFT OUTER JOIN [dbo].[BankRecTransactions] AS [BRT]
                        ON [BRT].[NomTransId] = [NML].[RECORDID]
                       AND [BRT].[BATCH] <> 0
     WHERE [NML].[RECNO] <= 0
       AND [NML].[CODE] = @BANKAC
       AND [NML].[DATE] <= @RECDATE
       AND [NML].[BATCHNO] <> 0
       AND [BRT].[RECORDID] IS NULL -- Dont bring the same items in again
       
    INSERT INTO [dbo].[BankRecTransactions] (
           [BANKAC],
           [TYPE],
           [DATE],
           [REF],
           [BATCH],
           [PREF],
           [NARR],
           [VALUE],
           [OSRECNO],
           [RECNO],
           [TICKED],
           [NomTransId])
    SELECT @BANKAC,
           [TMP].[Type],
           [NML].[DATE],
           LEFT([NML].[REF], 8),
           [NML].[BATCHNO],
           [NML].[PREF],
           LEFT([NML].[NARR], 60),
           CASE WHEN [TMP].[Type] = 'P'
                     THEN [NML].[VALUE] * -1
                ELSE [NML].[VALUE] END AS [VALUE],
           [NML].[RECNO] AS [OSRECNO],
           @RECNO,
           '' AS [TICKED],
           [NML].[RECORDID]
      FROM @TRANS AS [TMP]
           INNER JOIN [dbo].[NominalLedger] AS [NML]
                   ON [TMP].[RecordID] = [NML].[RECORDID]

    DECLARE @OSLODGE    DECIMAL(19, 2)
    DECLARE @OSCHEQUE   DECIMAL(19, 2)
    DECLARE @LODGEMENTS DECIMAL(19, 2)
    DECLARE @TOTCHEQUES DECIMAL(19, 2)
    
    SELECT @OSCHEQUE   = SUM(CASE WHEN [BRT].[TYPE] = 'P'
                                       THEN [BRT].[VALUE]
                                  ELSE 0 END),
           @OSLODGE    = SUM(CASE WHEN [BRT].[TYPE] = 'R'
                                       THEN [BRT].[VALUE]
                                  ELSE 0 END),
           @LODGEMENTS = SUM(CASE WHEN [BRT].[TYPE] = 'R'
                                   AND [BRT].[OSRECNO] = 0
                                       THEN [BRT].[VALUE]
                                  ELSE 0 END),
           @TOTCHEQUES = SUM(CASE WHEN [BRT].[TYPE] = 'P'
                                   AND [BRT].[OSRECNO] = 0
                                       THEN [BRT].[VALUE]
                                  ELSE 0 END)
      FROM [dbo].[BankRecTransactions] AS [BRT]
     WHERE [BRT].[BANKAC] = @BANKAC

    DECLARE @OPENBAL DECIMAL(19, 2)
    SELECT @OPENBAL = [BRH].[CLOSINGBAL]
      FROM [dbo].[BankRecHistory] AS [BRH]
     WHERE [BRH].[RECNO] = @LASTRECNO
       AND [BRH].[BANKAC] = @BANKAC

    SELECT @OPENBAL    = ISNULL(@OPENBAL, 0),
           @OSCHEQUE   = ISNULL(@OSCHEQUE, 0),
           @OSLODGE    = ISNULL(@OSLODGE, 0),
           @LODGEMENTS = ISNULL(@LODGEMENTS, 0),
           @TOTCHEQUES = ISNULL(@TOTCHEQUES, 0)

    INSERT INTO [dbo].[BankRecHistory] (
           [RECNO],
           [BANKAC],
           [RECDATE],
           [DATECOMPLETE],
           [LASTREC],
           [CURRENCY],
           [OPENINGBALANCE],
           [LODGEMENTS],
           [CHEQUES],
           [OSLODGEMENTS],
           [OSCHEQUES],
           [BANKBAL],
           [CLOSINGBAL],
           [DIFF])
    SELECT @RECNO,
           @BANKAC,
           @RECDATE,
           NULL,
           @LASTRECNO,
           'E',
           @OPENBAL,
           @LODGEMENTS,
           @TOTCHEQUES,
           @OSLODGE,
           @OSCHEQUE,
           0,
           @OPENBAL + @LODGEMENTS - @TOTCHEQUES,
           @OPENBAL + @LODGEMENTS - @TOTCHEQUES - @OSLODGE + @OSCHEQUE

    UPDATE [NML]
       SET [NML].[RECNO] = @RECNO * -1
      FROM [dbo].[NominalLedger] AS [NML]
           INNER JOIN @TRANS AS [TMP]
                   ON [TMP].[RecordID] = [NML].[RECORDID]
    END TRY
    BEGIN CATCH
    END CATCH
END
GO

IF OBJECT_ID(N'KAAS_SamInsertKPIParamerter', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_SamInsertKPIParamerter]
END
GO
CREATE PROCEDURE [dbo].[KAAS_SamInsertKPIParamerter] (
       @ID          INT,
       @StartOfYear DATETIME,
       @FromDate    DATETIME,
       @ToDate      DATETIME, 
       @Period      INT, 
       @Year        INT)
AS
 /*******************************************************************************************************
* This procedure is used to update the KPI Parameters								   *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_SamInsertKPIParamerter]  										   *
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-08-03	Revathy D		Created                                                                *
 *******************************************************************************************************/
BEGIN
 SET NOCOUNT ON
    IF ISNULL(@ID, 0) = 0 AND NOT EXISTS(SELECT TOP 1 1 FROM [dbo].[KPIParameters])
    BEGIN
        INSERT INTO [dbo].[KPIParameters] (
               [StartOfYear],
               [FromDate],
               [ToDate],
               [Period],
               [Year])
        SELECT @StartOfYear,
               @FromDate,
               @ToDate,
               @Period,
               @Year
    END
    ELSE
    BEGIN
       UPDATE [dbo].[KPIParameters]
          SET [StartOfYear] = @StartOfYear,
              [FromDate]    = @FromDate,
              [ToDate]      = @ToDate,
              [Period]      = @Period,
              [Year]        = @Year
        WHERE [ID] = @ID
    END    
 SET NOCOUNT OFF
END
GO





IF EXISTS (SELECT TOP 1 1
             FROM [sys].[objects] AS [SO]
            WHERE [SO].[name] = N'KAAS_SAMPeriodEndCheck'
              AND [SO].[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_SAMPeriodEndCheck]
END
GO
CREATE PROCEDURE [dbo].[KAAS_SAMPeriodEndCheck](
       @NEXTPERIODEND     DATETIME,    /* Next period end date, e.g. 31/01/2020 */
       @USER              VARCHAR(10), /* Log in code for user calling this proc */
	   @IGNOREUNALLOC     BIT) 
       
AS
/*******************************************************************************************
 * KAAS_SAMPeriodEndCheck
 * This procedure checks if a period end can be completed. It returns a list of errors in a 
 * single text column so that Clarion can handle this list and show the user
 * This also returns 1 if everything is okay and 0 if not
 *
 * Modification History;
 * 2024-01-12   Revathy.D   Created
 *
 *******************************************************************************************/
BEGIN
    SET NOCOUNT ON
    
    DECLARE @CONTINUE BIT
    SET @CONTINUE = 1
    
    DECLARE @RESULT TABLE ([Error] VARCHAR(2000),
	[ErrorCode] VARCHAR(100) )

    DECLARE @YEAR           INT
    DECLARE @CURPER         INT    
    DECLARE @TODAY          DATETIME

    SELECT TOP 1
           @YEAR          = [CON].[YEAR],
           @CURPER        = [CON].[CURPER]          
      FROM [dbo].[control] AS [CON]
  
    SELECT @CURPER       = ISNULL(@CURPER, 0),
           @YEAR         = ISNULL(@YEAR, 0),
           @CONTINUE     = 1,          
           @TODAY        = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
    
    /* Check for unallocated receipts */
    IF ISNULL((SELECT COUNT(1)
                 FROM [dbo].[DebtorsLedger] AS [DTL]
                WHERE 
				[DTL].[YEAR] = @YEAR
                  AND [DTL].[PER] = @CURPER
                  AND [DTL].[TYPE] = 'R'
                  AND [DTL].[OSVALUE] <> 0), 0) > 0
    BEGIN
	 IF(@IGNOREUNALLOC = 1)
	 BEGIN
            INSERT INTO [dbo].[Log] (
                   [DATE],
                   [EVENT],
                   [USER])
            VALUES (@TODAY,
                    'Period-end Unallocated Cash - accepted by user',
                    @USER)
					END
					ELSE
					BEGIN

            INSERT INTO @RESULT VALUES ('You have Unallocated Receipts|VAT on Cash Receipts basis requires there to be NONE
			|If you are on Cash Receipts basis and you continue this process|the consequences will NOT BE COVERED by your support contract
			|Continue with Period-end?','MSG')
			END
            SET @CONTINUE = 0
        
    END

    SELECT *
        FROM @RESULT
    
    RETURN @CONTINUE

SET NOCOUNT OFF
END

GO

IF EXISTS (SELECT TOP 1 1
             FROM [sys].[objects] AS [SO]
            WHERE [SO].[name] = N'KAAS_SAMPeriodEndProc'
              AND [SO].[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_SAMPeriodEndProc]
END
GO
CREATE PROCEDURE [dbo].[KAAS_SAMPeriodEndProc] (     
      @NEXTPERIODEND  DATETIME,  /* Next period end date, e.g. 31/01/2020 */    
      @USER           VARCHAR(10), /* Log in code for user calling this proc */
	  @IGNOREUNALLOC  BIT) 
AS
/*******************************************************************************************
 * KAAS_SAMPeriodEndProc
 * This procedure checks if a period end can be completed and then runs the year end.
 *
 * Modification History;
 * 2024-01-12   Revathy.D      Created                                                     *
 *******************************************************************************************/
BEGIN
    SET NOCOUNT ON
    SET XACT_ABORT ON	 

    DECLARE @TRANCOUNT INT
    SET @TRANCOUNT = @@TRANCOUNT
    
    IF @TRANCOUNT = 0
        BEGIN TRANSACTION
    ELSE
        SAVE TRANSACTION [PeriodEndTransaction]

    BEGIN TRY
        DECLARE @RESULT TABLE ([Error] VARCHAR(2000),
		[ErrorCode] VARCHAR(100))

        INSERT INTO @RESULT ([Error],[ErrorCode])
        EXEC [dbo].[KAAS_SAMPeriodEndCheck] @NEXTPERIODEND, @USER, @IGNOREUNALLOC
    
        /* If there any errors then quit */
        IF ISNULL((SELECT COUNT(1) FROM @RESULT), 0) > 0
        BEGIN
            SELECT *
                FROM @RESULT

            IF @TRANCOUNT = 0
                COMMIT TRANSACTION

            RETURN
        END

        DECLARE @YEAR           INT
        DECLARE @CURPER         INT
        DECLARE @TODAY          DATETIME

        SELECT TOP 1
               @YEAR          = [CON].[YEAR],
			   @CURPER		  = ISNULL([CON].[CURPER],0)
            FROM [dbo].[control] AS [CON]
  
        SELECT @YEAR         = ISNULL(@YEAR, 0),
               @TODAY        = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

        UPDATE [MAT]
           SET [MAT].[DebtBalFwd]       = 0,
               [MAT].[OutlayBalFwd]     = 0,
               [MAT].[ClientBalFwd]     = 0,
               [MAT].[ClientCurBalFwd]  = 0,
               [MAT].[ClientDepBalFwd]  = 0,
               [MAT].[CurDebtBalFwd]    = 0,
               [MAT].[CurOutlayBalFwd]  = 0,
               [MAT].[CurClientCBalFwd] = 0,
               [MAT].[CurClientDBalFwd] = 0
          FROM [dbo].[matters] AS [MAT]

		 
        UPDATE [SUP]
           SET [SUP].[BALANCEFWD] = 0
          FROM [dbo].[Suppliers] AS [SUP]

		 
       
	   UPDATE [NOM]
          SET [NOM].[MONTH2] = CASE WHEN @CURPER = 1 
		                       THEN [NOM].[BALANCEFWD] ELSE [NOM].[MONTH2]
							   END,
			  [NOM].[MONTH3] = CASE WHEN @CURPER = 2 
							   THEN [NOM].[BALANCEFWD] ELSE [NOM].[MONTH3]
							   END,
			  [NOM].[MONTH4] = CASE WHEN @CURPER = 3 
							   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH4]
			                   END,
			  [NOM].[MONTH5] = CASE WHEN @CURPER = 4
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH5]
			                   END,
			  [NOM].[MONTH6] = CASE WHEN @CURPER = 5 
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH6]
			                   END,
			  [NOM].[MONTH7] = CASE WHEN @CURPER = 6
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH7]
			                   END,
			  [NOM].[MONTH8] = CASE WHEN @CURPER = 7
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH8]
			                   END, 
			  [NOM].[MONTH9] = CASE WHEN @CURPER = 8 
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH9]
			                   END,
			  [NOM].[MONTH10]= CASE WHEN @CURPER = 9 
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH10]
			                   END,
			  [NOM].[MONTH11]= CASE WHEN @CURPER = 10
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH11]
			                   END,
			  [NOM].[MONTH12]= CASE WHEN @CURPER = 11
			                   THEN  [NOM].[BALANCEFWD] ELSE [NOM].[MONTH12]
			                   END,
			  [NOM].[BALANCEFWD] = 0,
			  [NOM].[CURRENCYBALFWD] = 0
         FROM [dbo].[Nominal] AS [NOM]

		UPDATE [CON] 
		   SET [CON].[P1BATCH] = CASE WHEN @CURPER = 1 
								 THEN [CON].[LASTBATCH] ELSE [CON].[P1BATCH] 
								 END,
			   [CON].[P2BATCH] = CASE WHEN @CURPER = 2 
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P2BATCH]
								 END,
			   [CON].[P3BATCH] = CASE WHEN @CURPER = 3 
							     THEN  [CON].[LASTBATCH] ELSE [CON].[P3BATCH]
			                     END,
			   [CON].[P4BATCH] = CASE WHEN @CURPER = 4
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P4BATCH]
								 END,
			   [CON].[P5BATCH] = CASE WHEN @CURPER = 5 
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P5BATCH]
							     END,
			   [CON].[P6BATCH] = CASE WHEN @CURPER = 6
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P6BATCH]
								 END,
			   [CON].[P7BATCH] = CASE WHEN @CURPER = 7
								 Then  [CON].[LASTBATCH] ELSE [CON].[P7BATCH]
								 END, 
			   [CON].[P8BATCH] = CASE WHEN @CURPER = 8 
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P8BATCH]
								 END,
			   [CON].[P9BATCH] = CASE WHEN @CURPER = 9 
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P9BATCH]
								 END,
			   [CON].[P10BATCH]= CASE WHEN @CURPER = 10
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P10BATCH]
								 END,
			   [CON].[P11BATCH]= CASE WHEN @CURPER = 11
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P11BATCH]
								 END,
			   [CON].[P12BATCH]= CASE WHEN @CURPER = 12 
								 THEN  [CON].[LASTBATCH] ELSE [CON].[P12BATCH]
								 END,
			   [CON].[CURPER]  = @CURPER+1, 
			   [CON].[PERIODEND]= DATEDIFF(DAY, '18001228', @NEXTPERIODEND)
		  FROM [dbo].[Control] [CON]  



        INSERT INTO [dbo].[Log] (
               [DATE],
               [EVENT],
               [USER])
        SELECT @TODAY,
               'Period End ' + CONVERT(VARCHAR(24), GETDATE(), 113),
               @USER
        
        IF @TRANCOUNT = 0
            COMMIT TRANSACTION

    END TRY
    BEGIN CATCH
        DECLARE @ERROR   INT
        DECLARE @MESSAGE VARCHAR(4000)
        DECLARE @XSTATE  INT

        SELECT @ERROR   = ERROR_NUMBER(),
               @MESSAGE = ERROR_MESSAGE(),
               @XSTATE  = XACT_STATE()

        DECLARE @ERRMSG VARCHAR(2000)

        SET @ERRMSG = '0 - An error occurred. Please contact support.' + 
                      CHAR(13) + CHAR(10) + 
                      'On line ' + CONVERT(VARCHAR(10), ERROR_LINE()) + ': ' + 
                      CHAR(13) + CHAR(10) + 
                      @MESSAGE

        SELECT @ERRMSG,'ERR'

        IF @TRANCOUNT = 0
        BEGIN
            PRINT(3)
            ROLLBACK TRANSACTION
        END
        ELSE
        BEGIN
            IF @XSTATE <> -1
            BEGIN
                ROLLBACK TRANSACTION [PeriodEndTransaction]
            END
        END
                
        RAISERROR(@ERRMSG, 16, 1, @ERROR, @MESSAGE)
        
    END CATCH
    
    SET NOCOUNT OFF
END

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMRefreshBankRec' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMRefreshBankRec] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMRefreshBankRec] (
       @RECNO  INT,
       @BANKAC VARCHAR(20))
AS
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_SAMRefreshBankRec]                                                                            *
 *                                                                                                           *
 * Description: This procedure is used to get new transactions and put them into a bank rec in progress      *
 * Copied From: [dbo].[ky_NETRefreshBankRec]																 *
 *                                                                                                           *
 * Modification history:                                                                                     *
 * 2022-02-11   Balamurugan   Created                                                                        *
 *************************************************************************************************************/
BEGIN
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [BankRecHistory] AS [BRH]
                    WHERE [BRH].[RECNO] = @RECNO
                      AND [BRH].[BANKAC] = @BANKAC)
    BEGIN
        RETURN
    END

    DECLARE @RECDATE DATETIME

    SELECT @RECDATE = [BRH].[RECDATE]
      FROM [dbo].[BankRecHistory] AS [BRH]
     WHERE [BRH].[RECNO] = @RECNO
       AND [BRH].[BANKAC] = @BANKAC

    DECLARE @TRANS TABLE (
            [RecordID] INT        PRIMARY KEY,
            [Type]     VARCHAR(1))
   
   -- Find list of transactions and figure out whether its a receipt or payment         
   INSERT INTO @TRANS (
           [RecordID],
           [Type])
    SELECT [NML].[RECORDID],
           CASE WHEN [BAH].[BATCHNO] IS NULL
                     THEN 'P' -- If no BatchH found then this is an EFT batch
                WHEN [BAH].[TYPE] IN ('T', 'R')
                 AND [NML].[CODE] = [BAH].[CLIENTBANK]
                     THEN 'P'
                WHEN [BAH].[TYPE] NOT IN ('P', 'R', 'T')
                  OR [BAH].[BATCHNO] = 0
                     THEN CASE WHEN [NML].[VALUE] < 0
                                    THEN 'P'
                               ELSE 'R' END
                WHEN [BAH].[TYPE] = 'T'
                     THEN 'R'
                ELSE [BAH].[TYPE] END AS [Type]
      FROM [dbo].[NominalLedger] AS [NML]
           LEFT OUTER JOIN [dbo].[BatchH] AS [BAH]
                        ON [NML].[BATCHNO] = [BAH].[BATCHNO]
           LEFT OUTER JOIN [dbo].[BankRecTransactions] AS [BRT]
                        ON [BRT].[NomTransId] = [NML].[RECORDID]
                       AND [BRT].[BATCH] <> 0
     WHERE [NML].[RECNO] = 0
       AND [NML].[CODE] = @BANKAC
       AND [NML].[DATE] <= @RECDATE
       AND [NML].[BATCHNO] <> 0
       AND [BRT].[RECORDID] IS NULL -- Dont bring the same items in again

    INSERT INTO [dbo].[BankRecTransactions] (
           [BANKAC],
           [TYPE],
           [DATE],
           [REF],
           [BATCH],
           [PREF],
           [NARR],
           [VALUE],
           [OSRECNO],
           [RECNO],
           [TICKED],
           [NomTransId])
    SELECT @BANKAC,
           [TMP].[Type],
           [NML].[DATE],
           LEFT([NML].[REF], 8),
           [NML].[BATCHNO],
           [NML].[PREF],
           LEFT([NML].[NARR], 60),
           CASE WHEN [TMP].[Type] = 'P'
                     THEN [NML].[VALUE] * -1
                ELSE [NML].[VALUE] END AS [VALUE],
           0 AS [OSRECNO],
           @RECNO,
           '' AS [TICKED],
           [NML].[RECORDID]
      FROM @TRANS AS [TMP]
           INNER JOIN [dbo].[NominalLedger] AS [NML]
                   ON [TMP].[RecordID] = [NML].[RECORDID]

    UPDATE [NML]
       SET [NML].[RECNO] = @RECNO * -1
      FROM [dbo].[NominalLedger] AS [NML]
           INNER JOIN @TRANS AS [TMP]
                   ON [TMP].[RecordID] = [NML].[RECORDID]
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_SamSaveCategoryContact]
	   (@RecordId				INT  = 0,
	    @CategoryType	 VARCHAR(6)  = '',
		@Category		VARCHAR(10)  = '',
		@Date        	       DATE  = NULL,
		@FieldValue1    VARCHAR(60)  = '',
		@FieldValue2    VARCHAR(60)  = '',
		@FieldValue3    VARCHAR(60)  = '',
		@FieldValue4    VARCHAR(60)  = '',
		@FieldValue5    VARCHAR(60)  = '',
		@FieldValue6    VARCHAR(60)  = '',
		@FieldValue7    VARCHAR(60)  = '',
		@FieldValue8    VARCHAR(60)  = '',
		@FieldValue9    VARCHAR(60)  = '',
		@FieldValue10   VARCHAR(60)  = '',
		@ContactCode	 VARCHAR(8)  = '')
AS

/*******************************************************************************************************
* Save contact category code and type								                                   * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamSaveCategoryContact]        			    			       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-01    Vinodhkumar M        Created                                                           *
* 2022-03-09   Balamurugan.C        Modified - Handled TCL Statements                                  * 
 *******************************************************************************************************/

BEGIN
	BEGIN TRY
		BEGIN TRAN
		IF(@RecordId != 0)
		 BEGIN
			UPDATE ContactCategories
			   SET 
					CATEGORYTYPE   = @CategoryType,
					CATEGORY       = @Category,
					DATE		   = @Date,
					FIELDVALUE1    = @FieldValue1,
					FIELDVALUE2    = @FieldValue2,
					FIELDVALUE3    = @FieldValue3,
					FIELDVALUE4    = @FieldValue4,
					FIELDVALUE5    = @FieldValue5,
					FIELDVALUE6    = @FieldValue6,
					FIELDVALUE7    = @FieldValue7,
					FIELDVALUE8    = @FieldValue8,
					FIELDVALUE9    = @FieldValue9,
					FIELDVALUE10   = @FieldValue10
			 WHERE  
					RECORDID       = @RecordId					
		 END
		ELSE
		 BEGIN
		   INSERT INTO ContactCategories(
						CONTACT,
						CATEGORYTYPE,
						CATEGORY,
						DATE,
						FIELDVALUE1,
						FIELDVALUE2,
						FIELDVALUE3,
						FIELDVALUE4,
						FIELDVALUE5,
						FIELDVALUE6,
						FIELDVALUE7,
						FIELDVALUE8,
						FIELDVALUE9,
						FIELDVALUE10)

				 VALUES(
						@ContactCode,
						@CategoryType,
						@Category,
						@Date,
						@FieldValue1,
						@FieldValue2,
						@FieldValue3,
						@FieldValue4,
						@FieldValue5,
						@FieldValue6,
						@FieldValue7,
						@FieldValue8,
						@FieldValue9,
						@FieldValue10)
		 END

	  COMMIT TRAN
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END 
	END CATCH


 END

GO

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

CREATE PROCEDURE
       [dbo].[KAAS_SAMSelectContacts]
	    ( 
			@PageNumber    INT = 1,
			@PageSize	   INT = 20000,
			@Search  VARCHAR(500) = '',
			@SortBy	   VARCHAR(100) = 'Code',
			@SortOrder     VARCHAR(100) = 'ASC',
			@Handler       VARCHAR(20)  = ''
		 )
AS
/************************************************************************************
* This procedure is used To Fetch Contacts for Browse Contacts page					*
*                                                                                   *
* Stored Procedure Name	: [dbo].[KAAS_SAMSelectContacts]        					*
*                                                                                   *
* Modification History	:                                                           *
* 2024-03-13	Vignesh M		Created	
* 2024-03-14	Vignesh M		Modified - As per Client suggestion
								Handler privileges has been removed	
 ************************************************************************************/
BEGIN
DECLARE		@sql		      NVARCHAR(max)
DECLARE		@offset		      INT = @PageSize * (@PageNumber -1)

SET			@sql =		'SELECT DISTINCT
								ROW_NUMBER() OVER(ORDER BY [CTC].CODE ASC)												  AS [Id],
								RTRIM(ISNULL([CTC].[Code], ''''))                                                         AS [Code],
								RTRIM(ISNULL([CTC].[Name], ''''))                                                         AS [Name],
								MAX([RML].[DateField])                                                                    AS [LastAccessed],
								[dbo].[KAAS_FN_RemoveSpuriousWhitespace](RTRIM(ISNULL([CTC].[Address], '''')), 200)       AS [Address],
								[dbo].[KAAS_FN_RemoveSpuriousWhitespace](RTRIM(ISNULL([CTC].[OtherAddress], '''')), 200)  AS [OtherAddress],
								[dbo].[ky_HeuristicMultiPhoneNo](RTRIM(ISNULL([CTC].[Address], '''')), [CTC].[Tel])       AS [PhoneNo],
								[dbo].[ky_HeuristicMultiPhoneNo](RTRIM(ISNULL([CTC].[Address], '''')), [CTC].[Fax])       AS [FaxNo],
								RTRIM(ISNULL([CTC].[Salut], ''''))                                                        AS [Salut],
								RTRIM(ISNULL([CTC].[email], ''''))                                                        AS [email],
								CASE WHEN ISNULL([CTC].[Approved], 0) = 1 THEN 1 ELSE 0 END                               AS [Approved],
								CASE WHEN RTRIM(ISNULL([CTC].[ChargeOutRateInd], '''')) = ''Y'' THEN ''Y'' ELSE ''N'' END   AS [ChargeOutRateInd],
								[CTC].[CompMatter]
						   FROM [dbo].[contacts] [CTC]
					  LEFT JOIN [dbo].[Matters] [SL]        ON [SL].[ClientCode] = [CTC].[Code]
					  LEFT JOIN [dbo].[RecentMatterList] [RML]    ON [SL].[Code] = [RML].[MATTER] ' +
	                     'WHERE	1 = 1' +
		                   'AND  ( 
									[CTC].[Code]    LIKE' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[Name]      LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[Address]      LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[OtherAddress]    LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[Tel]  LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[Fax]   LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[Salut]   LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[email]   LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[Approved]   LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[ChargeOutRateInd]   LIKE ' + '''%' + @Search + '%' + '''' +
									'OR
									[CTC].[CompMatter]   LIKE ' + '''%' + @Search + '%' + '''' +
									
								 ')
					 GROUP BY [CTC].[Code]
							 ,[CTC].[Name]
							 ,[CTC].[Address]
							 ,[CTC].[OtherAddress]
							 ,[CTC].[Tel]
							 ,[CTC].[Fax]
							 ,[CTC].[Salut]
							 ,[CTC].[email]
							 ,[CTC].[Approved]
							 ,[CTC].[ChargeOutRateInd]
							 ,[CTC].[CompMatter]
					 ORDER BY '  +    @SortBy + ' '  + @SortOrder + ' ' +
	                  'OFFSET '  +    CAST(@offset AS NVARCHAR(10)) + ' ROWS ' + 
                  'FETCH NEXT '  +    CAST(@PageSize AS NVARCHAR(10)) +  ' ROWS ONLY';

PRINT @sql
EXEC Sp_executesql @sql

END

GO


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

CREATE PROCEDURE [dbo].[KAAS_SamUnGroupBillingGuide]
	   (@ControlID	   INT = 0,
	    @GroupIDString VARCHAR(38))
AS
/*******************************************************************************************************
* UnGroup all Billing Guide				                                                               * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SamUnGroupBillingGuide]           							   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-25    Vinodhkumar M        Created                                                           *
*******************************************************************************************************/
BEGIN 
		EXEC [dbo].[ky_UngroupGUIDBG] @ControlID, @GroupIDString
		EXEC [dbo].[ky_ReorderGroupBG] @ControlID
END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMUpdateMatterTimeBalance' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMUpdateMatterTimeBalance] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_SAMUpdateMatterTimeBalance]
        (
			@matter            VARCHAR(20)
		)
AS
  /*******************************************************************************************************
  *  Update Matter Time Balance                                                                          * 
  *                                                                                                      *
  * Stored Procedure Name : [dbo].[KAAS_SAMUpdateMatterTimeBalance]   			            			 *
  * Copied From           : [dbo].[ky_WDUpdateMatterTimeBalance]                                         *
  *                                                                                                      *
  * Modification History:                                                                                *
  * 2021-11-12    Balamurugan C        Created                                                           *
  *******************************************************************************************************/
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.[CHARGE], 0) - IsNull(TIE.[BilledAmount], 0) <> 0
													THEN IsNull(TIE.[time], 0) 
											   ELSE 0 END), 0) AS [TOTALTIME],
							   IsNull(SUM(IsNull(TIE.[CHARGE], 0) - IsNull(TIE.[BilledAmount], 0)), 0) AS [TOTALCHARGED]
						  FROM [dbo].[TimeEntry] TIE
						 WHERE TIE.[MATTER] = MAT.[Code]
						   AND RTRIM(ISNULL(TIE.[REC_IRR], '')) <> 'N'
						   AND RTRIM(ISNULL(TIE.[TimeorCharge], '')) <> 'B') TTL
	 WHERE MAT.[Code] = @Matter

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMYearEndCheck' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMYearEndCheck] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_SAMYearEndCheck] (
       @YEARENDDATE    DATETIME,    /* Year end date, e.g. 31/12/2019 */
       @SUBDATEFROM    DATETIME,    /* Balance forward date, e.g. 01/01/2020 */
       @NEXTPERIODEND  DATETIME,    /* Next period end date, e.g. 31/01/2020 */
       @UPDATEALLOCS   VARCHAR(1),  /* Check unallocated receipts, typically set to 'Y' */
       @USER           VARCHAR(10), /* Log in code for user calling this proc */
       @IGNOREUNALLOC  BIT)         /* Set to 1 to ignore unallocated receipts, this will be logged */
AS
/*******************************************************************************************
 * KAAS_SAMYearEndCheck
 * This procedure checks if a year end can be completed. It returns a list of errors in a 
 * single text column so that Clarion can handle this list and show the user
 * This also returns 1 if everything is okay and 0 if not
 *
 * Modification History;
 * 2024-01-24   Revathy.D   Copied from [dbo].[ky_NETYearEndCheck]                         *
 *******************************************************************************************/
BEGIN
    SET NOCOUNT ON
    
    DECLARE @CONTINUE BIT
    SET @CONTINUE = 1
    
    DECLARE @RESULT TABLE ([Error] VARCHAR(2000))

    DECLARE @YEAR           INT
    DECLARE @CURPER         INT
    DECLARE @PL             VARCHAR(10)
    DECLARE @RECINSTALLED   VARCHAR(1)
    DECLARE @BADNOM         VARCHAR(2000)
    DECLARE @TIMECOSTING    VARCHAR(1)
    DECLARE @TODAY          DATETIME
    DECLARE @EICONVERT      DECIMAL(19, 6)

    SELECT TOP 1
           @YEAR          = [CON].[YEAR],
           @CURPER        = [CON].[CURPER],
           @RECINSTALLED  = [CON].[RECINSTALLED],
           @PL            = [CON].[PL],
           @TIMECOSTING   = [CON].[TIMECOSTING],
           @EICONVERT     = [CON].[EICONVERT]
      FROM [dbo].[control] AS [CON]
  
    SELECT @CURPER       = ISNULL(@CURPER, 0),
           @YEAR         = ISNULL(@YEAR, 0),
           @CONTINUE     = 1,
           @RECINSTALLED = ISNULL(@RECINSTALLED, ''),
           @TIMECOSTING  = ISNULL(@TIMECOSTING, ''),
           @TODAY        = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
           @EICONVERT    = ISNULL(@EICONVERT, 1)

    IF @YEARENDDATE IS NULL
    BEGIN
        INSERT INTO @RESULT VALUES ('1 - Year end date is not set')
        SET @CONTINUE = 0
    END

    IF ISNULL(@CURPER, 0) < 12
    BEGIN
        INSERT INTO @RESULT VALUES ('2 - Period is not 12')
        SET @CONTINUE = 0
    END

    /* Check for period 13 entries that have a date <= year end date */
    IF ISNULL((SELECT COUNT(1)
                 FROM [dbo].[NominalLedger] AS [NML]
                WHERE [NML].[YEAR] = @YEAR
                  AND [NML].[PER] = 13
                  AND [NML].[DATE] <= @YEARENDDATE), 0) > 0
    BEGIN
        INSERT INTO @RESULT VALUES ('3 - Entries in period 13 dated before year end date')
        SET @CONTINUE = 0
    END

    /* Check for unallocated receipts */
    IF ISNULL((SELECT COUNT(1)
                 FROM [dbo].[DebtorsLedger] AS [DTL]
                WHERE [DTL].[YEAR] = @YEAR
                  AND [DTL].[PER] = @CURPER
                  AND [DTL].[TYPE] = 'R'
                  AND [DTL].[OSVALUE] <> 0), 0) > 0
    BEGIN
        IF @IGNOREUNALLOC = 1
        BEGIN
            INSERT INTO [dbo].[Log] (
                   [DATE],
                   [EVENT],
                   [USER])
            VALUES (@TODAY,
                    'Year-end Unallocated Cash - accepted by user',
                    @USER)
        END
        ELSE
        BEGIN
            INSERT INTO @RESULT VALUES ('4 - Unallocated receipts')
            SET @CONTINUE = 0
        END
    END

    IF EXISTS (SELECT TOP 1 1
                 FROM [dbo].[Nominal] AS [NOM]
                WHERE ISNULL(LTRIM(RTRIM([NOM].[PB])), '') = '')
    BEGIN
        SET @BADNOM = NULL

        SELECT @BADNOM = CASE WHEN @BADNOM IS NOT NULL
                                   THEN @BADNOM + ', '
                              ELSE '' END + 
                         [NOM].[Code]
          FROM [dbo].[Nominal] AS [NOM]
         WHERE ISNULL(LTRIM(RTRIM([NOM].[PB])), '') = ''
     
        INSERT INTO @RESULT VALUES ('5 - Nominals not marked as Profit & Loss or Balance Sheet: ' + @BADNOM)
        SET @CONTINUE = 0
    END

    IF @RECINSTALLED = 'Y'
    BEGIN
        /* Check if any banks are not reconciled */
        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Nominal] AS [NOM]
                          INNER JOIN [dbo].[NominalLedger] AS [NML]
                                  ON [NOM].[CODE] = [NML].[CODE]
                    WHERE [NOM].[TYPE] = 'BANK'
                      AND [NML].[DATE] <= @YEARENDDATE
                      AND [NML].[RECNO] = 0)
        BEGIN
            SET @BADNOM = NULL

            SELECT @BADNOM = CASE WHEN @BADNOM IS NOT NULL
                                       THEN @BADNOM + ', '
                                  ELSE '' END +
                             [NOM].[CODE]
              FROM [dbo].[Nominal] AS [NOM]
                   INNER JOIN (SELECT [NML].[CODE]
                                 FROM [dbo].[NominalLedger] AS [NML]
                                WHERE [NML].[RECNO] = 0
                                  AND [NML].[DATE] <= @YEARENDDATE
                                      GROUP BY [NML].[CODE]) AS [NML]
                            ON [NML].[CODE] = [NOM].[CODE]
             WHERE [NOM].[TYPE] ='BANK'

            INSERT INTO @RESULT VALUES ('6 - Bank reconcilliation for bank accounts has not been completed: ' + @BADNOM)
            SET @CONTINUE = 0
        END

        /* Check if any bank recs are incomplete */
        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BankRecHistory] AS [BRH]
                    WHERE [BRH].[DATECOMPLETE] IS NULL)
        BEGIN
            SET @BADNOM = NULL

            SELECT @BADNOM = CASE WHEN @BADNOM IS NOT NULL
                                       THEN @BADNOM + ', '
                                  ELSE '' END +
                             [NOM].[CODE]
              FROM [dbo].[Nominal] AS [NOM]
                   INNER JOIN (SELECT [BRH].[BANKAC]
                                 FROM [dbo].[BankRecHistory] AS [BRH]
                                WHERE [BRH].[DATECOMPLETE] IS NULL
                                      GROUP BY [BRH].[BANKAC]) AS [BRH]
                           ON [BRH].[BANKAC] = [NOM].[CODE]

            INSERT INTO @RESULT VALUES ('7 - Bank recs for the following banks are not complete: ' + @BADNOM)
            SET @CONTINUE = 0
        END
    END

    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Nominal] AS [NOM]
                    WHERE [NOM].[CODE] = @PL)
    BEGIN
        INSERT INTO @RESULT VALUES ('8 - P&L account not specified in the system options')
        SET @CONTINUE = 0
    END

    SELECT *
        FROM @RESULT
    
    RETURN @CONTINUE

SET NOCOUNT OFF
END

GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SAMYearEndProc' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SAMYearEndProc] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_SAMYearEndProc] (
       @YEARENDDATE    DATETIME,    /* Year end date, e.g. 31/12/2019 */
       @SUBDATEFROM    DATETIME,    /* Balance forward date, e.g. 01/01/2020 */
       @NEXTPERIODEND  DATETIME,    /* Next period end date, e.g. 31/01/2020 */
       @UPDATEALLOCS   VARCHAR(1),  /* Check unallocated receipts, typically set to 'Y' */
       @USER           VARCHAR(10)  /* Log in code for user calling this proc */,
       @IGNOREUNALLOC  BIT)         /* Set to 1 to ignore unallocated receipts, this will be logged */
AS
/*******************************************************************************************
 * KAAS_SAMYearEndProc
 * This procedure checks if a year end can be completed and then runs the year end.
 *
 * Modification History;
 * 2024-01-24   Revathy.D      Copied from [dbo].[ky_NETYearEndProc]                        *
 *******************************************************************************************/
BEGIN
    SET NOCOUNT ON
    SET XACT_ABORT ON

    /*
        JG discussed with SK the default behaviour regarding clearing/keeping the nominal ledger of the year we are closing.

        For on premise the default behaviour is to CLEAR the nominal ledger (much like the original Clarion code did)
        For  Azure DB  the default behaviour is to KEEP  the nominal ledger (because we wont restore previous year as a separate DB)

        In order to change this behaviour you can add the setting "KeepNominalLedgerYearEnd" and set it to 1 to keep, or 0 to clear
        the nominal ledger in the procedure
    */

    DECLARE @KEEPNOMINALLEDGER BIT
    SET @KEEPNOMINALLEDGER = 0

    IF ServerProperty('EngineEdition') = 5
    BEGIN
        SET @KEEPNOMINALLEDGER = 1
    END
    
    IF EXISTS (SELECT TOP 1 1
                 FROM [dbo].[Settings] AS [SET]
                WHERE [SET].[KeyName] = 'KeepNominalLedgerYearEnd')
    BEGIN
        SELECT @KEEPNOMINALLEDGER = CASE WHEN [SET].[KeyValue] = '1' THEN 1
                                         WHEN [SET].[KeyValue] = '0' THEN 0
                                         ELSE @KEEPNOMINALLEDGER END
          FROM [dbo].[Settings] AS [SET]
         WHERE [SET].[KeyName] = 'KeepNominalLedgerYearEnd'
    END

    DECLARE @TRANCOUNT INT
    SET @TRANCOUNT = @@TRANCOUNT
    
    IF @TRANCOUNT = 0
        BEGIN TRANSACTION
    ELSE
        SAVE TRANSACTION [YearEndTransaction]

    BEGIN TRY
        DECLARE @RESULT TABLE ([Error] VARCHAR(2000))

        INSERT INTO @RESULT ([Error])
        EXEC [dbo].[KAAS_SAMYearEndCheck] @YEARENDDATE, @SUBDATEFROM, @NEXTPERIODEND, @UPDATEALLOCS, @USER, @IGNOREUNALLOC
    
        /* If there any errors then quit */
        IF ISNULL((SELECT COUNT(1) FROM @RESULT), 0) > 0
        BEGIN
            SELECT *
                FROM @RESULT

            IF @TRANCOUNT = 0
                COMMIT TRANSACTION

            RETURN
        END

        DECLARE @YEAR           INT
        DECLARE @PL             VARCHAR(10)
        DECLARE @RECINSTALLED   VARCHAR(1)
        DECLARE @TIMECOSTING    VARCHAR(1)
        DECLARE @TODAY          DATETIME
        DECLARE @EICONVERT      DECIMAL(19, 6)

        SELECT TOP 1
               @YEAR          = [CON].[YEAR],
               @RECINSTALLED  = [CON].[RECINSTALLED],
               @PL            = [CON].[PL],
               @TIMECOSTING   = [CON].[TIMECOSTING],
               @EICONVERT     = [CON].[EICONVERT]
            FROM [dbo].[control] AS [CON]
  
        SELECT @YEAR         = ISNULL(@YEAR, 0),
               @RECINSTALLED = ISNULL(@RECINSTALLED, ''),
               @TIMECOSTING  = ISNULL(@TIMECOSTING, ''),
               @TODAY        = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
               @EICONVERT    = ISNULL(@EICONVERT, 1)

        /* Check tables for forward post transactions and set period to 13 (look at the date and control file period end date) */
        UPDATE [NML]
           SET [NML].[PER] = 13
          FROM [dbo].[NominalLedger] AS [NML]
         WHERE [NML].[DATE] > @YEARENDDATE
           AND [NML].[PER] <> 13
           AND [NML].[YEAR] = @YEAR

        UPDATE [BAH]
           SET [BAH].[PERNO] = 13
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[DATE] > @YEARENDDATE
           AND [BAH].[PERNO] <> 13
           AND [BAH].[YEAR] = @YEAR

        UPDATE [BAD]
           SET [BAD].[PERNO] = 13
          FROM [dbo].[BatchDetails] AS [BAD]
         WHERE [BAD].[DATE] > @YEARENDDATE
           AND [BAD].[PERNO] <> 13
           AND [BAD].[YEAR] = @YEAR

        UPDATE [DTL]
           SET [DTL].[PER] = 13
          FROM [dbo].[DebtorsLedger] AS [DTL]
         WHERE [DTL].[DATE] > @YEARENDDATE
           AND [DTL].[PER] <> 13
           AND [DTL].[YEAR] = @YEAR

        UPDATE [SPL]
           SET [SPL].[PER] = 13
          FROM [dbo].[SupplierLedger] AS [SPL]
         WHERE [SPL].[DATE] > @YEARENDDATE
           AND [SPL].[PER] <> 13
           AND [SPL].[YEAR] = @YEAR

        UPDATE [MTL]
           SET [MTL].[PER] = 13
          FROM [dbo].[MatterLedger] AS [MTL]
         WHERE [MTL].[DATE] > @YEARENDDATE
           AND [MTL].[PER] <> 13
           AND [MTL].[YEAR] = @YEAR
            
        UPDATE [MAT]
           SET [MAT].[DebtBalFwd]       = 0,
               [MAT].[OutlayBalFwd]     = 0,
               [MAT].[ClientBalFwd]     = 0,
               [MAT].[ClientCurBalFwd]  = 0,
               [MAT].[ClientDepBalFwd]  = 0,
               [MAT].[CurDebtBalFwd]    = 0,
               [MAT].[CurOutlayBalFwd]  = 0,
               [MAT].[CurClientCBalFwd] = 0,
               [MAT].[CurClientDBalFwd] = 0
          FROM [dbo].[matters] AS [MAT]

        UPDATE [SUP]
           SET [SUP].[BALANCEFWD] = 0
          FROM [dbo].[Suppliers] AS [SUP]

        UPDATE [DTL]
           SET [DTL].[PER] = 1,
               [DTL].[YEAR] = [DTL].[YEAR] + 1
          FROM [dbo].[DebtorsLedger] AS [DTL]
         WHERE [DTL].[DATE] > @YEARENDDATE
           AND [DTL].[YEAR] = @YEAR

        UPDATE [SPL]
           SET [SPL].[PER] = 1,
               [SPL].[YEAR] = [SPL].[YEAR] + 1
          FROM [dbo].[SupplierLedger] AS [SPL]
         WHERE [SPL].[DATE] > @YEARENDDATE
           AND [SPL].[YEAR] = @YEAR

        UPDATE [MTL]
           SET [MTL].[PER] = 1,
               [MTL].[YEAR] = [MTL].[YEAR] + 1
          FROM [dbo].[MatterLedger] AS [MTL]
         WHERE [MTL].[DATE] > @YEARENDDATE
           AND [MTL].[YEAR] = @YEAR

        UPDATE [BAH]
           SET [BAH].[PERNO] = 1,
               [BAH].[YEAR] = [BAH].[YEAR] + 1
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[DATE] > @YEARENDDATE
           AND [BAH].[YEAR] = @YEAR

        UPDATE [BAD]
           SET [BAD].[PERNO] = 1,
               [BAD].[YEAR] = [BAD].[YEAR] + 1
          FROM [dbo].[BatchDetails] AS [BAD]
         WHERE [BAD].[DATE] > @YEARENDDATE
           AND [BAD].[YEAR] = @YEAR

        UPDATE [NML]
           SET [NML].[PER] = 1,
               [NML].[YEAR] = [NML].[YEAR] + 1
          FROM [dbo].[NominalLedger] AS [NML]
         WHERE [NML].[DATE] > @YEARENDDATE
           AND [NML].[YEAR] = @YEAR

        IF @TIMECOSTING = 'Y'
        BEGIN
            /* The "ACTUAL" columns hold a clarion date, so I need to convert to DATETIME, add 1 year and then convert back to clarion */
            UPDATE [HAN]
               SET [HAN].[ACTUAL1]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL1], '18001228'))),
                   [HAN].[ACTUAL2]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL2], '18001228'))),
                   [HAN].[ACTUAL3]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL3], '18001228'))),
                   [HAN].[ACTUAL4]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL4], '18001228'))),
                   [HAN].[ACTUAL5]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL5], '18001228'))),
                   [HAN].[ACTUAL6]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL6], '18001228'))),
                   [HAN].[ACTUAL7]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL7], '18001228'))),
                   [HAN].[ACTUAL8]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL8], '18001228'))),
                   [HAN].[ACTUAL9]  = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL9], '18001228'))),
                   [HAN].[ACTUAL10] = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL10], '18001228'))),
                   [HAN].[ACTUAL11] = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL11], '18001228'))),
                   [HAN].[ACTUAL12] = DATEDIFF(DAY, '18001228', DATEADD(YEAR, 1, DATEADD(DAY, [HAN].[ACTUAL12], '18001228')))
              FROM [dbo].[Handlers] AS [HAN]
        END

        /* Third party balances */
        UPDATE [SUP]
           SET [SUP].[TPBAL] = ISNULL([BAH].[Balance], 0)
          FROM [dbo].[Suppliers] AS [SUP]
               LEFT OUTER JOIN (SELECT [BAH].[SUPP], SUM(ISNULL([BAH].[VALUE], 0)) AS [Balance]
                                  FROM [dbo].[BatchH] AS [BAH]
                                 WHERE [BAH].[DATE] > @YEARENDDATE
                                   AND [BAH].[YEAR] = @YEAR
                                       GROUP BY [BAH].[SUPP]) AS [BAH]
                            ON [BAH].[SUPP] = [SUP].[CODE]

        UPDATE [NOM]
           SET [NOM].[LASTYEAR1]  = [NOM].[MONTH1],
               [NOM].[LASTYEAR2]  = [NOM].[MONTH2],
               [NOM].[LASTYEAR3]  = [NOM].[MONTH3],
               [NOM].[LASTYEAR4]  = [NOM].[MONTH4],
               [NOM].[LASTYEAR5]  = [NOM].[MONTH5],
               [NOM].[LASTYEAR6]  = [NOM].[MONTH6],
               [NOM].[LASTYEAR7]  = [NOM].[MONTH7],
               [NOM].[LASTYEAR8]  = [NOM].[MONTH8],
               [NOM].[LASTYEAR9]  = [NOM].[MONTH9],
               [NOM].[LASTYEAR10] = [NOM].[MONTH10],
               [NOM].[LASTYEAR11] = [NOM].[MONTH11],
               [NOM].[LASTYEAR12] = [NOM].[MONTH12],
               [NOM].[MONTH2]  = 0,
               [NOM].[MONTH3]  = 0,
               [NOM].[MONTH4]  = 0,
               [NOM].[MONTH5]  = 0,
               [NOM].[MONTH6]  = 0,
               [NOM].[MONTH7]  = 0,
               [NOM].[MONTH9]  = 0,
               [NOM].[MONTH10] = 0,
               [NOM].[MONTH11] = 0,
               [NOM].[MONTH12] = 0
          FROM [dbo].[Nominal] AS [NOM]

        IF @UPDATEALLOCS = 'N'
        BEGIN
            UPDATE [NOM]
               SET [NOM].[BALANCE]     = 0,
                   [NOM].[CURRENCYBAL] = 0,
                   [NOM].[MONTH1]      = 0
              FROM [dbo].[Nominal] AS [NOM]
        END
        ELSE
        BEGIN
            /* Opening balances */
            DECLARE @BALANCEFORWARD TABLE (
                    [CODE]    VARCHAR(10),
                    [BRANCH]  VARCHAR(10),
                    [BALANCE] DECIMAL(19, 2),
                    [NARR]    VARCHAR(200))

            /* Bank forward balances */
            INSERT INTO @BALANCEFORWARD (
                   [CODE],
                   [BRANCH],
                   [BALANCE],
                   [NARR])
            SELECT [NOM].[CODE],
                   [NML].[BRANCH],
                   SUM(ISNULL([NML].[VALUE], 0)),
                   'Balance Forward' + 
                   CASE WHEN COALESCE([BRA].[DESCRIPTION], [NML].[BRANCH], '') = ''
                             THEN ''
                        ELSE ' for ' + ISNULL([BRA].[DESCRIPTION], [NML].[BRANCH]) END
              FROM [dbo].[Nominal] AS [NOM]
                   INNER JOIN [dbo].[NominalLedger] AS [NML]
                           ON [NML].[CODE] = [NOM].[CODE]
                   LEFT OUTER JOIN [dbo].[Branch] AS [BRA]
                                ON [NML].[BRANCH] = [BRA].[BRANCHCODE]
             WHERE [NML].[DATE] <= @YEARENDDATE
               AND [NOM].[PB] = 'B'
               AND [NML].[YEAR] = @YEAR
                   GROUP BY [NOM].[CODE],
                            [NML].[BRANCH],
                            [BRA].[DESCRIPTION]
            HAVING SUM(ISNULL([NML].[VALUE], 0)) <> 0

            /* Profit & loss */
            INSERT INTO @BALANCEFORWARD (
                   [CODE],
                   [BRANCH],
                   [BALANCE],
                   [NARR])
            SELECT @PL,
                   [NML].[BRANCH],
                   SUM(ISNULL([NML].[VALUE], 0)),
                   'Retained Profits Forward from ' + CONVERT(VARCHAR(4), 2020) + ' ' +
                   CASE WHEN COALESCE([BRA].[DESCRIPTION], [NML].[BRANCH], '') = ''
                             THEN ''
                        ELSE 'for ' + ISNULL([BRA].[DESCRIPTION], [NML].[BRANCH]) END
              FROM [dbo].[Nominal] AS [NOM]
                   INNER JOIN [dbo].[NominalLedger] AS [NML]
                           ON [NML].[CODE] = [NOM].[CODE]
                   LEFT OUTER JOIN [dbo].[Branch] AS [BRA]
                                ON [NML].[BRANCH] = [BRA].[BRANCHCODE]
             WHERE [NML].[DATE] <= @YEARENDDATE
               AND [NOM].[PB] = 'P'
               AND [NML].[YEAR] = @YEAR
                   GROUP BY [NML].[BRANCH],
                            [BRA].[DESCRIPTION]
            HAVING SUM(ISNULL([NML].[VALUE], 0)) <> 0

            INSERT INTO [dbo].[NominalLedger] (
                   [CODE],
                   [BRANCH],
                   [BATCHNO],
                   [PREF],
                   [DATE],
                   [REF],
                   [NARR],
                   [MATTER],
                   [SUPP],
                   [FEE],
                   [PER],
                   [YEAR],
                   [RECNO],
                   [ENTRYDATE],
                   [VALUE],
                   [CURRENCYVALUE])
            SELECT [TMP].[CODE],
                   [TMP].[BRANCH],
                   0,
                   0,
                   @SUBDATEFROM,
                   'B/F',
                   [TMP].[NARR],
                   '', /* MATTER */
                   '', /* SUPP */
                   '', /* FEE */
                   1,
                   @YEAR + 1,
                   1,
                   @TODAY,
                   [TMP].[BALANCE],
                   [TMP].[BALANCE] / @EICONVERT
                FROM @BALANCEFORWARD AS [TMP]

            UPDATE [NOM]
               SET [NOM].[BALANCE]     = ISNULL([NML].[BALANCE], 0),
                   [NOM].[CURRENCYBAL] = ISNULL([NML].[BALANCE], 0) / @EICONVERT,
                   [NOM].[MONTH1]      = ISNULL([NML].[BALANCE], 0),
                   [NOM].[BALANCEFWD]  = 0
              FROM [dbo].[Nominal] AS [NOM]
                   LEFT OUTER JOIN (SELECT [NML].[CODE],
                                           SUM(ISNULL([NML].[VALUE], 0)) AS [BALANCE]
                                      FROM [dbo].[NominalLedger] AS [NML]
                                     WHERE [NML].[YEAR] = @YEAR + 1
                                           GROUP BY [NML].[CODE]) AS [NML]
                                ON [NOM].[CODE] = [NML].[CODE]
        END
        
        IF @RECINSTALLED = 'Y' AND @KEEPNOMINALLEDGER = 0
        BEGIN
            /* OS fwd
                REC - RecOsTrans
                These are transactions which were not reconciled this year */
            INSERT INTO [dbo].[BankRecOutstandingTrans] (
                   [BANKAC],
                   [TYPE],
                   [DATE],
                   [REF],
                   [BATCH],
                   [PREF],
                   [NARR],
                   [VALUE],
                   [RECNO])
            SELECT [NML].[CODE],
                   [TYPE].[Value] AS [TYPE],
                   [NML].[DATE],
                   SUBSTRING([NML].[REF], 0, 8),
                   0,
                   [NML].[PREF],
                   SUBSTRING([NML].[NARR], 0, 60),
                   CASE WHEN [TYPE].[Value] = 'P'
                          OR ([TYPE].[Value] = 'R'
                          AND [NML].[CODE] = [BAH].[CLIENTBANK])
                             THEN [NML].[VALUE] * -1
                        ELSE [NML].[VALUE] END AS [VALUE],
                   [NML].[RECNO]
              FROM [dbo].[NominalLedger] AS [NML]
                   INNER JOIN [dbo].[Nominal] AS [NOM]
                           ON [NML].[CODE] = [NOM].[CODE]
                   INNER JOIN [dbo].[BatchH] AS [BAH]
                           ON [BAH].[BATCHNO] = [NML].[BATCHNO]
                   OUTER APPLY (SELECT CASE WHEN [BAH].[TYPE] = 'T'
                                                 THEN 'R'
                                            WHEN [BAH].[TYPE] = 'R'
                                             AND [NML].[CODE] = [BAH].[CLIENTBANK]
                                                 THEN 'P'
                                            WHEN [BAH].[TYPE] NOT IN ('P', 'R', 'T')
                                              OR [NML].[BATCHNO] = 0
                                                 THEN CASE WHEN [NML].[VALUE] < 0
                                                                THEN 'P'
                                                           ELSE 'R' END
                                            ELSE [BAH].[TYPE] END AS [Value]) AS [TYPE]
             WHERE [NML].[DATE] <= @YEARENDDATE
               AND [NML].[RECNO] <= 0
               AND [NOM].[TYPE] = 'BANK'
               AND [NML].[YEAR] = @YEAR
        END

        /* Delete nominal ledger for year we are closing */
        IF @KEEPNOMINALLEDGER = 0
        BEGIN
            DELETE [NML]
              FROM [dbo].[NominalLedger] AS [NML]
             WHERE [NML].[DATE] <= @YEARENDDATE
               AND [NML].[YEAR] = @YEAR
        END

        UPDATE [CON]
           SET [CON].[LASTBATCH]   = [CON].[LASTBATCH] + 1,
               [CON].[LASTPREF]    = [CON].[LASTPREF] + 1,
               [CON].[YEAR]        = [CON].[YEAR] + 1,
               [CON].[CURPER]      = 1,
               [CON].[PERIODEND]   = DATEDIFF(DAY, '18001228', @NEXTPERIODEND),
               [CON].[YearEndDate] = DATEADD(YEAR, 1, @YEARENDDATE)
          FROM [dbo].[control] AS [CON]

        INSERT INTO [dbo].[Log] (
               [DATE],
               [EVENT],
               [USER])
        SELECT @TODAY,
               'Year End ' + CONVERT(VARCHAR(24), GETDATE(), 113),
               @USER
        
        IF @TRANCOUNT = 0
            COMMIT TRANSACTION

    END TRY
    BEGIN CATCH
        DECLARE @ERROR   INT
        DECLARE @MESSAGE VARCHAR(4000)
        DECLARE @XSTATE  INT

        SELECT @ERROR   = ERROR_NUMBER(),
               @MESSAGE = ERROR_MESSAGE(),
               @XSTATE  = XACT_STATE()

        DECLARE @ERRMSG VARCHAR(2000)

        SET @ERRMSG = '0 - An error occurred in ky_NETYearEndProc. Please contact support.' + 
                      CHAR(13) + CHAR(10) + 
                      'On line ' + CONVERT(VARCHAR(10), ERROR_LINE()) + ': ' + 
                      CHAR(13) + CHAR(10) + 
                      @MESSAGE

        SELECT @ERRMSG

        IF @TRANCOUNT = 0
        BEGIN
            PRINT(3)
            ROLLBACK TRANSACTION
        END
        ELSE
        BEGIN
            IF @XSTATE <> -1
            BEGIN
                ROLLBACK TRANSACTION [YearEndTransaction]
            END
        END
                
        RAISERROR(@ERRMSG, 16, 1, @ERROR, @MESSAGE)
        
    END CATCH
    
    SET NOCOUNT OFF
END

GO

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

CREATE PROCEDURE [dbo].[KAAS_SAM_GetPaymentClearDate]
	   (@Date				DATE  = NULL,
	    @ClearDays			 INT  = 0,
		@Result	            DATE   OUTPUT)
AS
/*******************************************************************************************************
* Get Clear Date based on Payment method	                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SAM_GetPaymentClearDate]	        	     			           *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-11-08    vinodhkumar M        Created  
* 2021-09-07    Ghayathri.S.V        Modified - The input date format to the function parameter                                                         *
*******************************************************************************************************/
BEGIN
	 DECLARE  @InputDate  DATE
	     SET  @InputDate = DATEADD(DAY, DATEDIFF(DAY, 0, @Date), 0)
	  SELECT  @Result = [dbo].[ky_NETFNClearedDate](@InputDate, @ClearDays)
END

GO
IF OBJECT_ID(N'KAAS_SaveColumnChooserList', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_SaveColumnChooserList]
END
GO
CREATE PROCEDURE [dbo].[KAAS_SaveColumnChooserList]
		(
			@Mode				VARCHAR(4)     = '',
		    @HandlerCode		VARCHAR(50)    = '',
			@PageName			VARCHAR(50)    = '',       
			@DefaultColumns 	NVARCHAR(MAX)  = ''
		)
AS
/*******************************************************************************************************
* Save the Default ColumnChooser Column List                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SaveColumnChooserList]   			            				   *
*                                                                                                      *
* Modification History:                                                                                *
* Balamurugan			21-May-2021					Created                                            *
* Balamurugan			09-Mar-2022					Modified - Formatting                              *
 *******************************************************************************************************/
BEGIN
	SET NOCOUNT ON
		IF(@Mode='SAVE')
			BEGIN
			/*CHECK THE DATA ALREADY PRESENT OR NOT*/
				IF EXISTS
					(
							SELECT TOP 1 1 
							      FROM [dbo].[DefaultPageColumnsByHanlder] 
							     WHERE [HandlerCode] = @HandlerCode 
								   AND [PageName]    = @PageName		
					)
					BEGIN
								UPDATE [dbo].[DefaultPageColumnsByHanlder]
								   SET [DefaultColumns] = @DefaultColumns
								 WHERE [HandlerCode] = @HandlerCode 
								   AND [PageName]    = @PageName 

					END
				ELSE
					BEGIN
							    INSERT 
							      INTO [dbo].[DefaultPageColumnsByHanlder] 
									(   
									   [HandlerCode],
									   [PageName],
									   [DefaultColumns]
									)
							    VALUES    
								    (
									   @HandlerCode,
									   @PageName,
									   @DefaultColumns
									)
					END
			END
		IF(@Mode='VIEW')
			BEGIN
				SELECT [HandlerCode],
					   [PageName],
					   [DefaultColumns]
				  FROM [dbo].[DefaultPageColumnsByHanlder] 
				 WHERE [HandlerCode] = @HandlerCode 
				   AND [PageName]    = @PageName 
			END
	SET NOCOUNT OFF
END
GO


IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SetSAMClientToApprovedForMoneyLaundering' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SetSAMClientToApprovedForMoneyLaundering] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_SetSAMClientToApprovedForMoneyLaundering]
				(
					    @Result INT OUTPUT
				)
AS

/*******************************************************************************************************
* This stored procedure is used to SET MoneyLaudering is Approved for all client                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_SetSAMClientToApprovedForMoneyLaundering]      				   *
* Copied From			: [dbo].[ky_NETMATSetClientToApprovedForMoneyLaundering]                       *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-08-11    Balamurugan.C        Created                                                           *
* 2022-02-28    Balamurugan.C        Modified - Handled TCL Statements								   *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON
	  BEGIN TRY
		 BEGIN TRAN
			UPDATE [dbo].[Contacts] 
			   SET [Approved] = 1 
			 WHERE [Client]   = 'Y'

			   SET @Result = 1
	 		
			COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH		
    SET NOCOUNT OFF

END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_SetSAMMatterOutlayBudget' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_SetSAMMatterOutlayBudget] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_SetSAMMatterOutlayBudget] 
	(
       @OutlayAmount     DECIMAL(18,9),
       @Target           VARCHAR(30)
	)
AS
/***********************************************************************************
 * 																				   *
 * This stored procedure is used to set all matter outlaybudget is set value	   *
 *																				   *
 * Stored Procedure Name : [dbo].[KAAS_SetSAMMatterOutlayBudget]				   *
 * Copied From           : [dbo].[ky_netSetMatterOutlayBudget]					   *
 *																				   *
 * Modification History:														   *
 * 2021-08-11    Balamurugan.C            Created								   *
 * 2022-02-28    Balamurugan.C    Modified - Handled TCL Statements                *
 ***********************************************************************************/
BEGIN
    SET NOCOUNT ON
     	BEGIN TRY
		 BEGIN TRAN
			IF LOWER(ISNULL(@Target, '')) = 'all'
				BEGIN
					UPDATE [dbo].[Matters] 
					   SET [OutlayBud] = ISNULL(@OutlayAmount, 0)
				END
			 
			IF LOWER(ISNULL(@Target, '')) = 'nobudget'
				BEGIN
					UPDATE [MAT]
					   SET [MAT].[OutlayBud] = ISNULL(@OutlayAmount, 0)
					  FROM [dbo].[Matters] AS [MAT]
					 WHERE ISNULL([MAT].[OutlayBud], 0) = 0
				END
		
		COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH
    
    SET NOCOUNT OFF
END
GO

IF OBJECT_ID(N'KAAS_SPMaintainUpdateHandler', N'P') IS NOT NULL
BEGIN
    DROP PROCEDURE [dbo].[KAAS_SPMaintainUpdateHandler]
END
GO
CREATE PROCEDURE	[dbo].[KAAS_SPMaintainUpdateHandler]
      (
		   @XML                 NVARCHAR(MAX),
		   @SkipWelcomeScreen   BIT,
		   @Result				INT OUTPUT
	   )
AS
BEGIN
/*************************************************************************************************************
 *                                                                                                           *
 * [dbo].[KAAS_SPMaintainUpdateHandler]                                                                     *
 *                                                                                                           *
 * Description: This procedure is used to update handler information                                         *
 *                                                                                                           *
 *   *****************************************************************************************************   *
 *                                                                                                           *
 * Modification history:                                                                                     *
 * 2021-06-25  Natarajan S            Created																 *
 * 2021-06-29  Natarajan S			  Modified - Changed variables as per coding standard.					 *
 * 2021-12-17  Balamurugan.C          Mofified - Added Ouput parameter as mentioned in service               *
 * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                      *
 *************************************************************************************************************/
BEGIN TRY
   BEGIN TRAN
		DECLARE @iSL INT

		EXEC sp_xml_preparedocument @iSL OUTPUT, @XML

		DECLARE @COMMAND NVARCHAR(MAX)

		DECLARE @NEWHANDLERPHONES TABLE
			   ([Code]         VARCHAR(10)     PRIMARY KEY,
				[PhoneNo]      VARCHAR(50),
				[PhoneNumber]  VARCHAR(50))

		INSERT
		  INTO @NEWHANDLERPHONES
			  ([Code],
			   [PhoneNo],
			   [PhoneNumber])
		SELECT [Code],
			   [PhoneNo],
			   [PhoneNumber]
		  FROM OPENXML(@iSL, N'HAN')
		  WITH ([Code]                VARCHAR(10)         '@Code',
				[Phoneno]             VARCHAR(50)         '@Phoneno',
				[PhoneNumber]         VARCHAR(50)         '@PhoneNumber') [DTA]

		UPDATE @NEWHANDLERPHONES
		   SET [Phoneno] = ISNULL([PhoneNumber], '')
		 WHERE ISNULL([PhoneNo], '') = ''

		UPDATE @NEWHANDLERPHONES
		   SET [PhoneNumber] = ISNULL([Phoneno], '')
		 WHERE ISNULL([PhoneNumber], '') = ''

		UPDATE @NEWHANDLERPHONES
		   SET [PhoneNumber] = ISNULL([Phoneno], '')
		 WHERE [PhoneNumber] <> [Phoneno]

		SELECT @COMMAND = N'
		DECLARE @Exists BIT

		INSERT
		  INTO [dbo].[Handlers]
			  ([Code])
		SELECT [NEW].[Code]
		  FROM (SELECT ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Code]), '''', '''''')) + N''' [Code]) [NEW]
			   LEFT OUTER JOIN [dbo].[Handlers] [HAN]
							ON [HAN].[Code] = [NEW].[Code]
		 WHERE [HAN].[Code] IS NULL

		UPDATE [HAN]
		   SET '
			   + CASE WHEN [DTA].[Team] IS NULL
						   THEN N''
					  ELSE N'
			   [Team] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Team]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[TeamCode] IS NULL
						   THEN N''
					  ELSE N',
			   [TeamCode] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[TeamCode]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Dept] IS NULL
						   THEN N''
					  ELSE N',
			   [Dept] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Dept]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Type] IS NULL
						   THEN N''
					  ELSE N',
			   [Type] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Type]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Name] IS NULL
						   THEN N''
					  WHEN RTRIM([DTA].[Name]) = RTRIM(ISNULL([HAN].[Name], ''))
						   THEN N''
					  ELSE N',
			   [Name] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Name]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Rate] IS NULL
						   THEN N''
					  ELSE N',
			   [Rate] = ' + CONVERT(NVARCHAR(200), [DTA].[Rate]) END
			   + CASE WHEN [DTA].[Budget1] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget1] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget1]) END
			   + CASE WHEN [DTA].[Budget2] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget2] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget2]) END
			   + CASE WHEN [DTA].[Budget3] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget3] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget3]) END
			   + CASE WHEN [DTA].[Budget4] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget4] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget4]) END
			   + CASE WHEN [DTA].[Budget5] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget5] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget5]) END
			   + CASE WHEN [DTA].[Budget6] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget6] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget6]) END
			   + CASE WHEN [DTA].[Budget7] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget7] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget7]) END
			   + CASE WHEN [DTA].[Budget8] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget8] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget8]) END
			   + CASE WHEN [DTA].[Budget9] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget9] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget9]) END
			   + CASE WHEN [DTA].[Budget10] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget10] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget10]) END
			   + CASE WHEN [DTA].[Budget11] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget11] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget11]) END
			   + CASE WHEN [DTA].[Budget12] IS NULL
						   THEN N''
					  ELSE N',
			   [Budget12] = ' + CONVERT(NVARCHAR(200), [DTA].[Budget12]) END
			   + CASE WHEN [DTA].[Actual1] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual1] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual1])) END
			   + CASE WHEN [DTA].[Actual2] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual2] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual2])) END
			   + CASE WHEN [DTA].[Actual3] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual3] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual3])) END
			   + CASE WHEN [DTA].[Actual4] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual4] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual4])) END
			   + CASE WHEN [DTA].[Actual5] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual5] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual5])) END
			   + CASE WHEN [DTA].[Actual6] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual6] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual6])) END
			   + CASE WHEN [DTA].[Actual7] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual7] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual7])) END
			   + CASE WHEN [DTA].[Actual8] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual8] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual8])) END
			   + CASE WHEN [DTA].[Actual9] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual9] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual9])) END
			   + CASE WHEN [DTA].[Actual10] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual10] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual10])) END
			   + CASE WHEN [DTA].[Actual11] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual11] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual11])) END
			   + CASE WHEN [DTA].[Actual12] IS NULL
						   THEN N''
					  ELSE N',
			   [Actual12] = ' + CONVERT(NVARCHAR(200), DATEDIFF(DAY, CONVERT(DATETIME, '18001228'), [DTA].[Actual12])) END
			   + CASE WHEN [DTA].[TempCalc] IS NULL
						   THEN N''
					  ELSE N',
			   [TempCalc] = ' + CONVERT(NVARCHAR(200), [DTA].[TempCalc]) END
			   + CASE WHEN [DTA].[Logon] IS NULL
						   THEN N''
					  ELSE N',
			   [Logon] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Logon]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[MailAddress] IS NULL
						   THEN N''
					  ELSE N',
			   [MailAddress] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[MailAddress]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[TimeCoster] IS NULL
						   THEN N''
					  ELSE N',
			   [TimeCoster] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[TimeCoster]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[TEAMLEADER] IS NULL
						   THEN N''
					  ELSE N',
			   [TEAMLEADER] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[TEAMLEADER]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[NoRecentMatters] IS NULL
						   THEN N''
					  ELSE N',
			   [NoRecentMatters] = ' + CONVERT(NVARCHAR(200), [DTA].[NoRecentMatters]) END
			   + CASE WHEN [DTA].[DefaultTask] IS NULL
						   THEN N',
			   [DefaultTask] = '''''
					  ELSE N',
			   [DefaultTask] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[DefaultTask]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[ExchangeAlias] IS NULL
						   THEN N''
					  ELSE N',
			   [ExchangeAlias] = ''' + CONVERT(NVARCHAR(300), REPLACE(RTRIM([DTA].[ExchangeAlias]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Rate1] IS NULL
						   THEN N''
					  ELSE N',
			   [Rate1] = ' + CONVERT(NVARCHAR(200), [DTA].[Rate1]) END
			   + CASE WHEN [DTA].[Rate2] IS NULL
						   THEN N''
					  ELSE N',
			   [Rate2] = ' + CONVERT(NVARCHAR(200), [DTA].[Rate2]) END
			   + CASE WHEN [DTA].[Rate3] IS NULL
						   THEN N''
					  ELSE N',
			   [Rate3] = ' + CONVERT(NVARCHAR(200), [DTA].[Rate3]) END
			   + CASE WHEN [DTA].[Rate4] IS NULL
						   THEN N''
					  ELSE N',
			   [Rate4] = ' + CONVERT(NVARCHAR(200), [DTA].[Rate4]) END
			   + CASE WHEN [DTA].[Rate5] IS NULL
						   THEN N''
					  ELSE N',
			   [Rate5] = ' + CONVERT(NVARCHAR(200), [DTA].[Rate5]) END
			   + CASE WHEN [DTA].[Signature] IS NULL
						   THEN N''
					  ELSE N',
			   [Signature] = ''' + CONVERT(NVARCHAR(MAX), REPLACE(RTRIM([DTA].[Signature]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Email] IS NULL
						   THEN N''
					  ELSE N',
			   [Email] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Email]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Retired] IS NULL
						   THEN N''
					  ELSE N',
			   [Retired] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Retired]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Delegate] IS NULL
						   THEN N''
					  ELSE N',
			   [Delegate] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Delegate]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[OutlookView] IS NULL
						   THEN N''
					  ELSE N',
			   [OutlookView] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[OutlookView]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[AutoLaunchTimer] IS NULL
						   THEN N''
					  ELSE N',
			   [AutoLaunchTimer] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[AutoLaunchTimer]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[Phoneno] IS NULL
						   THEN N''
					  ELSE N',
			   [Phoneno] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([HPN].[Phoneno]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[PhoneNumber] IS NULL
						   THEN N''
					  ELSE N',
			   [PhoneNumber] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([HPN].[Phoneno]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[AutoLaunchKPI] IS NULL
						   THEN N''
					  ELSE N',
			   [AutoLaunchKPI] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[AutoLaunchKPI]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[AxleNumber] IS NULL
						   THEN N''
					  ELSE N',
			   [AxleNumber] = ' + CONVERT(NVARCHAR(200), [DTA].[AxleNumber]) END
			   + CASE WHEN [DTA].[UnitCost] IS NULL
						   THEN N''
					  ELSE N',
			   [UnitCost] = ' + CONVERT(NVARCHAR(200), [DTA].[UnitCost]) END
			   + CASE WHEN [DTA].[TargetRecov] IS NULL
						   THEN N''
					  ELSE N',
			   [TargetRecov] = ' + CONVERT(NVARCHAR(200), [DTA].[TargetRecov]) END
			   + CASE WHEN [DTA].[Branch] IS NULL
						   THEN N''
					  ELSE N',
			   [Branch] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Branch]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[FaxNumber] IS NULL
						   THEN N''
					  ELSE N',
			   [FaxNumber] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[FaxNumber]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[ChargeGroup] IS NULL
						   THEN N''
					  ELSE N',
			   [ChargeGroup] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[ChargeGroup]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[EmployeeRefNo] IS NULL
						   THEN N''
					  ELSE N',
			   [EmployeeRefNo] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[EmployeeRefNo]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[ISChargeable] IS NULL
						   THEN N''
					  ELSE N',
			   [ISChargeable] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[ISChargeable]), '''', '''''')) + N'''' END
			   + CASE WHEN RTRIM(ISNULL([DTA].[TradingName], '')) = ''
						   THEN N',
			   [TradingName] = RTRIM(ISNULL([CON].[Name], ''''))'
					  ELSE N',
			   [TradingName] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[TradingName]), '''', '''''')) + N'''' END
			   + CASE WHEN [DTA].[JobTitle] IS NULL
						   THEN N''
					  ELSE N',
			   [JobTitle] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[JobTitle]), '''', '''''')) + N'''' END
			   + N'
		  FROM [dbo].[Handlers] [HAN]
			   CROSS APPLY (SELECT TOP 1 [Name] FROM [dbo].[Control]) [CON]
		 WHERE [HAN].[Code] = ''' + CONVERT(NVARCHAR(200), REPLACE(RTRIM([DTA].[Code]), '''', '''''')) + N''''
		  FROM OPENXML(@iSL, N'HAN')
		  WITH ([Code]                VARCHAR(10)         '@Code',
				[Team]                VARCHAR(10)         '@Team',
				[TeamCode]            CHAR(1)             '@TeamCode',
				[Dept]                VARCHAR(5)          '@Dept',
				[Type]                CHAR(1)             '@Type',
				[Name]                VARCHAR(30)         '@Name',
				[Rate]                DECIMAL(10,2)       '@Rate',
				[Budget1]             DECIMAL(13,2)       '@Budget1',
				[Budget2]             DECIMAL(13,2)       '@Budget2',
				[Budget3]             DECIMAL(13,2)       '@Budget3',
				[Budget4]             DECIMAL(13,2)       '@Budget4',
				[Budget5]             DECIMAL(13,2)       '@Budget5',
				[Budget6]             DECIMAL(13,2)       '@Budget6',
				[Budget7]             DECIMAL(13,2)       '@Budget7',
				[Budget8]             DECIMAL(13,2)       '@Budget8',
				[Budget9]             DECIMAL(13,2)       '@Budget9',
				[Budget10]            DECIMAL(13,2)       '@Budget10',
				[Budget11]            DECIMAL(13,2)       '@Budget11',
				[Budget12]            DECIMAL(13,2)       '@Budget12',
				[Actual1]             DATETIME            '@Actual1',
				[Actual2]             DATETIME            '@Actual2',
				[Actual3]             DATETIME            '@Actual3',
				[Actual4]             DATETIME            '@Actual4',
				[Actual5]             DATETIME            '@Actual5',
				[Actual6]             DATETIME            '@Actual6',
				[Actual7]             DATETIME            '@Actual7',
				[Actual8]             DATETIME            '@Actual8',
				[Actual9]             DATETIME            '@Actual9',
				[Actual10]            DATETIME            '@Actual10',
				[Actual11]            DATETIME            '@Actual11',
				[Actual12]            DATETIME            '@Actual12',
				[TempCalc]            DECIMAL(13,2)       '@TempCalc',
				[Logon]               VARCHAR(10)         '@Logon',
				[MailAddress]         VARCHAR(20)         '@MailAddress',
				[TimeCoster]          CHAR(1)             '@TimeCoster',
				[TeamLeader]          VARCHAR(10)         '@TeamLeader',
				[NoRecentMatters]     INT                 '@NoRecentMatters',
				[DefaultTask]         CHAR(6)             '@DefaultTask',
				[ExchangeAlias]       VARCHAR(256)        '@ExchangeAlias',
				[Rate1]               DECIMAL(7,2)        '@Rate1',
				[Rate2]               DECIMAL(7,2)        '@Rate2',
				[Rate3]               DECIMAL(7,2)        '@Rate3',
				[Rate4]               DECIMAL(7,2)        '@Rate4',
				[Rate5]               DECIMAL(7,2)        '@Rate5',
				[Signature]           VARCHAR(MAX)        '@Signature',
				[Email]               VARCHAR(100)        '@Email',
				[Retired]             CHAR(1)             '@Retired',
				[Delegate]            VARCHAR(50)         '@Delegate',
				[OutlookView]         CHAR(1)             '@OutlookView',
				[AutoLaunchTimer]     CHAR(1)             '@AutoLaunchTimer',
				[Phoneno]             VARCHAR(50)         '@Phoneno',
				[PhoneNumber]         VARCHAR(50)         '@PhoneNumber',
				[AutoLaunchKPI]       CHAR(1)             '@AutoLaunchKPI',
				[AxleNumber]          INT                 '@AxleNumber',
				[UnitCost]            DECIMAL(14,2)       '@UnitCost',
				[TargetRecov]         DECIMAL(7,2)        '@TargetRecov',
				[Branch]              CHAR(3)             '@Branch',
				[FaxNumber]           VARCHAR(50)         '@FaxNumber',
				[ChargeGroup]         CHAR(5)             '@ChargeGroup',
				[EmployeeRefNo]       VARCHAR(10)         '@EmployeeRefNo',
				[ISChargeable]        VARCHAR(1)          '@ISChargeable',
				[TradingName]         VARCHAR(200)        '@TradingName',
				[JobTitle]            VARCHAR(100)        '@JobTitle',
				[SyncRetire]          bit                 '@SyncRetire') [DTA]
			   INNER JOIN @NEWHANDLERPHONES [HPN]
					   ON [HPN].[Code] = [DTA].[Code]
			   LEFT OUTER JOIN [dbo].[Handlers] [HAN]
							ON [HAN].[Code] = [DTA].[Code]

		SET @COMMAND = REPLACE(@COMMAND, N'SET ,' + NCHAR(13) + NCHAR(10) + N'       ', N'SET ')
		
		EXEC (@COMMAND)

		UPDATE [FEC]
		   SET [FEC].[Retired] = [HAN].[Retired]
		  FROM OPENXML(@iSL, N'HAN')
		  WITH ([Code]                VARCHAR(10)         '@Code',
				[SyncRetire]          bit                 '@SyncRetire') [DTA]
			   INNER JOIN [dbo].[Handlers] [HAN]
					   ON [HAN].[Code] = [DTA].[Code]
			   INNER JOIN [dbo].[FeeEarnerCodes] [FEC]
					   ON [FEC].[Code] = [DTA].[Code]
		 WHERE ISNULL([DTA].[SyncRetire], CONVERT(BIT, 0)) = 1

		INSERT
		  INTO [dbo].[UserSettings]
			  ([Handler],
			   [Key],
			   [Value])
		SELECT [DTA].[Code],
			   'NewMatterWizardDontShowWelcomeScreen',
			   CONVERT(NVARCHAR(MAX), ISNULL(@SkipWelcomeScreen, CONVERT(BIT, 0)))
		  FROM OPENXML(@iSL, N'HAN')
		  WITH ([Code]                VARCHAR(10)         '@Code') [DTA]
			   LEFT OUTER JOIN [dbo].[UserSettings] [SET]
							ON [SET].[Handler] = [DTA].[Code]
						   AND [SET].[Key] = 'NewMatterWizardDontShowWelcomeScreen'
		 WHERE [SET].[SettingID] IS NULL

		UPDATE [SET]
		   SET [SET].[Value] = CONVERT(NVARCHAR(MAX), ISNULL(@SkipWelcomeScreen, CONVERT(BIT, 0)))
		  FROM OPENXML(@iSL, N'HAN')
		  WITH ([Code]                VARCHAR(10)         '@Code') [DTA]
			   INNER JOIN [dbo].[UserSettings] [SET]
							ON [SET].[Handler] = [DTA].[Code]
						   AND [SET].[Key] = 'NewMatterWizardDontShowWelcomeScreen'

		-- KEYD-6912 - Insert new name into HandlerNames table, but only update now if the setting is turned off (default) 
		IF NOT EXISTS 
		  (SELECT TOP 1 1
			 FROM [dbo].[Settings] AS [SET]
			WHERE [SET].[KeyName] = 'DelayHandlerNameUpdate' 
			  AND [SET].[KeyValue] = 'True')
		BEGIN
			UPDATE [HN]
			   SET [HN].[Name] = ISNULL([DTA].[Name], '')
			  FROM OPENXML(@iSL, N'HAN')
			  WITH ([Code]                VARCHAR(10)         '@Code',
					[TeamCode]            CHAR(1)             '@TeamCode',
					[Name]                VARCHAR(30)         '@Name') [DTA]
				   INNER JOIN [dbo].[HandlerNames] AS [HN]
						   ON [HN].[Code] = [DTA].[Code]
			 --WHERE ISNULL([DTA].[TeamCode], '') <> 'Y'
		END

		INSERT INTO [dbo].[HandlerNames] (
			   [Code],
			   [Name])
		SELECT [DTA].[Code],
			   ISNULL([DTA].[Name], '')
		  FROM OPENXML(@iSL, N'HAN')
		  WITH ([Code]                VARCHAR(10)         '@Code',
				[TeamCode]            CHAR(1)             '@TeamCode',
				[Name]                VARCHAR(30)         '@Name') [DTA]
			   LEFT OUTER JOIN [dbo].[HandlerNames] AS [HN]
							ON [HN].[Code] = [DTA].[Code]
		 WHERE [HN].[Code] IS NULL   
		   AND ISNULL([DTA].[TeamCode], '') <> 'Y'

		EXEC sp_xml_removedocument @iSL
			
		COMMIT TRAN
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END
	END CATCH
END


GO
IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_UndoBankReconciliationTransaction' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_UndoBankReconciliationTransaction] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_UndoBankReconciliationTransaction]
	( 
		@BankAc	           VARCHAR(10)   = '',
		@RecNo             INT           = 0,
		@Handler           VARCHAR(20)   = ''
	)
AS
/*******************************************************************************************************
* Undo Bank Reconciliation Transaction																   *
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_UndoBankReconciliationTransaction]   			                   *
*                                                                                                      *
* Modification History:                                                                                *
* 2022-02-07    Balamurugan C        Created                                                           *
* 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 * 
*******************************************************************************************************/
BEGIN
 BEGIN TRY
   BEGIN TRAN

		DECLARE @DateComplete DATE = NULL;
		 SELECT @DateComplete = [DateComplete]
		   FROM [dbo].[BankRecHistory]
		 WHERE [BankAc] = @BankAc
		   AND [RecNo]  = @RecNo
	
		IF(@DateComplete IS NULL)
			BEGIN
				/* UPDATE OUTSTANDING TRANSACTION TABLE */
				UPDATE [dbo].[BankRecOutstandingTrans]
				   SET [RecNo]  = 0 
				 WHERE [BankAc] = @BankAc 
				   AND [RecNo]  = @RecNo

				/* UPDATE NOMINAL LEDGER RECON NUMBER*/

				UPDATE [dbo].[NominalLedger] 
				   SET [RecNo] = ISNULL((SELECT [OsRecNo] 
										   FROM [dbo].[BankRecTransactions] 
										  WHERE [NomTransId] = [NominalLedger].[RecordId] 
											AND [Pref]       = [NominalLedger].[PRef]),0) 
				 WHERE [Code]=@BankAc 
				   AND ABS([RecNo]) = @RecNo

				/* DELETE BANK RECON TRANACTION*/

				DELETE [dbo].[BankRecTransactions] 
				 WHERE [BankAc] = @BankAc
				  AND  [RecNo]  = @RecNo

				/* DELETE RECON HISTORY TABLE*/
				DELETE [dbo].[BankRecHistory]
				 WHERE [BankAc] = @BankAc
				   AND [RecNo]  = @RecNo
				   AND [DateComplete] IS NULL
			END

   COMMIT
 END TRY
 BEGIN CATCH
  ROLLBACK TRAN
      INSERT 
		INTO [dbo].[Log] 
			 (
				  [Date],
				  [User],
				  [Event]
			 )
	  VALUES (
				  GETDATE(),
				  @Handler,
				 'Bank Rec No: ' + @RecNo + ' for Bank Acc ' + @BankAc + ' not undone'
			 )
	 DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
 END CATCH
END
GO

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

CREATE PROCEDURE
		[dbo].[KAAS_UpdateContactLastMatter] (
       @CLIENTCODE VARCHAR(20))
AS
/*****************************************************************
 * Stored Procedure Name :  [dbo].[KAAS_UpdateContactLastMatter]
 * Copied From : [dbo].[ky_NETUpdateContactLastMatter]
 *
 * Recalculates the LastMatter and OpenMatters for a given Contact
 *
 * Modification History:                                                              *
 * 2022-05-31     Ghayathri.S.V        Created  
 *
 *****************************************************************/
BEGIN
    SET NOCOUNT ON

    /* Update our contact's LastMatter and OpenMatters */
    UPDATE [CNT]
       SET [CNT].[LastMatter] = [MAT].[LastMatter],
           [CNT].[OpenMatters] = [MAT].[OpenMatters],
           [CNT].[Client] = 'Y'
      FROM [dbo].[Contacts] AS [CNT]
           INNER JOIN (SELECT [MAT].[ClientCode],
                              MAX(CASE WHEN PATINDEX('%[^0-9]%', [MAT].[Matter]) <= 0 THEN CONVERT(INT, [MAT].[Matter]) ELSE 0 END) AS [LastMatter],
                              SUM(CASE WHEN [MAT].[Closed] <> 'Y' THEN 1 ELSE 0 END) AS [OpenMatters]
                         FROM [dbo].[matters] AS [MAT]
                        WHERE [MAT].[ClientCode] = @CLIENTCODE
                              GROUP BY [MAT].[ClientCode]) AS [MAT]
                   ON [MAT].[ClientCode] = [CNT].[Code]

    SET NOCOUNT OFF
END

GO



IF OBJECT_ID(N'KAAS_UpdateCreditorsList',N'P')IS NOT NULL
	DROP PROCEDURE [dbo].[KAAS_UpdateCreditorsList]
GO
CREATE PROCEDURE [dbo].[KAAS_UpdateCreditorsList]
				(@PayValue decimal(11,2),
				 @RecordId decimal(17,0))
AS

/*******************************************************************************************************
* Updates the creditors list                                                                           * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[KAAS_UpdateCreditorsList]   								    	   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-10-05    Revathy D        Created                                                               *
* 2022-02-28    Balamurugan.C    Modified - Handled TCL Statements                                     *
 *******************************************************************************************************/
    
BEGIN
	SET NOCOUNT ON
	  BEGIN TRY
		BEGIN TRAN
			UPDATE [dbo].[CreditorsList] 
			   SET [PAYVALUE]   = @PayValue
			 WHERE [RECORDID]	= @RecordId 
		       
			COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH
    SET NOCOUNT OFF
END

GO






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

CREATE PROCEDURE
       [dbo].[KAAS_UpdateEFTDefaults]
      (
		@EFTYN					CHAR(1),
		@BANKFILENAME			VARCHAR(50),
		@LOCATION				VARCHAR(100),
		@FILENUMBER				VARCHAR(100),
		@EFTLIMIT				VARCHAR(100),
		@EFTTANSACTIONLIMIT		VARCHAR(100)
	  )
AS
/*************************************************************************************************************                                                *
 * Modification History                                                                                      *
 * 2024-03-19   Ghayathri S.V     Created																     *
 *************************************************************************************************************/
BEGIN

SET NOCOUNT ON

UPDATE	EFTDetails 
   SET	EFTYN = @EFTYN, 
		EFTLimit = @EFTLIMIT, 
		EFTTransactionLimit = @EFTTANSACTIONLIMIT, 
		BankFileName = @BANKFILENAME, 
		Location = @LOCATION, 
		FileNumber = @FILENUMBER
WHERE   RecordID = 1

SET NOCOUNT OFF

END
GO




IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_UpdatePostingIssueInvoive' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_UpdatePostingIssueInvoive] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_UpdatePostingIssueInvoive]
	( 
		@PostedBatchNo	   INT         = 0,
		@PostedType		   VARCHAR(1)  = '',
		@IsPostingFwd      VARCHAR(1)  = '',
		@HandlerName       VARCHAR(20) = ''  
	)
AS
 /*******************************************************************************************************
 * Update Posting Logic for Issue Invoive                                                               * 
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMMultiPayment]   			            	        *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-11-23    Balamurugan C        Created                                                           *
 * 2022-02-17    Balamurugan C        Modified - Chnaged Logic as per SAM                               *
 * 2022-02-21    Balamurugan C        Modified - Handled Current Period and Period End Date             *
 * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
 *******************************************************************************************************/

--DECLARE
--  @PostedBatchNo	   INT         = 1513,
--  @PostedType		   VARCHAR(1)  = 'I',
--  @IsPostingFwd      VARCHAR(1)  = 'N',
--  @HandlerName       VARCHAR(20) = 'admin';

 BEGIN
 	BEGIN TRY
		BEGIN TRAN
		/*UPDATE CUR PER NO IN BATCH HEADER*/
		UPDATE [dbo].[BatchH]
		   SET [PerNo]   = CASE WHEN @IsPostingFwd = 'Y' THEN [PerNo] + 1 ELSE [PerNo] END
		 WHERE [BatchNo] = @PostedBatchNo
	

		/*UPDATE CUR PER NO IN BATCH DETAILS*/
		UPDATE [dbo].[BatchDetails]
		   SET [PerNo]   = CASE WHEN @IsPostingFwd = 'Y' THEN [PerNo] + 1 ELSE [PerNo] END
		 WHERE [BatchNo] = @PostedBatchNo   


		 /*UPDATE PERIOD END DATE FOR BATCH DETAILS*/
		DECLARE @ControlPeriodEnd     DATE =  NULL,
				@BatchDetailDate      DATE =  NULL;
		(SELECT @ControlPeriodEnd = DATEADD(dd,  (SELECT [PERIODEND] FROM [dbo].[Control] WITH (NOLOCK)), '18001228') )
		(SELECT @BatchDetailDate = [Date] FROM [dbo].[BatchDetails])

			 IF(@BatchDetailDate > @ControlPeriodEnd AND @IsPostingFwd='N')
				BEGIN
					UPDATE [dbo].[BatchDetails]
					   SET [Date]    = @ControlPeriodEnd
					 WHERE [BatchNo] = @PostedBatchNo   
				END
				--	/* SELECT BATCH HEADER AND INSERT INTO TABLE VARIBALE*
	DECLARE @tempBatchH TABLE 
	        ([BatchNo]        [int]            NOT NULL,
			 [Type]           [char](1)        NULL,
	         [Code]           [char](10)       NULL,	
			 [Ref]            [char](10)       NULL,
			 [Date]           [datetime]       NULL,
			 [Matter]         [varchar](20)    NULL,
			 [SubTotal]       [decimal](17, 2) NULL,
			 [Supp]           [char](10)       NULL,
			 [Narr]           [char](150)      NULL,
			 [Value]          [decimal](17, 2) NULL,
			 [Currency]       [varchar](10)    NULL,
			 [CurrencyValue]  [decimal](17, 2) NULL,	
			 [Posted]         [char](1)        NULL,
			 [Branch]         [varchar](3)     NULL,	
			 [PerNo]          [smallint]       NULL,
			 [Year]           [smallint]       NULL,
			 [EntryDate]      [datetime]       NULL,
			 [RecNo]          [int]            NULL,
			 [ChequeReqNo]    [int]            NULL,	
			 [UserCode]       [char](8)        NULL,
			 [Pref]           [int]            NULL,
			 [ClientAc]       [char](1)        NULL,
			 [EFT]            [char](1)        NOT NULL,
			 [ClientBank]     [char](10)       NULL,
			 [ThirdParty]     [char](1)        NULL,
			 [Payee]          [char](60)       NULL,
			 [EFTSent]        [char](1)        NOT NULL,
			 [PayClient]      [char](1)        NOT NULL,
			 [OnceOffPayment] [char](1)        NOT NULL,
			 [ClientCode]     [varchar](10)    NULL,
			 [Feetotal]		  [decimal](17, 2) NULL,
			 [Outlaytotal]	  [decimal](17, 2) NULL,
			 [VatTotal]		  [decimal](17, 2) NULL,
			 [WriteDown]      [datetime]       NULL,
		     [WriteBackHours] [decimal](7, 2)  NULL,
		     [WriteBackValue] [decimal](13, 2) NULL,
			 [CreditInvoiceNo][int]            NULL,
			 [Invcr]          [char](1)        NULL,
			 [Fee]            [varchar](10)    NULL,
			 [PaymentMethod]  [int]			   NULL,
		     [ClearedDate]    [datetime]       NULL,
			 [SingleLine]     [varchar](1)     NULL,
			 [DraftBillNo]	  [int]            NULL)

	INSERT INTO @tempBatchH 
		 SELECT [BAH].[BatchNo], 
				RTRIM(ISNULL([BAH].[Type],'')), 
				[BAH].[Code], 
				RTRIM(ISNULL([BAH].[Ref],'')), 
				dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([BAH].[Date], @HandlerName),  
				[BAH].[Matter], 
				[BAH].[SUBTOT],
				[BAH].[Supp], 
				[BAH].[Narr], 
				[BAH].[Value],
				[BAH].[Currency],
				[BAH].[CurrencyValue],
				[BAH].[Posted],   
				[BAH].[Branch],
				[BAH].[PerNo], 
				[BAH].[Year],
				dbo.KEYHM_FNConvertUTCDateToTargetTimeZone([BAH].[EntryDate], @HandlerName) AS [EntryDate],
				[BAH].[RecNo], 
				[BAH].[ChequeReqNo],
				[BAH].[UserCode],
				[BAH].[Pref],
				[BAH].[ClientAc],
				[BAH].[EFTYorN],
				[BAH].[CLIENTBANK],
				[BAH].[ThirdParty],
				[BAH].[Payee], 
				[BAH].[EFTSent], 
				[BAH].[PayClient],
				[BAH].[OnceOffPayment],
				[BAH].[ClientCode],
				[BAH].[FEETOT],
				[BAH].[OUTLAYTOT],
				[BAH].[VATTOT],
				[BAH].[WRITEDOWN],
		        [BAH].[WRITEBACKHOURS],
		        [BAH].[WRITEBACKVALUE],
				[BAH].[CREDITINVOICENO],
				[BAH].[INVCR],
				[BAH].[FEE],
				[BAH].[PaymentMethod],
				[BAH].[ClearedDate],
				[BAH].[SingleLine],
				[BAH].[DraftBillNo]
		   FROM [dbo].[BatchH] [BAH] WITH(NOLOCK)
		  WHERE [BAH].[BatchNo] = @PostedBatchNo

	/* SELECT BATCH DETAILS AND INSERT INTO TEMP TABLE VARIBLE*/

	DECLARE @tempBatchDetails TABLE
  (
			 [BatchNo]         [INT]			NOT NULL,
			 [Type]            [CHAR](1)		NULL,
			 [Code]            [CHAR](10)		NULL,
			 [Pref]            [INT]			NULL,
			 [Ref]             [CHAR](10)		NULL,
			 [Date]            [DATETIME]		NULL,
			 [Fee]             [VARCHAR](10)	NULL,
			 [Branch]          [VARCHAR](3)		NULL,
			 [Narr]            [CHAR](100)		NULL,
			 [Matter]          [VARCHAR](20)	NULL,
			 [Supp]            [CHAR](10)		NULL,
			 [Value]           [DECIMAL](17, 2) NULL, 
			 [VatCode]         [CHAR](1)		NULL,
			 [VatVal]          [DECIMAL](17, 2) NULL,
			 [ClientYN]        [CHAR](1)		NULL,
			 [Outlay]          [CHAR](1)		NULL,
			 [Pending]         [CHAR](1)		NULL,
			 [Year]            [SMALLINT]		NULL,
			 [PerNo]           [SMALLINT]		NULL,
			 [EntryCurrency]   [CHAR](1)		NULL,
			 [CurrencyValue]   [DECIMAL](17, 2) NULL,
			 [CurrencyVat]     [DECIMAL](17, 2) NULL,
			 [OutlayCode]      [CHAR](4)		NULL,
			 [ThirdParty]      [CHAR](1)		NULL,
			 [Payee]           [CHAR](60)		NULL,
			 [HeadPref]        [INT]			NULL,
			 [HeadBatch]       [INT]			NULL,
			 [AllocBatch]      [INT]			NULL,
			 [AllocPref]       [INT]			NULL,
			 [AllocRef]        [CHAR](10)		NULL,
			 [AllocValue]      [DECIMAL](17, 2) NULL,
			 [AllocWriteOff]   [CHAR](1)		NULL,
			 [Psupp]           [CHAR](10)		NULL,
			 [Undetaking]      [SMALLINT]		NULL,
			 [CaseAssCode]     [VARCHAR](6)		NULL,
			 [OnceOffPayment]  [CHAR](1)		NOT NULL,
			 [PayClient]       [CHAR](1)		NOT NULL,
			 [ClientCode]      [VARCHAR](10)	NULL,
			 [EFTemailYorN]    [CHAR](1)		NOT NULL,
			 [RegisteredPost]  [INT]			NULL,
			 [PreBilledOutlay] [BIT]			NOT NULL,
			 [KeyId]		   [INT]			NOT NULL
  ) 
		INSERT 
		  INTO @tempBatchDetails
	    SELECT [BATCHNO],
			   [TYPE],           
			   [CODE],            
			   [PREF],            
			   [REF],             
			   [DATE],            
			   [FEE],             
			   [BRANCH],          
			   [NARR],            
			   [MATTER],          
			   [SUPP],            
			   [VALUE],     
			   [VATCODE],         
			   [VATVAL],          
			   [CLIENTYN],       
			   [OUTLAY],          
			   [PENDING],         
			   [YEAR],            
			   [PERNO],           
			   [ENTRYCURRENCY],   
			   [CURRENCYVALUE],   
			   [CURRENCYVAT],     
			   [OUTLAYCODE],      
			   [THIRDPARTY],      
			   [PAYEE],           
			   [HEADPREF],        
			   [HEADBATCH],       
			   [ALLOCBATCH],      
			   [ALLOCPREF],       
			   [ALLOCREF],        
			   [ALLOCVALUE],      
			   [ALLOCWRITEOFF],   
			   [PSUPP],           
			   [UNDETAKING],            
			   [CaseAssCode],     
			   [OnceOffPayment],  
			   [PayClient],       
			   [ClientCode],      
			   [EFTEmailYorN],    
			   [RegisteredPost],  
			   [PreBilledOutlay],
			   [KEYID]
		  FROM [dbo].[BatchDetails] WITH(NOLOCK)
		 WHERE [BATCHNO] = @PostedBatchNo

	   DECLARE @LastBatch           INT           = 0,
			   @LastPref            INT           = 0,
			   @CurPer              INT           = 0,
			   @InvCr               VARCHAR(1)    = '',
			   @InvCrValue          INT           = 0,
			   @OutlayTot           DECIMAL(17,2) = 0,
			   @SingleLine          VARCHAR(1)    = '',
			   @DepositAcct         VARCHAR(1)    = '',
			   @DeFaultOutlay       VARCHAR(10)   = '',
			   @VATControlCode      VARCHAR(10)   = '',
			   @DebtorsControlCode  VARCHAR(10)   = '',
			   @TimeCosting         VARCHAR(1)    = '',
			   @BatchFeeTotal		DECIMAL(17,2) = 0,
			   @TimeTotal			DECIMAL(17,2) = 0,
			   @ChargeTotal         DECIMAL(17,2) = 0,
			   @TimeValue           DECIMAL(17,2) = 0,
			   @BHSupp              VARCHAR(10)   = '',
			   @MatterCode          VARCHAR(10)   = '',
			   @CreditInvoiceNo     INT           = 0,
			   @DraftBillNo			INT           = 0;     

/*FLAG VALUES*/
		SELECT @DefaultOutlay      = [Outlay],
			   @VATControlCode     = [Vat],
			   @DebtorsControlCode = [Debtors],
			   @TimeCosting		   = [TimeCosting]
		  FROM [dbo].[Control] WITH(NOLOCK)

		SELECT @InvCr		    = [INVCR],
		       @OutlayTot       = [Outlaytotal],
			   @SingleLine      = [SingleLine],
			   @BatchFeeTotal   = [Feetotal],
			   @BHSupp          = [Supp],
			   @MatterCode      = [Matter],
			   @CreditInvoiceNo = [CreditInvoiceNo],
			   @DraftBillNo     = [DraftBillNo],
			   @CurPer          = [PerNo]
		  FROM @tempBatchH 
		   

IF(@InvCr = 'C')
	    BEGIN
			SET @InvCrValue = -1;
		END
ELSE
		BEGIN
			SET @InvCrValue = 1;
		END

/* INSERT INTO MATTER LEDGER TABLE - BATCH HEADER */
IF(@OutlayTot<>0 AND @SingleLine = 'Y')
	BEGIN
		INSERT 
		  INTO [dbo].[MatterLedger]
			(
			   [Matter],
			   [BatchNo],
			   [Pref],
			   [Date],
			   [Ref],
			   [Narr],
			   [ValueD],
			   [ValueO],
			   [ValueC],
			   [Fee],
			   [Per],
			   [Year],
			   [EntryDate],
			   [Client],
			   [ValueCC],
			   [ValueCD],
			   [DepositType],
			   [CurValueD],
			   [CurValueO],
			   [CurValueC],
			   [CurValueCC],
			   [CurValueCD],
			   [Billed],
			   [BillingYear],
			   [BillingPeriod],
			   [BillingDate],
			   [BilledOutlayValue],
			   [InvoiceNo],
			   [IncludeInBill],
			   [ClearedDate]
			 )				  	   
			 (
		 SELECT [TBH].[Matter]		
			   ,[TBH].[BatchNo]
			   ,[TBH].[Pref]		
			   ,[TBH].[Date]		
			   ,[TBH].[Ref]		
			   ,'To Invoice' + ISNULL([TBH].[Ref],'')		
			   ,0.00		
			   ,[Outlaytotal] * @InvCrValue		
			   ,0.00     
			   ,[TBH].[Fee]		
			   ,[TBH].[PerNo]		
			   ,[TBH].[Year]		
			   ,CAST(GETDATE() AS DATE)		
			   ,SUBSTRING([TBH].[Matter], 1, 6)
			   ,0.00
			   ,0.00
			   ,''		 
			   ,0.00		 
			   ,CASE WHEN [TBH].[Currency] = 'I'
			    THEN ([TBH].[Outlaytotal] / 0.787564) * -1 * @InvCrValue
				ELSE ([TBH].[Outlaytotal] * 0.787564) * -1 * @InvCrValue
				END AS [CurValueC]
			   ,0.00
			   ,0.00
			   ,0.00
			   ,''			 
			   ,0			 
			   ,0			 
			   ,null		 
			   ,0
			   ,0			 
			   ,0			 
			   ,[TBH].[ClearedDate]
		  FROM @tempBatchH [TBH]
			 )

/* UPDATE MATTER LEDGER VALUE*/
		UPDATE [MAL]
		   SET [MAL].[BilledOutlayValue] = [MAL].[ValueO]
		  FROM [dbo].[MatterLedger] [MAL]
		  JOIN @tempBatchH [TBH]
		    ON [MAL].[Matter] = [TBH].[Matter]
		   AND [MAL].[BatchNo] = [TBH].[BatchNo]

/*UPDATE MATTER TABLE FOR OUTLAY  */
	 UPDATE [MAT]
		SET [MAT].[OutlayBal]       = ISNULL([MAT].[OutlayBal],0) + ISNULL([TBH].[Outlaytotal] * -1 * @InvCrValue,0), 
		    [MAT].[CurOutlayBal]    = ISNULL([MAT].[CurOutlayBal],0) + ISNULL([MAL].[CurValueO] * -1 * @InvCrValue,0),
			[MAT].[OutlayBalFwd]    = CASE WHEN @IsPostingFwd='Y' 
										   THEN ISNULL([MAT].[OutlayBalFwd],0) + ISNULL([TBH].[Value] * -1 * @InvCrValue,0)
										   ELSE [MAT].[OutlayBalFwd] END,
			[MAT].[CurOutlayBalFwd] = CASE WHEN @IsPostingFwd='Y' 
										   THEN ISNULL([MAT].[CurOutlayBalFwd],0) + ISNULL([MAL].[CurValueO] * -1 * @InvCrValue,0)
										   ELSE [MAT].[CurOutlayBalFwd] END
	   FROM [dbo].[matters] [MAT]
 INNER JOIN @tempBatchH [TBH]
		 ON [MAT].[Code] = [TBH].[Matter]
 INNER JOIN [dbo].[MatterLedger] [MAL]
         ON [MAL].[Matter] = [TBH].[Matter]
		AND [MAL].[BatchNo] = [TBH].[BatchNo]

/* UPDATE CONTACTS TABLE - OUTLAY*/
	 UPDATE [CON]
		SET [CON].[OutlayBal]    = ISNULL([CON].[OutlayBal],0) + ISNULL([TBH].[Outlaytotal] * -1 * @InvCrValue,0), 
			[CON].[CurOutlayBal] =  ISNULL([CON].[CurOutlayBal],0) + ISNULL([MAL].[CurValueO] * -1 * @InvCrValue,0)
		FROM [dbo].[Contacts] [CON]
 INNER JOIN @tempBatchH [TBH]
		 ON [CON].[Code] = SUBSTRING([TBH].[Matter], 1, 6)
 INNER JOIN [dbo].[MatterLedger] [MAL]
         ON [MAL].[Matter] = [TBH].[Matter]
		AND [MAL].[BatchNo] = [TBH].[BatchNo]

/* INSERT INTO NOMIANL LEDGER */
	 INSERT 
	   INTO [dbo].[NominalLedger]
		(
			[Code],
			[Branch],
			[BatchNo],
			[Pref],
			[Date],
			[Ref],
			[Narr],
			[Matter],
			[Supp],
			[Fee],
			[Value],
			[CurrencyValue],
			[Per],
			[Year],
			[EntryDate],
			[RecNo],
			[ClearedDate]
		)
		(
	 SELECT @DefaultOutlay  AS [Code],
			[TBH].[Branch],
			[TBH].[BatchNo],
			[TBH].[Pref],
			[TBH].[Date],
			[TBH].[Ref],
			'To Invoive '+ ISNULL([TBH].[Ref],'') AS [Narr],
			[TBH].[Matter],
			CASE WHEN [TBH].[Supp]='N' THEN '' ELSE [TBH].[Supp] END,
			'' AS [Fee],
			ISNULL([TBH].[Outlaytotal] * -1 * @InvCrValue,0) AS [Value],
			ISNULL([MAL].[CurValueO] * -1 * @InvCrValue,0) AS [CurrencyValue],
			[TBH].[PerNo],
			[TBH].[Year],
			CAST(GETDATE() AS DATE) AS [EntryDate],
			[TBH].[RecNo],
			[TBH].[ClearedDate]
	   FROM @tempBatchH [TBH]
 INNER JOIN [dbo].[MatterLedger] [MAL]
         ON [MAL].[Matter] = [TBH].[Matter]
		AND [MAL].[BatchNo] = [TBH].[BatchNo]
		  )

/* UPDATE NOMINAL BALANCE FOR OUTLAY */

	 UPDATE [NOM]
	    SET [NOM].[Balance]		    = ISNULL([NOM].[Balance],0)+([TBH].[Outlaytotal] * -1 * @InvCrValue),
		    [NOM].[CurrencyBal]     = ISNULL([NOM].[CurrencyBal],0)+([MAL].[CurValueO] * -1 * @InvCrValue),
		    [NOM].[BalanceFwd]      = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[BalanceFwd],0)+([TBH].[Outlaytotal] * -1 * @InvCrValue)
		    								ELSE ISNULL([NOM].[BalanceFwd],0) END,
		    [NOM].[CurrencyBalFwd]  = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[CurrencyBalFwd],0)+([MAL].[CurValueO] * -1 * @InvCrValue)
		    								ELSE ISNULL([NOM].[CurrencyBalFwd],0) END,
		    [NOM].[Month1]			= CASE WHEN @CurPer = 1  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month1]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month1]  END,
		    [NOM].[Month2]			= CASE WHEN @CurPer = 2  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month2]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month2]  END,
		    [NOM].[Month3]			= CASE WHEN @CurPer = 3  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month3]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month3]  END,
		    [NOM].[Month4]			= CASE WHEN @CurPer = 4  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month4]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month4]  END,
		    [NOM].[Month5]			= CASE WHEN @CurPer = 5  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month5]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month5]  END,
		    [NOM].[Month6]			= CASE WHEN @CurPer = 6  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month6]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month6]  END,
		    [NOM].[Month7]			= CASE WHEN @CurPer = 7  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month7]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month7]  END,
		    [NOM].[Month8]			= CASE WHEN @CurPer = 8  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month8]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month8]  END,
		    [NOM].[Month9]			= CASE WHEN @CurPer = 9  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month9]+([TBH].[Outlaytotal] * -1 * @InvCrValue)  ELSE  [NOM].[Month9]  END,
		    [NOM].[Month10]			= CASE WHEN @CurPer = 10 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month10]+([TBH].[Outlaytotal] * -1 * @InvCrValue) ELSE  [NOM].[Month10] END,
		    [NOM].[Month11]			= CASE WHEN @CurPer = 11 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month11]+([TBH].[Outlaytotal] * -1 * @InvCrValue) ELSE  [NOM].[Month11] END,
		    [NOM].[Month12]			= CASE WHEN @CurPer = 12 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month12]+([TBH].[Outlaytotal] * -1 * @InvCrValue) ELSE  [NOM].[Month12] END
	   FROM [dbo].[Nominal] [NOM]
	   JOIN @tempBatchH [TBH]
	     ON [NOM].[Code] = @DefaultOutlay
INNER JOIN [dbo].[MatterLedger] [MAL]
         ON [MAL].[Matter] = [TBH].[Matter]
		AND [MAL].[BatchNo] = [TBH].[BatchNo]

	END

/* INSERT INTO MATTER LEDGER -BATCH DETAILS */

			INSERT 
		  INTO [dbo].[MatterLedger]
			(
			   [Matter],
			   [BatchNo],
			   [Pref],
			   [Date],
			   [Ref],
			   [Narr],
			   [ValueD],
			   [ValueO],
			   [ValueC],
			   [Fee],
			   [Per],
			   [Year],
			   [EntryDate],
			   [Client],
			   [ValueCC],
			   [ValueCD],
			   [DepositType],
			   [CurValueD],
			   [CurValueO],
			   [CurValueC],
			   [CurValueCC],
			   [CurValueCD],
			   [Billed],
			   [BillingYear],
			   [BillingPeriod],
			   [BillingDate],
			   [BilledOutlayValue],
			   [InvoiceNo],
			   [IncludeInBill],
			   [ClearedDate]
			 )				  	   
			 (
		 SELECT [TBH].[Matter]		
			   ,[TBD].[BatchNo]
			   ,[TBD].[Pref]		
			   ,[TBD].[Date]		
			   ,[TBD].[Ref]		
			   ,CASE WHEN [TBH].[Invcr] ='C'
			    THEN 'From Cr. Note ' + ISNULL(RTRIM([TBH].[Ref]),'')
				ELSE 'To Inv ' + ISNULL(RTRIM([TBH].[Ref]),'') + ' ' + ISNULL(RTRIM([TBD].[Narr]),'')
				END AS [Narr]
			   ,0.00
			   ,[TBD].[Value] *-1* @InvCrValue
			   ,0.00     
			   ,[TBD].[Fee]		
			   ,[TBH].[PerNo]		
			   ,[TBH].[Year]		
			   ,CAST(GETDATE() AS DATE) AS [EntryDate]		
			   ,SUBSTRING([TBH].[Matter], 1, 6)
			   ,0.00
			   ,0.00
			   ,''		 
			   ,0.00		 
			   ,[TBD].[CurrencyValue] *-1* @InvCrValue
			   ,0.00
			   ,0.00
			   ,0.00
			   ,''			 
			   ,0			 
			   ,0			 
			   ,null		 
			   ,0
			   ,0			 
			   ,0			 
			   ,[TBH].[ClearedDate]
		  FROM @tempBatchDetails [TBD]
	INNER JOIN @tempBatchH [TBH]
	        ON [TBH].[BatchNo] = [TBD].[BatchNo]
		 WHERE [TBD].[Outlay] = 'O'
			 )

/* UPDATE MATTER LEDGER VALUE*/
		UPDATE [MAL]
		   SET [MAL].[BilledOutlayValue] = [MAL].[ValueO]
		  FROM [dbo].[MatterLedger] [MAL]
		  JOIN @tempBatchH [TBH]
		    ON [MAL].[Matter] = [TBH].[Matter]
		   AND [MAL].[BatchNo] = [TBH].[BatchNo]


/*UPDATE MATTER TABLE FOR OUTLAY  */
	 UPDATE [MAT]
		SET [MAT].[OutlayBal]       = ISNULL([MAT].[OutlayBal],0) + ISNULL([TBD].[Value] *-1 * @InvCrValue,0),
		    [MAT].[CurOutlayBal]    = ISNULL([MAT].[CurOutlayBal],0) + ISNULL([TBD].[CurrencyValue] * -1 * @InvCrValue,0),
			[MAT].[OutlayBalFwd]    = CASE WHEN @IsPostingFwd='Y' 
										   THEN ISNULL([MAT].[OutlayBalFwd],0) + ISNULL([TBD].[Value] * -1 * @InvCrValue,0)
										   ELSE [MAT].[OutlayBalFwd] END,
			[MAT].[CurOutlayBalFwd] = CASE WHEN @IsPostingFwd='Y' 
										   THEN ISNULL([MAT].[CurOutlayBalFwd],0) + ISNULL([TBD].[CurrencyValue] * -1 * @InvCrValue,0)
										   ELSE [MAT].[CurOutlayBalFwd] END
	   FROM [dbo].[matters] [MAT]
	 INNER JOIN @tempBatchDetails [TBD]
		 ON [MAT].[Code] = (SELECT DISTINCT [IBH].[Matter] 
		                      FROM @tempBatchH [IBH]
							  JOIN @tempBatchDetails [IBD]
							    ON [IBD].[BatchNo] = [IBH].[BatchNo] 
							)
	  WHERE [TBD].[Outlay] = 'O'

/*UPDATE CONTACT TABLE FOR OUTLAY  */
	 UPDATE [CON]
		SET [CON].[OutlayBal]    = ISNULL([CON].[OutlayBal],0) + ISNULL([TBD].[Value] * -1 * @InvCrValue,0), 
			[CON].[CurOutlayBal] =  ISNULL([CON].[CurOutlayBal],0) + ISNULL([TBD].[CurrencyValue] * -1 * @InvCrValue,0)
		FROM [dbo].[Contacts] [CON]
 INNER JOIN @tempBatchH [TBH]
		 ON [CON].[Code] = SUBSTRING([TBH].[Matter], 1, 6)
 INNER JOIN @tempBatchDetails [TBD]
         ON [TBD].[BatchNo] = [TBH].[BatchNo]
	  WHERE [TBD].[Outlay] = 'O'

/* INSERT NOMINAL LEDGER  FOR DETAILS LINE INCLUDING CORRESPODING VAT*/

			DECLARE @tempNominalLedger TABLE
				  (
						[Code]			        VARCHAR(10)   NULL,
						[Branch]	            VARCHAR(3)	  NULL,
						[BatchNo]	            INT			  NULL,
						[Pref]			        INT			  NULL,
						[Date]			        DATETIME	  NULL,
						[Ref]			        VARCHAR(10)	  NULL,
						[Narr]			        VARCHAR(100)  NULL,
						[Matter]		        VARCHAR(20)	  NULL,
						[Supp]			        VARCHAR(10)	  NULL,
						[Fee]			        VARCHAR(10)	  NULL,
						[Value]			        DECIMAL(17,2) NULL,
						[CurrencyValue]	        DECIMAL(17,2) NULL,
						[Per]			        SMALLINT	  NULL,
						[Year]			        SMALLINT	  NULL,
						[EntryDate]		        DATETIME	  NULL,	
						[RecNo]			        INT			  NULL,
						[ClearedDate]	        DATETIME	  NULL,
						[VatCode]			    VARCHAR(20)	  NULL,
						[VatCodeValue]          DECIMAL(17,2) NULL,
						[VatCodeCurrencyVat]    DECIMAL(17,2) NULL
				  )
			INSERT
			  INTO @tempNominalLedger
				SELECT [TBD].CODE,
					   [TBD].BRANCH,	
					   [TBD].BATCHNO,
					   [TBD].PREF,
					   [TBD].[DATE],
					   [TBD].REF,
					   [TBD].NARR,
					   [TBD].MATTER,
					   [TBD].SUPP,
					   [TBD].FEE,
				       [TBD].[Value] * -1 *@InvCrValue AS [Value],
					   [TBD].[CurrencyValue] * -1 * @InvCrValue AS [CurrencyValue],
					   [TBD].PERNO,
					   [TBD].[YEAR],
					   CAST(GETDATE() AS DATE) AS [EntryDate],
					   [TBH].RecNo,
					   [TBH].[ClearedDate],
					   @VATControlCode AS [VatCode],
					   [TBD].[VatVal] *-1 * @InvCrValue AS [VatCodeValue],
					   [TBD].[CurrencyVat] * -1 * @InvCrValue AS [VatCodeCurrencyVat]
				  FROM @tempBatchDetails [TBD]
			 LEFT JOIN @tempBatchH [TBH] 
					ON [TBH].[BatchNo]=[TBD].[BatchNo]
	
					INSERT 
					  INTO [dbo].[NominalLedger]
						 (
						   [Code],
						   [Branch],
						   [BatchNo],
						   [Pref],
						   [Date],
						   [Ref],
						   [Narr],
						   [Matter],
						   [Supp],
						   [Fee],
						   [Value],
						   [CurrencyValue],
						   [Per],
						   [Year],
						   [EntryDate],
						   [RecNo],
						   [ClearedDate]
						 )
						 (
					SELECT CA.Code,
						   CA.Branch,
						   CA.BatchNo,
						   CA.Pref,
						   CA.[Date],
						   CA.Ref,
						   CA.Narr,
						   CA.Matter,
						   CA.Supp,
						   CA.Fee,
						   CA.[Value],
						   CA.[CurrencyValue],
						   CA.Per,
						   CA.[Year],
						   CA.[EntryDate],
						   CA.RecNo,
						   CA.ClearedDate
					  FROM @tempNominalLedger
			   CROSS APPLY (
						  VALUES (Code,BatchNo,Branch,Pref,[Date],Ref,Narr,Matter,Supp,Fee,[Value],[CurrencyValue],Per,[Year],[EntryDate],RecNo,ClearedDate),
								 (VATCode,BatchNo,Branch,Pref,[Date],Ref,'VAT on Invoice/Cr Note '+ ISNULL(Ref,''),Matter,Supp,Fee,VatCodeValue,VatCodeCurrencyVat,Per,[Year],[EntryDate],RecNo,ClearedDate)
						   ) 
							  AS CA (Code,BatchNo,Branch,Pref,[Date],Ref,Narr,Matter,Supp,Fee,[Value],[CurrencyValue],Per,[Year],[EntryDate],RecNo,ClearedDate)
							)

/* INSERT INTO MATTER LEDGER - DEBTORS LOGIC*/

			INSERT 
		  INTO [dbo].[MatterLedger]
			(
			   [Matter],
			   [BatchNo],
			   [Pref],
			   [Date],
			   [Ref],
			   [Narr],
			   [ValueD],
			   [ValueO],
			   [ValueC],
			   [Fee],
			   [Per],
			   [Year],
			   [EntryDate],
			   [Client],
			   [ValueCC],
			   [ValueCD],
			   [DepositType],
			   [CurValueD],
			   [CurValueO],
			   [CurValueC],
			   [CurValueCC],
			   [CurValueCD],
			   [Billed],
			   [BillingYear],
			   [BillingPeriod],
			   [BillingDate],
			   [BilledOutlayValue],
			   [InvoiceNo],
			   [IncludeInBill],
			   [ClearedDate]
			 )				  	   
			 (
		 SELECT [TBH].[Matter]		
			   ,[TBH].[BatchNo]
			   ,[TBH].[Pref]		
			   ,[TBH].[Date]		
			   ,[TBH].[Ref]		
			   ,CASE WHEN [TBH].[Invcr] = 'C'
			    THEN 'Cr. Note:  Fees:' + CONVERT(VARCHAR,CONVERT(DECIMAL(17,2),[TBH].[Feetotal])) 
				+ ' Outlay:' + CONVERT(VARCHAR,CONVERT(DECIMAL(17,2),[TBH].[Outlaytotal])) 
				+ ' VAT:' + CONVERT(VARCHAR,CONVERT(DECIMAL(17,2),[TBH].[VatTotal])) 
				ELSE 'Invoice:  Fees:' + CONVERT(VARCHAR,CONVERT(DECIMAL(17,2),[TBH].[Feetotal])) 
				+ ' Outlay:' + CONVERT(VARCHAR,CONVERT(DECIMAL(17,2),[TBH].[Outlaytotal])) 
				+ ' VAT:' + CONVERT(VARCHAR,CONVERT(DECIMAL(17,2),[TBH].[VatTotal])) 
				END AS [Narr]
			   ,[TBH].[Value] * @InvCrValue
			   ,0.00
			   ,0.00     
			   ,[TBH].[Fee]		
			   ,[TBH].[PerNo]		
			   ,[TBH].[Year]		
			   ,CAST(GETDATE() AS DATE)		
			   ,SUBSTRING([TBH].[Matter], 1, 6)
			   ,0.00
			   ,0.00
			   ,''		 
			   ,[TBH].[CurrencyValue] * @InvCrValue
			   ,0.00
			   ,0.00
			   ,0.00
			   ,0.00
			   ,''			 
			   ,0			 
			   ,0			 
			   ,null		 
			   ,0 
			   ,0			 
			   ,0			 
			   ,[TBH].[ClearedDate]
		  FROM @tempBatchH [TBH]
			 )

/* UPDATE MATTER LEDGER VALUE*/
		UPDATE [MAL]
		   SET [MAL].[BilledOutlayValue] = [MAL].[ValueO]
		  FROM [dbo].[MatterLedger] [MAL]
		  JOIN @tempBatchH [TBH]
		    ON [MAL].[Matter] = [TBH].[Matter]
		   AND [MAL].[BatchNo] = [TBH].[BatchNo]


/* UPDATE MATTER TABLE DEBTORS*/

	 UPDATE [MAT]
		SET [MAT].[DebtBal]       = ISNULL([MAT].[DebtBal],0) + ISNULL([TBH].[Value] * @InvCrValue ,0),
			[MAT].[CurDebtBal]    = ISNULL([MAT].[DebtBal],0) * 0.787564,
		    [MAT].[DebtBalFwd]    = CASE WHEN  @IsPostingFwd='Y' 
									   THEN ISNULL([MAT].[DebtBalFwd],0) + ISNULL([TBH].[Value] * @InvCrValue,0)
									   ELSE ISNULL([MAT].[DebtBalFwd],0) END,
			[MAT].[CurDebtBalFwd] = CASE WHEN  @IsPostingFwd='Y' 
										THEN ISNULL([MAT].[DebtBalFwd] * 0.787564,0)
										ELSE ISNULL([MAT].[CurDebtBalFwd],0) END,
			[MAT].[FNL_Date]      = 0,
			[MAT].[FNL_Name]      = '',
			[MAT].[FNL_Address]   = '',
			[MAT].[FNL_Fees]      = 0,
            [MAT].[FNL_Outlay]    = 0,
            [MAT].[FNL_VAT]       = 0,
            [MAT].[FNL_Total]     = 0,
			[MAT].[LastAct]       = CAST(GETDATE() AS DATE),
			[MAT].[LastActType]   = 'Inv/CrNote',
			[MAT].[EstFee]        = 0,
            [MAT].[ExpBillD]      = 0,
            [MAT].[ExpPayD]       = [TBH].[Date] + 30
	   FROM [dbo].[matters] [MAT]
 INNER JOIN @tempBatchH [TBH]
		 ON [MAT].[Code] = [TBH].[Matter]

/* UPDATE CONTACT FOR DEBTORS*/

	 UPDATE [CON]
		SET [CON].[BillBal]    = [CON].[BillBal] + ISNULL([TBH].[Value] * @InvCrValue,0), 
			[CON].[CurBillBal] =  [CON].[CurBillBal] + ISNULL([TBH].[CurrencyValue] * @InvCrValue,0)
	   FROM [dbo].[Contacts] [CON]
 INNER JOIN @tempBatchH [TBH]
		 ON [CON].[Code] = SUBSTRING([TBH].[Matter], 1, 6)

/* INSERT NOMINAL LEDGER FOR DEBTORS */

	 INSERT 
	   INTO [dbo].[NominalLedger]
		(
			[Code],
			[Branch],
			[BatchNo],
			[Pref],
			[Date],
			[Ref],
			[Narr],
			[Matter],
			[Supp],
			[Fee],
			[Value],
			[CurrencyValue],
			[Per],
			[Year],
			[EntryDate],
			[RecNo],
			[ClearedDate]
		)
		(
	 SELECT @DebtorsControlCode  AS [Code],
			[TBH].[Branch],
			[TBH].[BatchNo],
			[TBH].[Pref],
			[TBH].[Date],
			[TBH].[Ref],
			[TBH].[Narr],
			[TBH].[Matter],
			CASE WHEN [TBH].[Supp]='N' THEN '' ELSE [TBH].[Supp] END,
			[TBH].[Fee],
			ISNULL([TBH].[Value] * @InvCrValue,0) AS [Value],
			ISNULL([TBH].[CurrencyValue] * @InvCrValue,0) AS [CurrencyValue],
			[TBH].[PerNo],
			[TBH].[Year],
			CAST(GETDATE() AS DATE) AS [EntryDate],
			[TBH].[RecNo],
			[TBH].[ClearedDate]
	   FROM @tempBatchH [TBH]
		  )

/* UPDATE NOMINAL BALANCE FOR DEBTORS */

	 UPDATE [NOM]
	    SET [NOM].[Balance]		    = ISNULL([NOM].[Balance],0)+([TBH].[Value] * @InvCrValue),
		    [NOM].[CurrencyBal]     = ISNULL([NOM].[CurrencyBal],0)+([TBH].[CurrencyValue] * @InvCrValue),
		    [NOM].[BalanceFwd]      = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[BalanceFwd],0)+([TBH].[Value] * @InvCrValue)
		    								ELSE ISNULL([NOM].[BalanceFwd],0) END,
		    [NOM].[CurrencyBalFwd]  = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[CurrencyBalFwd],0)+([TBH].[CurrencyValue] * @InvCrValue)
		    								ELSE ISNULL([NOM].[CurrencyBalFwd],0) END,
		    [NOM].[Month1]			= CASE WHEN @CurPer = 1  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month1]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month1]  END,
		    [NOM].[Month2]			= CASE WHEN @CurPer = 2  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month2]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month2]  END,
		    [NOM].[Month3]			= CASE WHEN @CurPer = 3  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month3]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month3]  END,
		    [NOM].[Month4]			= CASE WHEN @CurPer = 4  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month4]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month4]  END,
		    [NOM].[Month5]			= CASE WHEN @CurPer = 5  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month5]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month5]  END,
		    [NOM].[Month6]			= CASE WHEN @CurPer = 6  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month6]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month6]  END,
		    [NOM].[Month7]			= CASE WHEN @CurPer = 7  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month7]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month7]  END,
		    [NOM].[Month8]			= CASE WHEN @CurPer = 8  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month8]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month8]  END,
		    [NOM].[Month9]			= CASE WHEN @CurPer = 9  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month9]+([TBH].[Value] * @InvCrValue)  ELSE  [NOM].[Month9]  END,
		    [NOM].[Month10]			= CASE WHEN @CurPer = 10 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month10]+([TBH].[Value] * @InvCrValue) ELSE  [NOM].[Month10] END,
		    [NOM].[Month11]			= CASE WHEN @CurPer = 11 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month11]+([TBH].[Value] * @InvCrValue) ELSE  [NOM].[Month11] END,
		    [NOM].[Month12]			= CASE WHEN @CurPer = 12 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month12]+([TBH].[Value] * @InvCrValue) ELSE  [NOM].[Month12] END
	   FROM [dbo].[Nominal] [NOM]
	   JOIN @tempBatchH [TBH]
	     ON [NOM].[Code] = @DebtorsControlCode

/* INSERT DEBTORS LEDGER */
	INSERT
		INTO [dbo].[DebtorsLedger]
		(  [Matter],
			[Type],
			[Client],
			[Date],
			[Ref],
			[BatchNo],
			[Pref],
			[Narr],
			[Original],
			[OsValue],
			[OrFees],
			[OrOutlay],
			[OrVat],
			[OsFees],
			[OsOutlay],
			[OsVat],
			[Per],
			[Year]
		)
		(  
	 SELECT [TBH].[Matter],
			[TBH].[Type],
			SUBSTRING([TBH].[Matter], 1, 6) AS [Client],
			[TBH].[Date],
			[TBH].[Ref],
			[TBH].[BatchNo],
			[TBH].[Pref],
			[MAL].[Narr],
			[TBH].[Value]       * @InvCrValue  AS [Original],
			[TBH].[Value]	    * @InvCrValue  AS [OsValue],
			[TBH].[Feetotal]    * @InvCrValue  AS [OrFees],
			[TBH].[Outlaytotal] * @InvCrValue  AS [OrOutlay],
			[TBH].[VatTotal]	* @InvCrValue  AS [OrVat],
			[TBH].[Feetotal]	* @InvCrValue  AS [OsFees],
			[TBH].[Outlaytotal] * @InvCrValue  AS [OsOutlay],
			[TBH].[VatTotal]	* @InvCrValue  AS [OsVat],
			[TBH].[PerNo]	                   AS [Per],
			[TBH].[Year]
	   FROM @tempBatchH [TBH]
	   JOIN [dbo].[MatterLedger] [MAL] WITH(NOLOCK)
	     ON [MAL].[BatchNo] = [TBH].[BatchNo]
		AND [MAL].[Matter]  = [TBH].[Matter]
		AND [MAL].[ValueD]  <> 0
		)

/* UPDATE DEBTORS LEDGER VAT CODE*/
	 UPDATE [DBL]
	    SET [DBL].[VatCode] = [TBD].[VatCode]
	   FROM [dbo].[DebtorsLedger] [DBL]
	   JOIN @tempBatchDetails [TBD]
	     ON [TBD].[BatchNo] = [DBL].[BatchNo]
	  WHERE [TBD].[Outlay]  = 'F'

/* UPDATE DEBTORS LEDGER VAT CODE*/
	 UPDATE [DBL]
	    SET [DBL].[VatCode] = [TBD].[VatCode]
	   FROM [dbo].[DebtorsLedger] [DBL]
	   JOIN @tempBatchDetails [TBD]
	     ON [TBD].[BatchNo] = [DBL].[BatchNo]
	  WHERE [TBD].[Outlay]  = 'O'
/* INSERT INTO COST TRANSFER GATHERING IF IT IS THRID PARTY */

	INSERT
	  INTO [dbo].[CostTransGathering]
	   (
		   [Date],
		   [Matter],
		   [Value],
		   [EntryCurrency],
		   [CurrencyValue],
		   [AllocBatch],
		   [AllocPRef],
		   [AllocRef],
		   [AllocValue],
		   [AllocWriteOff] 
	   )
	   (
	SELECT [TBH].[Date],
		   [TBH].[Matter],
		   [TBH].[Value],
		   [TBH].[Currency],
		   [TBH].[CurrencyValue],
		   [TBH].[BatchNo],
		   [TBH].[PRef],
		   [TBH].[Ref],
		   [TBH].[Value],
		   'N'AS [AllocWriteOff]
	  FROM @tempBatchH [TBH]
	 WHERE ISNULL([TBH].[ThirdParty],'')='Y'
	    )

/* TIME COSTING LOGIC*/
IF(@TimeCosting = 'Y' AND @BatchFeeTotal<>0)
	BEGIN
		IF(@InvCr = 'C')
			BEGIN
				SELECT @TimeTotal = - [TBH].[WriteBackHours] * 60,
					   @TimeValue = - [TBH].[WriteBackValue]
				  FROM @tempBatchH [TBH]
			END
		ELSE
			BEGIN
				SELECT @TimeTotal = SUM(CASE WHEN [TIE].[InvoiceNo] = 0 THEN 0 ELSE
										CASE WHEN ISNULL([TIE].[Rec_irr],'') <>'N' THEN  [TIE].[Time] ELSE 0 END END),
				       @TimeValue = SUM(CASE WHEN [TIE].[InvoiceNo] = 0 THEN 0 ELSE
										CASE WHEN ISNULL([TIE].[Rec_irr],'') <>'N' THEN  [TIE].[Charge] ELSE 0 END END)
				  FROM [dbo].[TimeEntry] [TIE] WITH(NOLOCK)
				  JOIN @tempBatchH [TBH]
				    ON [TIE].[Matter] = [TBH].[Matter]
				   --AND [TIE].[Date] = 4
			END

/* Hear We need to have the Bill Fee total JUST the Normal FEEs ie do not include the Misc Outlay
we will get this from the billDetails Type = 'F'...*/

			DECLARE @BHFeesTol DECIMAL(17,2)  = 0;
			
			SELECT @BHFeesTol = ISNULL(SUM(Net),0)
			  FROM [dbo].[BillDetails] [BID]
			 WHERE ISNULL([BID].[Type],'') = 'F'
			   AND [BID].[DraftNo] = (SELECT DISTINCT [TBH].[DraftBillNo]
			                            FROM @tempBatchH [TBH])

		    INSERT INTO [dbo].[TimeEntry] 
					(   [Matter],
						[FeeEarn],
						[Date],
						[Time],
						[Rate],
						[Charge],
						[Charged],
						[Units],
						[Task],						
						[TimeOrCharge],
						[Comment],
						[Billed],
						[NCCode],
						[Docket],
						[Team],
						[TrackRef],
						[Rec_Irr],
						[ShouldHave],
						[InvoiceNo],
						[Period],
                        [Year],
						[BillingPeriod],
						[BillingYear],
						[OpenInv],
						[ActionID],
						[StageCode],
						[BillingDate],
						[BilledDate],
						[BilledAmount],
						[AxleNumber],
						[WriteOffDT],
						[WriteOffID],
						[IncludeInBill],
                        [Leave],
						[MatterLevel],
						[FEERate],
						[ChargedMins],
						[FEECost],
						[TaskLevel],
						[WriteOff],
						[Branch],
						[EntryDate],
						[ModifyDate]
					)
					(
             SELECT  
						[TBH].[Matter],
						[MAT].[FECode],
                        [TBH].[WriteDown],
						0,
						0,
                        CASE WHEN @BHSupp='Y' THEN @BHFeesTol *-1
							 WHEN @InvCr='C' AND @BHSupp<>'Y' THEN @BHFeesTol
							 ELSE @BHFeesTol * -1 END,
						CASE WHEN @BHSupp='Y' THEN @BatchFeeTotal *-1
							 WHEN @InvCr='C' AND @BHSupp<>'Y' THEN @BHFeesTol
							 ELSE @BHFeesTol * 1 END,
						1,
						CASE WHEN @BHSupp='Y' THEN 'BILLED'
							 WHEN @InvCr='C' AND @BHSupp<>'Y' THEN 'CREDIT'
							 ELSE 'BILLED' END,
						'B',
						CASE WHEN @BHSupp='Y' THEN 'Open Invoice: (Total: '+CONVERT(VARCHAR,[TBH].[Value])+', Billed Fees:'+CONVERT(VARCHAR,@BHFeesTol)+ ')'
							 WHEN @InvCr='C' AND @BHSupp<>'Y' THEN 'Cr. Note Fees: ' + CONVERT(VARCHAR,@BHFeesTol)
							 ELSE 'Billed Fees: ' + CONVERT(VARCHAR,@BHFeesTol) END,
						0,
						'',
						0,
						[HAN].[Team],
						0,
						'C',
						0,
						[TBH].[Ref],
						[TBH].[PerNo],
						[TBH].[Year],
						0,
						0,
						CASE WHEN @BHSupp='Y' THEN 'Y'
							 WHEN @InvCr='C' AND @BHSupp<>'Y' THEN 'N'
							 ELSE 'N' END ,
						0,
						'',
						[TBH].[Date],
						[TBH].[Date],
						0,
						0,
						null,
						null,
						0,
						null,
						null,
						null,
						null,
						null,
						null,
						null,
						null,
						CAST(GETDATE() AS DATE),
						CAST(GETDATE() AS DATE)
				   FROM @tempBatchH [TBH]
				   JOIN [dbo].[Matters] [MAT] WITH(NOLOCK)
				     ON [MAT].[Code] = [TBH].[Matter]
				   JOIN [dbo].[Handlers] [HAN] WITH(NOLOCK)
				     ON [HAN].[Code]= [MAT].[FECode] 
				)    

	END

		DECLARE @BatchNo         INT,			
				@Type            VARCHAR(1),		
				@Code            VARCHAR(10),		
				@Pref            INT,			
				@Ref             VARCHAR(10),		
				@Date            DATETIME,		
				@Fee             VARCHAR(10),	
				@Branch          VARCHAR(3),		
				@Narr            VARCHAR(100),		
				@Matter          VARCHAR(20),	
				@Supp            VARCHAR(10),		
				@Value           DECIMAL(17, 2),
				@VatCode         VARCHAR(1),		
				@VatVal          DECIMAL(17, 2), 
				@ClientYN        VARCHAR(1),		
				@Outlay          VARCHAR(1),		
				@Pending         VARCHAR(1),		
				@Year            SMALLINT,		
				@PerNo           SMALLINT,		
				@EntryCurrency   VARCHAR(1),		
				@CurrencyValue   DECIMAL(17, 2) ,
				@CurrencyVat     DECIMAL(17, 2) ,
				@OutlayCode      VARCHAR(4),		
				@ThirdParty      VARCHAR(1),		
				@Payee           VARCHAR(60),		
				@HeadPref        INT,			
				@HeadBatch       INT,			
				@AllocBatch      INT,			
				@AllocPref       INT,			
				@AllocRef        VARCHAR(10),		
				@AllocValue      DECIMAL(17, 2), 
				@AllocWriteOff   VARCHAR(1),		
				@Psupp           VARCHAR(10),		
				@Undetaking      SMALLINT,		
				@CaseAssCode     VARCHAR(6),		
				@OnceOffPayment  VARCHAR(1),		
				@PayClient       VARCHAR(1),		
				@ClientCode      VARCHAR(10),	
				@EFTemailYorN    VARCHAR(1),		
				@RegisteredPost  INT,			
				@PreBilledOutlay BIT,			
				@KeyId		     INT,
				@ClientAc        VARCHAR(1),
				@EntryDate       DATETIME,
				@ClientBank		 VARCHAR(20),
				@Currency		 VARCHAR(10),
				@EFTSend		 VARCHAR(1),
				@EFTYorN		 VARCHAR(1),
				@ClearedDate     DATETIME,
				@BatchHCode      VARCHAR(10)	
	    DECLARE batchDetails_Cursor CURSOR FOR  
		   
		 SELECT [TBD].[BatchNo],         
				[TBD].[Type],            
				[TBD].[Code],            
				[TBD].[Pref],            
				[TBD].[Ref],            
				[TBD].[Date],            
				[TBD].[Fee],             
				[TBD].[Branch],          
				[TBD].[Narr],            
				[TBD].[Matter],          
				[TBD].[Supp],            
				[TBD].[Value],          
				[TBD].[VatCode],         
				[TBD].[VatVal],          
				[TBD].[ClientYN],        
				[TBD].[Outlay],          
				[TBD].[Pending],         
				[TBD].[Year],            
				[TBD].[PerNo],           
				[TBD].[EntryCurrency],   
				[TBD].[CurrencyValue],  
				[TBD].[CurrencyVat],    
				[TBD].[OutlayCode],      
				[TBD].[ThirdParty],      
				[TBD].[Payee],           
				[TBD].[HeadPref],        
				[TBD].[HeadBatch],       
				[TBD].[AllocBatch],      
				[TBD].[AllocPref],       
				[TBD].[AllocRef],        
				[TBD].[AllocValue],      
				[TBD].[AllocWriteOff],   
				[TBD].[Psupp],           
				[TBD].[Undetaking],      
				[TBD].[CaseAssCode],     
				[TBD].[OnceOffPayment],  
				[TBD].[PayClient],       
				[TBD].[ClientCode],      
				[TBD].[EFTemailYorN],    
				[TBD].[RegisteredPost],  
				[TBD].[PreBilledOutlay], 
				[TBD].[KeyId],
				[TBH].[ClientAc],
				[TBH].[EntryDate],
				[TBH].[ClientBank],
				[TBH].[Currency],
				[TBH].[EFTSent],
				[TBH].[EFT],
				[TBH].[ClearedDate],
				[TBH].[Code]
		   FROM @tempBatchDetails [TBD]
		   JOIN @tempBatchH [TBH]
		     ON [TBH].[BatchNo] = [TBD].[BatchNo]
		   OPEN batchDetails_Cursor
		  
		  FETCH 
	 NEXT FROM batchDetails_Cursor
		  INTO @BatchNo,         
			   @Type,            
			   @Code,            
			   @Pref,            
			   @Ref,             
			   @Date,            
			   @Fee,             
			   @Branch,          
			   @Narr,            
			   @Matter,          
			   @Supp,            
			   @Value,           
			   @VatCode,         
			   @VatVal,          
			   @ClientYN,        
			   @Outlay,          
			   @Pending,         
			   @Year,            
			   @PerNo,           
			   @EntryCurrency,   
			   @CurrencyValue,   
			   @CurrencyVat,     
			   @OutlayCode,      
			   @ThirdParty,      
			   @Payee,           
			   @HeadPref,        
			   @HeadBatch,       
			   @AllocBatch,      
			   @AllocPref,       
			   @AllocRef,        
			   @AllocValue,      
			   @AllocWriteOff,   
			   @Psupp,           
			   @Undetaking,      
			   @CaseAssCode,     
			   @OnceOffPayment,  
			   @PayClient,       
			   @ClientCode,      
			   @EFTemailYorN,    
			   @RegisteredPost,  
			   @PreBilledOutlay, 
			   @KeyId,
			   @ClientAc,
			   @EntryDate,
			   @ClientBank,
			   @Currency,
			   @EFTSend,
			   @EFTYorN,
			   @ClearedDate,
			   @BatchHCode
	
		WHILE @@FETCH_STATUS = 0
		BEGIN
			
/* UPDATE NOMINAL BALANCE BY DETAILS LINE*/
	 UPDATE [NOM]
	    SET [NOM].[Balance]		    = ISNULL([NOM].[Balance],0)+(@Value * -1 * @InvCrValue),
		    [NOM].[CurrencyBal]     = ISNULL([NOM].[CurrencyBal],0)+(@CurrencyValue * -1 * @InvCrValue),
		    [NOM].[BalanceFwd]      = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[BalanceFwd],0)+(@Value * -1 * @InvCrValue)
		    								ELSE ISNULL([NOM].[BalanceFwd],0) END,
		    [NOM].[CurrencyBalFwd]  = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[CurrencyBalFwd],0)+(@CurrencyValue * -1 * @InvCrValue)
		    								ELSE ISNULL([NOM].[CurrencyBalFwd],0) END,
		    [NOM].[Month1]			= CASE WHEN @CurPer = 1  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month1]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month1]  END,
		    [NOM].[Month2]			= CASE WHEN @CurPer = 2  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month2]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month2]  END,
		    [NOM].[Month3]			= CASE WHEN @CurPer = 3  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month3]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month3]  END,
		    [NOM].[Month4]			= CASE WHEN @CurPer = 4  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month4]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month4]  END,
		    [NOM].[Month5]			= CASE WHEN @CurPer = 5  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month5]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month5]  END,
		    [NOM].[Month6]			= CASE WHEN @CurPer = 6  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month6]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month6]  END,
		    [NOM].[Month7]			= CASE WHEN @CurPer = 7  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month7]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month7]  END,
		    [NOM].[Month8]			= CASE WHEN @CurPer = 8  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month8]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month8]  END,
		    [NOM].[Month9]			= CASE WHEN @CurPer = 9  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month9]+(@Value * -1 * @InvCrValue)  ELSE  [NOM].[Month9]  END,
		    [NOM].[Month10]			= CASE WHEN @CurPer = 10 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month10]+(@Value * -1 * @InvCrValue) ELSE  [NOM].[Month10] END,
		    [NOM].[Month11]			= CASE WHEN @CurPer = 11 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month11]+(@Value * -1 * @InvCrValue) ELSE  [NOM].[Month11] END,
		    [NOM].[Month12]			= CASE WHEN @CurPer = 12 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month12]+(@Value * -1 * @InvCrValue) ELSE  [NOM].[Month12] END
	   FROM [dbo].[Nominal] [NOM]
	  WHERE [NOM].[Code] = @Code

/* UPDATE NOMINAL BALANCE BY VAT VALUE */
	 UPDATE [NOM]
	    SET [NOM].[Balance]		    = ISNULL([NOM].[Balance],0)+(@VatVal * -1 * @InvCrValue),
		    [NOM].[CurrencyBal]     = ISNULL([NOM].[CurrencyBal],0)+(@CurrencyVat * -1 * @InvCrValue),
		    [NOM].[BalanceFwd]      = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[BalanceFwd],0)+(@VatVal * -1 * @InvCrValue)
		    								ELSE ISNULL([NOM].[BalanceFwd],0) END,
		    [NOM].[CurrencyBalFwd]  = CASE WHEN  @IsPostingFwd='Y' 
		    								THEN ISNULL([NOM].[CurrencyBalFwd],0)+(@CurrencyVat * -1 * @InvCrValue)
		    								ELSE ISNULL([NOM].[CurrencyBalFwd],0) END,
		    [NOM].[Month1]			= CASE WHEN @CurPer = 1  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month1]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month1]  END,
		    [NOM].[Month2]			= CASE WHEN @CurPer = 2  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month2]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month2]  END,
		    [NOM].[Month3]			= CASE WHEN @CurPer = 3  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month3]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month3]  END,
		    [NOM].[Month4]			= CASE WHEN @CurPer = 4  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month4]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month4]  END,
		    [NOM].[Month5]			= CASE WHEN @CurPer = 5  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month5]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month5]  END,
		    [NOM].[Month6]			= CASE WHEN @CurPer = 6  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month6]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month6]  END,
		    [NOM].[Month7]			= CASE WHEN @CurPer = 7  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month7]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month7]  END,
		    [NOM].[Month8]			= CASE WHEN @CurPer = 8  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month8]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month8]  END,
		    [NOM].[Month9]			= CASE WHEN @CurPer = 9  AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month9]+(@VatVal * -1 * @InvCrValue)  ELSE  [NOM].[Month9]  END,
		    [NOM].[Month10]			= CASE WHEN @CurPer = 10 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month10]+(@VatVal * -1 * @InvCrValue) ELSE  [NOM].[Month10] END,
		    [NOM].[Month11]			= CASE WHEN @CurPer = 11 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month11]+(@VatVal * -1 * @InvCrValue) ELSE  [NOM].[Month11] END,
		    [NOM].[Month12]			= CASE WHEN @CurPer = 12 AND @IsPostingFwd<>'Y'  THEN  [NOM].[Month12]+(@VatVal * -1 * @InvCrValue) ELSE  [NOM].[Month12] END
	   FROM [dbo].[Nominal] [NOM]
	  WHERE [NOM].[Code] = @Code



	   FETCH 
   NEXT FROM batchDetails_Cursor
		  INTO @BatchNo,         
			   @Type,            
			   @Code,            
			   @Pref,            
			   @Ref,             
			   @Date,            
			   @Fee,             
			   @Branch,          
			   @Narr,            
			   @Matter,          
			   @Supp,            
			   @Value,           
			   @VatCode,         
			   @VatVal,          
			   @ClientYN,        
			   @Outlay,          
			   @Pending,         
			   @Year,            
			   @PerNo,           
			   @EntryCurrency,   
			   @CurrencyValue,   
			   @CurrencyVat,     
			   @OutlayCode,      
			   @ThirdParty,      
			   @Payee,           
			   @HeadPref,        
			   @HeadBatch,       
			   @AllocBatch,      
			   @AllocPref,       
			   @AllocRef,        
			   @AllocValue,      
			   @AllocWriteOff,   
			   @Psupp,           
			   @Undetaking,      
			   @CaseAssCode,     
			   @OnceOffPayment,  
			   @PayClient,       
			   @ClientCode,      
			   @EFTemailYorN,    
			   @RegisteredPost,  
			   @PreBilledOutlay, 
			   @KeyId,
			   @ClientAc,
			   @EntryDate,
			   @ClientBank,
			   @Currency,
			   @EFTSend,
			   @EFTYorN,
			   @ClearedDate,
			   @BatchHCode
		  END
	 CLOSE batchDetails_Cursor;
DEALLOCATE batchDetails_Cursor;

/* UPDATE BATCHH DETAILS AS POSTED */

IF(@TimeCosting = 'Y')
	BEGIN
		UPDATE [MAT]
		   SET [MAT].[OpenInvoiceNo]  = [BIH].[BillNo]
		  FROM [dbo].[Matters] [MAT]
		  JOIN @tempBatchH [TBH]
		    ON [MAT].[Code] = [TBH].[Matter]
	 LEFT JOIN [dbo].[BillHeader] [BIH]
	        ON [BIH].[Matter]  = [TBH].[Matter]
		   AND [BIH].[BillNo]  = [TBH].[Ref]
		   AND [BIH].[DraftNo] = [TBH].[DraftBillNo]
	 END

	UPDATE [dbo].[BatchH]
	   SET [Posted]  = 'Y',
		   [PostFwd] = CASE WHEN @IsPostingFwd = 'Y' THEN 'Y' ELSE 'N' END
	 WHERE [BatchNo] = @PostedBatchNo

/* Update Time and Outlay for this invoice 
   Update the Time/Outlay based on the Billing Guide
*/
		DECLARE @BatchHMatter			VARCHAR(12) = '',
				@MCode				    VARCHAR(12) = '',
				@CompBillingMatter      VARCHAR(12) = '',
				@BGControlCnt           INT         = 0;

		 SELECT @BatchHMatter	   = [TBH].[Matter],
		        @MCode			   = [MAT].[Code],
				@CompBillingMatter = [MAT].[CompBillingMatter]
		   FROM @tempBatchH [TBH]
		   JOIN [dbo].[Matters] [MAT] WITH(NOLOCK)
		     ON [MAT].Code = [TBH].[Matter]

IF(@InvCr = 'I')
	BEGIN
		EXEC [dbo].[KAAS_SAMBillingGuideProcess] @PostedBatchNo

/* If this is a Composite Bill in to post the composite Journal */
		IF(@BatchHMatter = @MCode AND  @MCode = @CompBillingMatter)
			BEGIN
				EXEC [dbo].[KAAS_SAMBillingGuideTransfer] @PostedBatchNo
			END

	END
IF(@InvCr = 'C')
	BEGIN
		IF(@CreditInvoiceNo <> 0)
			BEGIN
				EXEC [dbo].[KAAS_SAMBillingGuideReset] @CreditInvoiceNo
			END
		IF(@BatchHMatter = @MCode AND  @MCode = @CompBillingMatter)
			BEGIN
				EXEC [dbo].[KAAS_SAMBillingGuideReverseTransfer] @PostedBatchNo
			END
	/* Check BGControl for Batch.*/
	IF(@DraftBillNo = 0 AND @CreditInvoiceNo IS NOT NULL)
		BEGIN
			SET @BGControlCnt = (SELECT COUNT(*) from [dbo].[BGControl] Where [BatchNo] = @PostedBatchNo)

				/* update TimeEntry Set all time with invoice number and date back to ZERO */

				IF(@BGControlCnt = 0)
					BEGIN
						UPDATE [TIE] 
						   SET [TIE].[InvoiceNo] = 0,
							   [TIE].[BilledAmount] = 0,
 							   [TIE].[BillingPeriod] = 0,
							   [TIE].[BillingYear] = 0
						  FROM [dbo].[TimeEntry] [TIE] 
						  JOIN @tempBatchH [TBH]
						    ON [TIE].[Matter] = [TBH].[Matter]
						   AND [TIE].[InvoiceNo] = [TBH].[CreditInvoiceNo]
						   AND [TIE].[TimeOrCharge] <> 'B'
						   AND [TIE].[DATE] = [TBH].[WriteDown]
                                       
				END
		END

	END


/* Update the Matter Time & charge Balances */
EXEC [KAAS_SAMUpdateMatterTimeBalance] @MatterCode

		COMMIT TRAN
	END TRY
	BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END
	END CATCH

 END
 GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_UpdatePostingSAMBankTransfer' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_UpdatePostingSAMBankTransfer] 
  END 
GO
CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMBankTransfer] ( 
       @BATCHNO   INT,
       @POSTFWD   VARCHAR(1),
       @HANDLER   VARCHAR(20))
AS
 /*******************************************************************************************************
 * Update Bank Tranfer Posting Logic                                                                    *
 *                                                                                                      *
 * Stored Procedure Name: [dbo].[KAAS_UpdatePostingSAMBankTransfer]                                     *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-11-18    Balamurugan C        Created                                                           *
 * 2022-02-22    Balamurugan C        Modified - Changed logic as pew SAM application and handled       *
                                                 period  end and post forward functionality             *
 * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
 * 2023-05-17    John Ginnane         Refactored the entire procedure                                   *
 * 2023-06-09    John Ginnane         Fixed bug around matter ledger sign
 ********************************************************************************************************/
 BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO)
    BEGIN
        RAISERROR ('Transaction does not exist.', 16, 99)
        RETURN
    END
    
    IF EXISTS (SELECT TOP 1 1
                 FROM [dbo].[BatchH] AS [BAH]
                WHERE [BAH].[BATCHNO] = @BATCHNO
                  AND [BAH].[POSTED] = 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END
    
     BEGIN TRY
        BEGIN TRAN
        
        UPDATE [BAH]
           SET [BAH].[POSTED]  = 'Y',
               [BAH].[POSTFWD] = 'N'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = 3064
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END
        
        DECLARE @CURYEAR       INT
        DECLARE @CURPER        INT
        DECLARE @VATNOMINAL    VARCHAR(10)
        DECLARE @CLCONTROL     VARCHAR(10)
        DECLARE @TODAY         DATETIME
        DECLARE @THIRDPARTY    BIT
        DECLARE @SHOWNOBAR     BIT
        DECLARE @CLIENTDEPOSIT BIT
        
        SELECT @CURYEAR       = [CON].[YEAR],
               @CURPER        = [CON].[CURPER],
               @VATNOMINAL    = [CON].[VAT],
               @CLCONTROL     = [CON].[CLIENT],
               @SHOWNOBAR     = CASE WHEN [CON].[NOBAR] = 'Y' THEN 1 ELSE 0 END,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY         = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
               @CLIENTDEPOSIT = 0
          FROM [dbo].[control] AS [CON]

        SELECT @THIRDPARTY = CASE WHEN ISNULL([BAH].[THIRDPARTY], '') = 'Y'
                                       THEN 1
                                  ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        IF @THIRDPARTY = 1
        BEGIN
            SELECT @CLIENTDEPOSIT = CASE WHEN ISNULL([NOM].[DEPOSITYN], '') = 'Y'
                                              THEN 1
                                         ELSE 0 END
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Nominal] AS [NOM]
                           ON [BAH].[CLIENTBANK] = [NOM].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
        END
        
        -- Rather than checking and displaying each EFT error message
        -- I'm going to check all of them and collate the outputs
        -- Then the user can be informed all multiple errors at once        
        DECLARE @EFTERROR VARCHAR(MAX)
        SET @EFTERROR = '' 
        
        -- !need to check
        -- !1 if the Bank EFT details are entered!
        SELECT @EFTERROR = @EFTERROR + 
                           COALESCE([NOM].[DESC], [NOM].[CODE], '') + 
                           ': Bank EFT details need to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND (ISNULL([NOM].[IBAN], '')        = ''
             OR ISNULL([NOM].[ACCOUNTNAME], '') = ''
             OR ISNULL([NOM].[SORTCODE], '')    = ''
             OR ISNULL([NOM].[ACCOUNTNO], '')   = ''
             OR ISNULL([NOM].[BIC], '')         = '')
             
        SELECT @EFTERROR = @EFTERROR + 
                           COALESCE([NOM].[DESC], [NOM].[CODE], '') + 
                           ': Bank EFT details need to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CLIENTBANK] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND (ISNULL([NOM].[IBAN], '')        = ''
             OR ISNULL([NOM].[ACCOUNTNAME], '') = ''
             OR ISNULL([NOM].[SORTCODE], '')    = ''
             OR ISNULL([NOM].[ACCOUNTNO], '')   = ''
             OR ISNULL([NOM].[BIC], '')         = '')

        IF ISNULL(@EFTERROR, '') <> ''
        BEGIN
            RAISERROR(@EFTERROR, 16, 99)
            RETURN
        END

        -- Make sure transaction is in correct year and period
        UPDATE [BAH]
           SET [BAH].[YEAR]  = @CURYEAR,
               [BAH].[PERNO] = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Check Money Laundering on all matters
        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Settings] AS [SET]
                    WHERE [SET].[KeyName] = 'Money Laundering_MoneyLaunderingCheck'
                      AND [SET].[KeyValue] IN ('1', 'true', 'Y'))
        BEGIN            
            DECLARE @CHECKAMLMATTERS VARCHAR(MAX)

            SELECT @CHECKAMLMATTERS = ISNULL(@CHECKAMLMATTERS, '') +
                                    CASE WHEN @CHECKAMLMATTERS IS NULL
                                              THEN ''
                                         ELSE ', ' END + [CNT].[Code]
              FROM [dbo].[Contacts] AS [CNT]
                   INNER JOIN (SELECT DISTINCT [MAT].[ClientCode]
                                 FROM [dbo].[BatchDetails] AS [BAD]
                                      INNER JOIN [dbo].[matters] AS [MAT]
                                              ON [MAT].[Code] = [BAD].[MATTER]
                                WHERE [BAD].[BATCHNO] = @BATCHNO) AS [BatchContacts]
                           ON [BatchContacts].[ClientCode] = [CNT].[Code]
             WHERE ISNULL([CNT].[Approved], 0) = 0

            IF ISNULL(@CHECKAMLMATTERS, '') <> ''
            BEGIN
                SET @CHECKAMLMATTERS = 'The following clients are not approved for AML: ' + @CLOSEDMATTERS + '. Cannot post.'
                RAISERROR (@CHECKAMLMATTERS, 16, 99)
                RETURN
            END        
        END
        
        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO],
               [BAD].[DATE]  = [BAH].[DATE]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
        
        -- ! If it should be on the Matter Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),                 /* MATTER */
               [BAD].[BATCHNO],                       /* BATCHNO */
               [BAD].[PREF],                          /* PREF */
               [BAH].[DATE],                          /* DATE */
               RTRIM([BAD].[REF]),                    /* REF */
               RTRIM([BAD].[NARR]),                   /* NARR */
               0,                                     /* VALUED */
               0,                                     /* VALUEO */
               ISNULL([BAD].[VALUE], 0) * -1,         /* VALUEC */
               [BAD].[FEE],                           /* FEE */
               [BAH].[PERNO],                         /* PER */
               @CURYEAR,                              /* YEAR */
               @TODAY,                                /* ENTRYDATE */
               LEFT([BAD].[MATTER], 6),               /* CLIENT */
               CASE WHEN [NOM].[DepositYN] <> 'Y'
                         THEN ISNULL([BAD].[VALUE], 0) * -1
                    ELSE 0 END,                       /* VALUECC */
               CASE WHEN [NOM].[DepositYN] = 'Y'
                         THEN ISNULL([BAD].[VALUE], 0) * -1
                    ELSE 0 END,                       /* VALUECD */
               '',                                    /* DEPOSITTYPE */
               0,                                     /* CURVALUED */
               0,                                     /* CURVALUEO */
               ISNULL([BAD].[CURRENCYVALUE], 0) * -1, /* CURVALUEC */
               CASE WHEN [NOM].[DEPOSITYN] <> 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                       /* CURVALUECC */
               CASE WHEN [NOM].[DEPOSITYN] = 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                       /* CURVALUECD */
               '',                                    /* BILLED */
               0,                                     /* BILLINGYEAR */
               0,                                     /* BILLINGPERIOD */
               NULL,                                  /* BILLINGDATE */
               0,                                     /* BilledOutlayValue */
               0,                                     /* InvoiceNo */
               0,                                     /* IncludeInBill */
               [BAH].[ClearedDate]                    /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[Nominal] AS [NOM]
                       ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
        
        -- Update matter's last act
        UPDATE [MAT]
           SET [MAT].[LastActType] = CASE [BAD].[OUTLAY]
                                          WHEN 'D' THEN 'Debtor Rec'
                                          WHEN 'O' THEN 'Outlay Rec'
                                          WHEN 'C' THEN 'Client Rec'
                                          ELSE [MAT].[LastActType] END,
               [MAT].[LastAct]     = @TODAY,
               [MAT].[LastActWho]  = @HANDLER
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [BAD].[MATTER] = [MAT].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- ! Update Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM(@CLCONTROL),                                                        /* CODE */
               RTRIM([BAH].[BRANCH]),                                                    /* BRANCH */
               [BAD].[BATCHNO],                                                          /* BATCHNO */
               [BAD].[PREF],                                                             /* PREF */
               [BAH].[DATE],                                                             /* DATE */
               RTRIM([BAD].[REF]),                                                       /* REF */
               RTRIM(LEFT([BAD].[NARR], 80)),                                            /* NARR */
               RTRIM([BAD].[MATTER]),                                                    /* MATTER */
               RTRIM([BAD].[SUPP]),                                                      /* SUPP */
               RTRIM([BAD].[FEE]),                                                       /* FEE */
               (ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)) * -1,              /* VALUE */
               (ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)) * -1, /* CURRENCYVALUE */
               [BAH].[PERNO],                                                            /* PER */
               @CURYEAR,                                                                 /* YEAR */
               @TODAY,                                                                   /* ENTRYDATE */
               0,                                                                        /* RECNO */
               [BAH].[ClearedDate]                                                       /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- ! If it should be on the Matter Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),             /* MATTER */
               [BAD].[BATCHNO],                   /* BATCHNO */
               [BAD].[PREF],                      /* PREF */
               [BAH].[DATE],                      /* DATE */
               RTRIM([BAD].[REF]),                /* REF */
               RTRIM([BAD].[NARR]),               /* NARR */
               CASE WHEN [BAD].[OUTLAY] = 'D'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,                   /* VALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,                   /* VALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,                   /* VALUEC */
               [BAD].[FEE],                       /* FEE */
               [BAH].[PERNO],                     /* PER */
               @CURYEAR,                          /* YEAR */
               @TODAY,                            /* ENTRYDATE */
               LEFT([BAD].[MATTER], 6),           /* CLIENT */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @CLIENTDEPOSIT = 0
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,                   /* VALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @CLIENTDEPOSIT = 1
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,                   /* VALUECD */
               '',                                /* DEPOSITTYPE */
               CASE WHEN [BAD].[OUTLAY] = 'D'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,                   /* CURVALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,                   /* CURVALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,                   /* CURVALUEC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @CLIENTDEPOSIT = 0
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,                   /* CURVALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @CLIENTDEPOSIT = 1
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,                   /* CURVALUECD */
               '',                                /* BILLED */
               0,                                 /* BILLINGYEAR */
               0,                                 /* BILLINGPERIOD */
               NULL,                              /* BILLINGDATE */
               0,                                 /* BilledOutlayValue */
               0,                                 /* InvoiceNo */
               0,                                 /* IncludeInBill */
               [BAH].[ClearedDate]                /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[Nominal] AS [NOM]
                       ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] <> 'N'

        -- ! 4/10/00 Update Debtled for bank trans
        INSERT INTO [dbo].[DebtorsLedger] (
               [MATTER],
               [TYPE],
               [CLIENT],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [ORFEES],
               [OROUTLAY],
               [ORVAT],
               [OSFEES],
               [OSOUTLAY],
               [OSVAT],
               [VATCODE],
               [PER],
               [YEAR],
               [FEECODE],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),    /* MATTER */
               'T',                      /* TYPE */
               LEFT([BAD].[MATTER], 6),  /* CLIENT */
               [BAH].[DATE],             /* DATE */
               RTRIM([BAD].[REF]),       /* REF */
               [BAD].[BATCHNO],          /* BATCHNO */
               [BAD].[PREF],             /* PREF */
               RTRIM([BAD].[NARR]),      /* NARR */
               ISNULL([BAD].[VALUE], 0), /* ORIGINAL */
               ISNULL([BAD].[VALUE], 0), /* OSVALUE */
               0,                        /* ORFEES */
               0,                        /* OROUTLAY */
               0,                        /* ORVAT */
               0,                        /* OSFEES */
               0,                        /* OSOUTLAY */
               0,                        /* OSVAT */
               [BAD].[VATCODE],          /* VATCODE */
               [BAH].[PERNO],            /* PER */
               [BAD].[YEAR],             /* YEAR */
               [BAD].[FEE],              /* FEECODE */
               [BAH].[ClearedDate]       /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] = 'D'
           
        -- Check if client balance will be overdrawn with this posting
        -- Or if the balance dips below the minimum amount
        DECLARE @MATTERSCLIENTBALANCES TABLE (
                [Code]      VARCHAR(20) PRIMARY KEY,
                [ClientMin] DECIMAL(19, 2),
                [ClientCur] DECIMAL(19, 2),
                [ClientDep] DECIMAL(19, 2))

        ;WITH [CTE_MAT] ([Code], [ClientMin]) AS (
        SELECT DISTINCT [MAT].[Code], ISNULL([MAT].[ClientMin], 0)
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = @BATCHNO),
              [CTE_MTL] ([Code], [ClientMin], [ClientCur], [ClientDep]) AS (
        SELECT LTRIM(RTRIM([CTE_MAT].[Code])),
               [CTE_MAT].[ClientMin],
               SUM(ISNULL([MTL].[VALUECC], 0)),
               SUM(ISNULL([MTL].[VALUECD], 0))
          FROM [CTE_MAT]
               LEFT OUTER JOIN [dbo].[MatterLedger] AS [MTL]
                            ON [MTL].[MATTER] = [CTE_MAT].[Code]
               GROUP BY LTRIM(RTRIM([CTE_MAT].[Code])),
                        [CTE_MAT].[ClientMin])
        INSERT INTO @MATTERSCLIENTBALANCES (
               [Code],
               [ClientMin],
               [ClientCur],
               [ClientDep])
        SELECT [CTE_MTL].[Code],
               [CTE_MTL].[ClientMin] * -1,
               [CTE_MTL].[ClientCur],
               [CTE_MTL].[ClientDep]
          FROM [CTE_MTL]
        
        DECLARE @OVERDRAWNMATTERS VARCHAR(MAX)

        SELECT @OVERDRAWNMATTERS = ISNULL(@OVERDRAWNMATTERS, '') +
                                   CASE WHEN @OVERDRAWNMATTERS IS NULL
                                             THEN ''
                                        ELSE ', ' END + [TMP].[Code]
          FROM @MATTERSCLIENTBALANCES AS [TMP]
         WHERE [TMP].[ClientCur] > 0
            --OR [TMP].[ClientDep] > 0 -- Commented out in clarion for some reason
        
        IF ISNULL(@OVERDRAWNMATTERS, '') <> ''
        BEGIN
            IF @SHOWNOBAR <> 1
            BEGIN
                SET @OVERDRAWNMATTERS = 'The following matters will be overdrawn: ' + @OVERDRAWNMATTERS + '. Cannot post.'
                RAISERROR (@OVERDRAWNMATTERS, 16, 99)
                RETURN
            END
        END
        
        -- ! Update Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAD].[CODE]),                                                 /* CODE */
               RTRIM([BAH].[BRANCH]),                                               /* BRANCH */
               [BAD].[BATCHNO],                                                     /* BATCHNO */
               [BAD].[PREF],                                                        /* PREF */
               [BAH].[DATE],                                                        /* DATE */
               RTRIM([BAD].[REF]),                                                  /* REF */
               RTRIM(LEFT([BAD].[NARR], 80)),                                       /* NARR */
               RTRIM([BAD].[MATTER]),                                               /* MATTER */
               RTRIM([BAD].[SUPP]),                                                 /* SUPP */
               RTRIM([BAD].[FEE]),                                                  /* FEE */
               (ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)),              /* VALUE */
               (ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)), /* CURRENCYVALUE */
               [BAH].[PERNO],                                                       /* PER */
               @CURYEAR,                                                            /* YEAR */
               @TODAY,                                                              /* ENTRYDATE */
               0,                                                                   /* RECNO */
               [BAH].[ClearedDate]                                                  /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- ! Update Nominal for Batch Header
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAH].[CODE]),              /* CODE */
               RTRIM([BAH].[BRANCH]),            /* BRANCH */
               [BAH].[BATCHNO],                  /* BATCHNO */
               [BAH].[PREF],                     /* PREF */
               [BAH].[DATE],                     /* DATE */
               RTRIM([BAH].[REF]),               /* REF */
               RTRIM(LEFT([BAH].[NARR], 80)),    /* NARR */
               RTRIM([BAH].[MATTER]),            /* MATTER */
               RTRIM([BAH].[SUPP]),              /* SUPP */
               RTRIM([BAH].[FEE]),               /* FEE */
               ISNULL([BAH].[VALUE], 0),         /* VALUE */
               ISNULL([BAH].[CURRENCYVALUE], 0), /* CURRENCYVALUE */
               [BAH].[PERNO],                    /* PER */
               @CURYEAR,                         /* YEAR */
               @TODAY,                           /* ENTRYDATE */
               0,                                /* RECNO */
               [BAH].[ClearedDate]               /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- ! Update Nominal for Batch Header
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAH].[CLIENTBANK]),             /* CODE */
               RTRIM([BAH].[BRANCH]),                 /* BRANCH */
               [BAH].[BATCHNO],                       /* BATCHNO */
               [BAH].[PREF],                          /* PREF */
               [BAH].[DATE],                          /* DATE */
               RTRIM([BAH].[REF]),                    /* REF */
               RTRIM(LEFT([BAH].[NARR], 80)),         /* NARR */
               RTRIM([BAH].[MATTER]),                 /* MATTER */
               RTRIM([BAH].[SUPP]),                   /* SUPP */
               RTRIM([BAH].[FEE]),                    /* FEE */
               ISNULL([BAH].[VALUE], 0) * -1,         /* VALUE */
               ISNULL([BAH].[CURRENCYVALUE], 0) * -1, /* CURRENCYVALUE */
               [BAH].[PERNO],                         /* PER */
               @CURYEAR,                              /* YEAR */
               @TODAY,                                /* ENTRYDATE */
               0,                                     /* RECNO */
               [BAH].[ClearedDate]                    /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        
        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN            
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                          FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     --UNION
                     --SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>'
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@CLCONTROL)) + '"/>') AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
END
GO
IF EXISTS (SELECT TOP 1 1
             FROM sys.[objects] SO
            WHERE SO.[name] = N'KAAS_UpdatePostingSAMInvoice'
              AND SO.[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_UpdatePostingSAMInvoice]
END
GO

CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMInvoice] (
       @BATCHNO   INT,
       @POSTFWD    VARCHAR(1),
       @HANDLER     VARCHAR(20))
AS
 /*******************************************************************************************************
 * Journal Posting Logic                                                                                *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMInvoice]                                         *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2022-01-13    Balamurugan C        Created                                                           *
 * 2022-02-21    Balamurugan C        Modified - Changed condition as per SAM                           *
 * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
 * 2022-07-15    John Ginnane         Refactored the entire procedure                                   *
 * 2022-10-17    Ghayathri.S.V        Modified - Updated all the cleared date values based on 
                                             batch header record                                        *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO)
    BEGIN
        RAISERROR ('Transaction does not exist.', 16, 99)
        RETURN
    END
    
    IF EXISTS (SELECT TOP 1 1
                 FROM [dbo].[BatchH] AS [BAH]
                WHERE [BAH].[BATCHNO] = @BATCHNO
                  AND [BAH].[POSTED] = 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END
    
    BEGIN TRY
        BEGIN TRAN
        
        UPDATE [BAH]
           SET [BAH].[POSTED]  = 'Y',
               [BAH].[POSTFWD] = 'N'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO         
        
        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = 3064
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END
        
        DECLARE @CURYEAR                   INT
        DECLARE @CURPER                    INT
        DECLARE @DEBTORS                   VARCHAR(10)
        DECLARE @OUTLAY                    VARCHAR(10)
        DECLARE @VATNOMINAL                VARCHAR(10)
        DECLARE @TODAY                     DATETIME
        DECLARE @THIRDPARTY                BIT
        DECLARE @SHOWNOBAR                 BIT
        DECLARE @MoneyLaunderingCheck      VARCHAR(1)
        DECLARE @MatterOutlayBudgetCheckON VARCHAR(1)
        DECLARE @INVCR                     INT
        DECLARE @EICONVERT                 DECIMAL(19, 6)
        DECLARE @IsBranchingEnabled        BIT
        DECLARE @TIMECOSTING               VARCHAR(1)
        
        SELECT @CURYEAR            = [CON].[YEAR],
               @CURPER             = [CON].[CURPER],
               @DEBTORS            = [CON].[DEBTORS],
               @OUTLAY             = [CON].[OUTLAY],
               @VATNOMINAL         = [CON].[VAT],
               @SHOWNOBAR          = CASE WHEN [CON].[NOBAR] = 'Y' THEN 1 ELSE 0 END,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY              = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
               @INVCR              = 1,
               @EICONVERT          = 0.787564, -- This is hard coded in clarion code
               @IsBranchingEnabled = CASE WHEN ISNULL([CON].[INDICATOR22], '') = 'Y' THEN 1 ELSE 0 END,
               @TIMECOSTING        = ISNULL([CON].[TIMECOSTING], '')
          FROM [dbo].[control] AS [CON]

        SELECT @MatterOutlayBudgetCheckON = CASE WHEN [SET].[KeyName] = 'MatterOutlayBudgetCheckON'
                                                      THEN [SET].[KeyValue]
                                                 ELSE @MatterOutlayBudgetCheckON END,
               @MoneyLaunderingCheck      = CASE WHEN [SET].[KeyName] = 'Money Laundering_MoneyLaunderingCheck'
                                                      THEN [SET].[KeyValue]
                                                 ELSE @MoneyLaunderingCheck END
          FROM [dbo].[Settings] AS [SET]
         WHERE [SET].[KeyName] IN ('MatterOutlayBudgetCheckON', 
                                   'Money Laundering_MoneyLaunderingCheck')
        
        SELECT @MatterOutlayBudgetCheckON = ISNULL(@MatterOutlayBudgetCheckON, '')

        SELECT @INVCR = CASE WHEN [BAH].[INVCR] = 'C' THEN -1 ELSE 1 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAH]
           SET [BAH].[YEAR]    = @CURYEAR,
               [BAH].[PERNO]   = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END,
               [BAH].[POSTED]  = 'Y',
               [BAH].[POSTFWD] = 'N'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO],
               [BAD].[DATE]  = [BAH].[DATE]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- Check Money Laundering on all matters
        IF @MoneyLaunderingCheck = 'Y'
        BEGIN
            DECLARE @CHECKAMLMATTERS VARCHAR(MAX)

            SELECT @CHECKAMLMATTERS = ISNULL(@CHECKAMLMATTERS, '') +
                                    CASE WHEN @CHECKAMLMATTERS IS NULL
                                              THEN ''
                                         ELSE ', ' END + [CNT].[Code]
              FROM [dbo].[Contacts] AS [CNT]
                   INNER JOIN (SELECT DISTINCT [MAT].[ClientCode]
                                 FROM [dbo].[BatchDetails] AS [BAD]
                                      INNER JOIN [dbo].[matters] AS [MAT]
                                              ON [MAT].[Code] = [BAD].[MATTER]
                                WHERE [BAD].[BATCHNO] = @BATCHNO) AS [BatchContacts]
                           ON [BatchContacts].[ClientCode] = [CNT].[Code]
             WHERE ISNULL([CNT].[Approved], 0) = 0

            IF ISNULL(@CHECKAMLMATTERS, '') <> ''
            BEGIN
                SET @CHECKAMLMATTERS = 'The following clients are not approved for AML: ' + @CLOSEDMATTERS + '. Cannot post.'
                RAISERROR (@CHECKAMLMATTERS, 16, 99)
                RETURN
            END
        END

        -- ! Update Matter (if Outlay on invoice)
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT RTRIM([BAH].[MATTER]),                      /* MATTER */
               [BAH].[BATCHNO],                            /* BATCHNO */
               [BAH].[PREF],                               /* PREF */
               [BAH].[DATE],                               /* DATE */
               RTRIM([BAH].[REF]),                         /* REF */
               'To Invoice ' + RTRIM([BAH].[REF]),         /* NARR */
               0,                                          /* VALUED */
               ISNULL([BAH].[OUTLAYTOT], 0) * -1 * @INVCR, /* VALUEO */
               0,                                          /* VALUEC */
               '',                                         /* FEE */
               [BAH].[PERNO],                              /* PER */
               @CURYEAR,                                   /* YEAR */
               @TODAY,                                     /* ENTRYDATE */
               LEFT([BAH].[MATTER], 6),                    /* CLIENT */
               0,                                          /* VALUECC */
               0,                                          /* VALUECD */
               '',                                         /* DEPOSITTYPE */
               0,                                          /* CURVALUED */
               CASE WHEN [BAH].[CURRENCY] = 'I'
                         THEN [BAH].[OUTLAYTOT] / @EICONVERT * -1 * @INVCR
                    WHEN [BAH].[CURRENCY] = 'E'
                         THEN [BAH].[OUTLAYTOT] * @EICONVERT * -1 * @INVCR
                    ELSE 0 END,                            /* CURVALUEO */
               0,                                          /* CURVALUEC */
               0,                                          /* CURVALUECC */
               0,                                          /* CURVALUECD */
               '',                                         /* BILLED */
               0,                                          /* BILLINGYEAR */
               0,                                          /* BILLINGPERIOD */
               NULL,                                       /* BILLINGDATE */
               0,                                          /* BilledOutlayValue */
               0,                                          /* InvoiceNo */
               0,                                          /* IncludeInBill */
               [BAH].[ClearedDate]                         /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[OUTLAYTOT] <> 0
           AND [BAH].[SINGLELINE] = 'Y'

        -- ! Update Outlay Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT @OUTLAY,                                        /* CODE */
               CASE WHEN @IsBranchingEnabled = 1
                         THEN ISNULL(RTRIM([BAH].[BRANCH]), '')
                    ELSE '' END,                               /* BRANCH */
               [BAH].[BATCHNO],                                /* BATCHNO */
               [BAH].[PREF],                                   /* PREF */
               [BAH].[DATE],                                   /* DATE */
               ISNULL(RTRIM([BAH].[REF]), ''),                 /* REF */
               'To Invoice ' + ISNULL(RTRIM([BAH].[REF]), ''), /* NARR */
               ISNULL(RTRIM([BAH].[MATTER]), ''),              /* MATTER */
               '',                                             /* SUPP */
               '',                                             /* FEE */
               [BAH].[OUTLAYTOT] * -1 * @INVCR,                /* VALUE */
               [MTL].[CURVALUEO] * -1 * @INVCR,                /* CURRENCYVALUE */
               [BAH].[PERNO],                                  /* PER */
               @CURYEAR,                                       /* YEAR */
               @TODAY,                                         /* ENTRYDATE */
               0,                                              /* RECNO */
               [BAH].[ClearedDate]                             /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[MatterLedger] AS [MTL]
                            ON [MTL].[BATCHNO] = [BAH].[BATCHNO]
                           AND [MTL].[PREF] = [BAH].[PREF]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[OUTLAYTOT] <> 0
           AND [BAH].[SINGLELINE] = 'Y'

        -- ! If it should be on the Matter Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT ISNULL(RTRIM([BAH].[MATTER]), ''),                    /* MATTER */
               [BAD].[BATCHNO],                                      /* BATCHNO */
               [BAD].[PREF],                                         /* PREF */
               [BAD].[DATE],                                         /* DATE */
               ISNULL(RTRIM([BAD].[REF]), ''),                       /* REF */
               CASE WHEN ISNULL(RTRIM(LTRIM([BAH].[INVCR])), '') = 'C'
                         THEN 'From Cr. Note ' + 
                               ISNULL(RTRIM(LTRIM([BAH].[REF])), '')
                    ELSE 'To Inv ' + 
                         ISNULL(RTRIM(LTRIM([BAH].[REF])), '') + 
                         ' ' + 
                         ISNULL(RTRIM(LTRIM([BAD].[NARR])), '') END, /* NARR */
               0,                                                    /* VALUED */
               ISNULL([BAD].[VALUE], 0) * -1 * @INVCR,               /* VALUEO */
               0,                                                    /* VALUEC */
               ISNULL(RTRIM(LTRIM([BAD].[FEE])), ''),                /* FEE */
               [BAH].[PERNO],                                        /* PER */
               @CURYEAR,                                             /* YEAR */
               @TODAY,                                               /* ENTRYDATE */
               LEFT([BAH].[MATTER], 6),                              /* CLIENT */
               0,                                                    /* VALUECC */
               0,                                                    /* VALUECD */
               '',                                                   /* DEPOSITTYPE */
               0,                                                    /* CURVALUED */
               ISNULL([BAD].[CURRENCYVALUE], 0) * -1 * @INVCR,       /* CURVALUEO */
               0,                                                    /* CURVALUEC */
               0,                                                    /* CURVALUECC */
               0,                                                    /* CURVALUECD */
               '',                                                   /* BILLED */
               0,                                                    /* BILLINGYEAR */
               0,                                                    /* BILLINGPERIOD */
               NULL,                                                 /* BILLINGDATE */
               ISNULL([BAD].[VALUE], 0) * -1 * @INVCR,               /* BilledOutlayValue */
               0,                                                    /* InvoiceNo */
               0,                                                    /* IncludeInBill */
               [BAH].[ClearedDate]                                   /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND ([BAD].[OUTLAY] = 'O'
            AND [BAH].[SINGLELINE] <> 'Y')

        -- ! Update Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT ISNULL(RTRIM([BAD].[CODE]), ''),                                   /* CODE */
               CASE WHEN @IsBranchingEnabled = 1 THEN [BAH].[BRANCH] ELSE '' END, /* BRANCH */
               [BAD].[BATCHNO],                                                   /* BATCHNO */
               [BAD].[PREF],                                                      /* PREF */
               [BAD].[DATE],                                                      /* DATE */
               ISNULL(RTRIM([BAD].[REF]), ''),                                    /* REF */
               ISNULL(RTRIM([BAD].[NARR]), ''),                                   /* NARR */
               ISNULL(RTRIM([BAH].[MATTER]), ''),                                 /* MATTER */
               '',                                                                /* SUPP */
               ISNULL(RTRIM([BAD].[FEE]), ''),                                    /* FEE */
               ISNULL([BAD].[VALUE], 0) * -1 * @INVCR,                            /* VALUE */
               ISNULL([BAD].[CURRENCYVALUE], 0) * -1 * @INVCR,                    /* CURRENCYVALUE */
               [BAH].[PERNO],                                                     /* PER */
               @CURYEAR,                                                          /* YEAR */
               @TODAY,                                                            /* ENTRYDATE */
               0,                                                                 /* RECNO */
               [BAH].[ClearedDate]                                                /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND ([BAD].[OUTLAY] = 'F'
             OR ([BAD].[OUTLAY] = 'O'
             AND [BAH].[SINGLELINE] <> 'Y'))
             
        -- ! Update Nominal for Detail Lines VAT
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT ISNULL(RTRIM(@VATNOMINAL), ''),                                    /* CODE */
               CASE WHEN @IsBranchingEnabled = 1 THEN [BAH].[BRANCH] ELSE '' END, /* BRANCH */
               [BAD].[BATCHNO],                                                   /* BATCHNO */
               [BAD].[PREF],                                                      /* PREF */
               [BAD].[DATE],                                                      /* DATE */
               ISNULL(RTRIM([BAD].[REF]), ''),                                    /* REF */
               'VAT on Invoice/Cr Note ' + ISNULL(RTRIM([BAD].[REF]), ''),        /* NARR */
               ISNULL(RTRIM([BAH].[MATTER]), ''),                                 /* MATTER */
               '',                                                                /* SUPP */
               ISNULL(RTRIM([BAD].[FEE]), ''),                                    /* FEE */
               ISNULL([BAD].[VATVAL], 0) * -1 * @INVCR,                           /* VALUE */
               ISNULL([BAD].[CURRENCYVAT], 0) * -1 * @INVCR,                      /* CURRENCYVALUE */
               [BAH].[PERNO],                                                     /* PER */
               @CURYEAR,                                                          /* YEAR */
               @TODAY,                                                            /* ENTRYDATE */
               0,                                                                 /* RECNO */
               [BAH].[ClearedDate]                                                /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[VATVAL] <> 0
           AND ([BAD].[OUTLAY] = 'F'
             OR ([BAD].[OUTLAY] = 'O'
             AND [BAH].[SINGLELINE] <> 'Y'))

        -- ! Update Nominal for Batch Header
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT ISNULL(RTRIM(@DEBTORS), ''),                                       /* CODE */
               CASE WHEN @IsBranchingEnabled = 1 THEN [BAH].[BRANCH] ELSE '' END, /* BRANCH */
               [BAH].[BATCHNO],                                                   /* BATCHNO */
               [BAH].[PREF],                                                      /* PREF */
               [BAH].[DATE],                                                      /* DATE */
               ISNULL(RTRIM([BAH].[REF]), ''),                                    /* REF */
               ISNULL(RTRIM([BAH].[NARR]), ''),                                   /* NARR */
               ISNULL(RTRIM([BAH].[MATTER]), ''),                                 /* MATTER */
               '',                                                                /* SUPP */
               ISNULL(RTRIM([BAH].[FEE]), ''),                                    /* FEE */
               ISNULL([BAH].[VALUE], 0) * @INVCR,                                 /* VALUE */
               ISNULL([BAH].[CURRENCYVALUE], 0) * @INVCR,                         /* CURRENCYVALUE */
               [BAH].[PERNO],                                                     /* PER */
               @CURYEAR,                                                          /* YEAR */
               @TODAY,                                                            /* ENTRYDATE */
               0,                                                                 /* RECNO */
               [BAH].[ClearedDate]												  /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        DECLARE @MAL_NARR VARCHAR(80)
        SELECT @MAL_NARR = CASE WHEN ISNULL(RTRIM(LTRIM([BAH].[INVCR])), '') = 'C'
                                     THEN 'Cr. Note:'
                                ELSE 'Invoice:' END + 
                           '  Fees:'   + CONVERT(VARCHAR(20), ISNULL([BAH].[FEETOT], 0)) + 
                           '  Outlay:' + CONVERT(VARCHAR(20), ISNULL([BAH].[OUTLAYTOT], 0)) + 
                           '  VAT:'    + CONVERT(VARCHAR(20), ISNULL([BAH].[VATTOT], 0))
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- !Update Matter Debtors Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT ISNULL(RTRIM([BAH].[MATTER]), ''),         /* MATTER */
               [BAH].[BATCHNO],                           /* BATCHNO */
               [BAH].[PREF],                              /* PREF */
               [BAH].[DATE],                              /* DATE */
               ISNULL(RTRIM([BAH].[REF]), ''),            /* REF */
               @MAL_NARR,                                 /* NARR */
               ISNULL([BAH].[VALUE], 0) * @INVCR,         /* VALUED */
               0,                                         /* VALUEO */
               0,                                         /* VALUEC */
               ISNULL(RTRIM(LTRIM([BAH].[FEE])), ''),     /* FEE */
               [BAH].[PERNO],                             /* PER */
               @CURYEAR,                                  /* YEAR */
               @TODAY,                                    /* ENTRYDATE */
               LEFT([BAH].[MATTER], 6),                   /* CLIENT */
               0,                                         /* VALUECC */
               0,                                         /* VALUECD */
               '',                                        /* DEPOSITTYPE */
               ISNULL([BAH].[CURRENCYVALUE], 0) * @INVCR, /* CURVALUED */
               0,                                         /* CURVALUEO */
               0,                                         /* CURVALUEC */
               0,                                         /* CURVALUECC */
               0,                                         /* CURVALUECD */
               '',                                        /* BILLED */
               0,                                         /* BILLINGYEAR */
               0,                                         /* BILLINGPERIOD */
               NULL,                                      /* BILLINGDATE */
               0,                                         /* BilledOutlayValue */
               0,                                         /* InvoiceNo */
               0,                                         /* IncludeInBill */
               [BAH].[ClearedDate]                        /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Update matter's last act
        UPDATE [MAT]
           SET [MAT].[LastActType] = 'Inv/CrNote',
               [MAT].[LastAct]     = @TODAY,
               [MAT].[LastActWho]  = @HANDLER,
               [MAT].[EstFee]      = 0,
               [MAT].[ExpBillD]    = NULL,
               [MAT].[FNL_Date]    = NULL,
               [MAT].[FNL_Name]    = '',
               [MAT].[FNL_Address] = '',
               [MAT].[FNL_Fees]    = 0,
               [MAT].[FNL_Outlay]  = 0,
               [MAT].[FNL_VAT]     = 0,
               [MAT].[FNL_Total]   = 0,
               [MAT].[ExpPayD]     = DATEADD(DAY, 30, [BAH].[DATE])
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [BAH].[MATTER] = [MAT].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- !here We need to have the Bill Fee total JUST the Normal FEEs ie do not include the Misc Outlay
        -- !we will get this from the billDetails Type = 'F'...
        DECLARE @BHFEESTOT DECIMAL(19, 2)
        SET @BHFEESTOT = 0

        SELECT @BHFEESTOT = CASE WHEN ISNULL([BAH].[DRAFTBILLNO], 0) <> 0
                                      THEN ISNULL([BD].[Value], 0)
                                 ELSE ISNULL([BAH].[FEETOT], 0) END -- !just use the total as before from the batchHeader.
          FROM [dbo].[BatchH] AS [BAH]
               OUTER APPLY (SELECT SUM(ISNULL([BD].[NET], 0)) AS [Value]
                              FROM [dbo].[BillDetails] AS [BD]
                             WHERE [BD].[TYPE] = 'F'
                               AND [BD].[DRAFTNO] = [BAH].[DraftBillNo]) AS [BD]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        INSERT INTO [dbo].[TimeEntry] (
               [Matter],
               [FeeEarn],
               [Date],
               [Time],
               [Rate],
               [Charge],
               [Charged],
               [Units],
               [Task],
               [TimeOrCharge],
               [Comment],
               [Billed],
               [NCCode],
               [Docket],
               [Team],
               [TrackRef],
               [Rec_Irr],
               [ShouldHave],
               [InvoiceNo],
               [Period],
               [Year],
               [BillingPeriod],
               [BillingYear],
               [OpenInv],
               [ActionID],
               [StageCode],
               [BillingDate],
               [BilledDate],
               [BilledAmount],
               [AxleNumber],
               [WriteOffDT],
               [WriteOffID],
               [IncludeInBill],
               [Leave],
               [MatterLevel],
               [FEERate],
               [ChargedMins],
               [FEECost],
               [TaskLevel],
               [WriteOff],
               [Branch],
               [EntryDate],
               [ModifyDate])
        SELECT LTRIM(RTRIM([BAH].[MATTER])),           /* Matter */
               LTRIM(RTRIM([MAT].[FECode])),           /* FeeEarn */
               [BAH].[WRITEDOWN],                      /* Date */
               0,                                      /* Time */
               0,                                      /* Rate */
               CASE WHEN [BAH].[SUPP] = 'Y'
                      OR [BAH].[INVCR] = 'I'
                         THEN @BHFEESTOT * -1
                    ELSE @BHFEESTOT END,               /* Charge */
               CASE WHEN [BAH].[SUPP] = 'Y'
                         THEN @BHFEESTOT * -1
                    ELSE @BHFEESTOT END,               /* Charged */
               1,                                      /* Units */
               CASE WHEN [BAH].[INVCR] = 'C'
                         THEN 'CREDIT'
                    ELSE 'BILLED' END,                 /* Task */
               'B',                                    /* TimeOrCharge */
               CASE WHEN ISNULL([BAH].[SUPP], '') = 'Y' 
                         THEN 'Open Invoice: (Total: ' + CONVERT(VARCHAR(20), ISNULL([BAH].[VALUE], 0)) + 
                                           ', Billed Fees:' + CONVERT(VARCHAR(20), @BHFEESTOT) + ')'
                    WHEN ISNULL([BAH].[INVCR], '') = 'C'
                         THEN 'Cr. Note Fees: ' + CONVERT(VARCHAR(20), @BHFEESTOT)
                    ELSE 'Billed Fees: ' + CONVERT(VARCHAR(20), @BHFEESTOT) END, /* Comment */
               0,                                      /* Billed */
               '',                                     /* NCCode */
               0,                                      /* Docket */
               ISNULL(LTRIM(RTRIM([HAN].[TEAM])), ''), /* Team */
               0,                                      /* TrackRef */
               'C',                                    /* Rec_Irr */
               0,                                      /* ShouldHave */
               CONVERT(INT, [BAH].[REF]),              /* InvoiceNo */ -- This is extremely risky
               [BAH].[PERNO],                          /* Period */
               [BAH].[YEAR],                           /* Year */
               0,                                      /* BillingPeriod */
               0,                                      /* BillingYear */
               CASE WHEN ISNULL([BAH].[SUPP], '') = 'Y'
                         THEN 'Y'
                   ELSE 'N' END,                       /* OpenInv */
               0,                                      /* ActionID */
               '',                                     /* StageCode */
               [BAH].[DATE],                           /* BillingDate */
               [BAH].[DATE],                           /* BilledDate */
               0,                                      /* BilledAmount */
               0,                                      /* AxleNumber */
               NULL,                                   /* WriteOffDT */
               NULL,                                   /* WriteOffID */
               0,                                      /* IncludeInBill */
               NULL,                                   /* Leave */
               NULL,                                   /* MatterLevel */
               NULL,                                   /* FEERate */
               NULL,                                   /* ChargedMins */
               NULL,                                   /* FEECost */
               NULL,                                   /* TaskLevel */
               NULL,                                   /* WriteOff */
               NULL,                                   /* Branch */
               @TODAY,                                 /* EntryDate */
               @TODAY                                  /* ModifyDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAH].[MATTER]
               INNER JOIN [dbo].[Handlers] AS [HAN]
                       ON [HAN].[CODE] = [MAT].[FECode]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- !Update Debtors Ledger
        INSERT INTO [dbo].[DebtorsLedger] (
               [MATTER],
               [TYPE],
               [CLIENT],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [ORFEES],
               [OROUTLAY],
               [ORVAT],
               [OSFEES],
               [OSOUTLAY],
               [OSVAT],
               [VATCODE],
               [PER],
               [YEAR],
               [FEECODE],
               [ClearedDate])
        SELECT LTRIM(RTRIM([BAH].[MATTER])),             /* MATTER */
               'I',                                      /* TYPE */
               [MAT].[ClientCode],                       /* CLIENT */
               [BAH].[DATE],                             /* DATE */
               LTRIM(RTRIM([BAH].[REF])),                /* REF */
               [BAH].[BATCHNO],                          /* BATCHNO */
               [BAH].[PREF],                             /* PREF */
               @MAL_NARR,                                /* NARR */
               [BAH].[VALUE]     * @INVCR,               /* ORIGINAL */
               [BAH].[VALUE]     * @INVCR,               /* OSVALUE */
               [BAH].[FEETOT]    * @INVCR,               /* ORFEES */
               [BAH].[OUTLAYTOT] * @INVCR,               /* OROUTLAY */
               [BAH].[VATTOT]    * @INVCR,               /* ORVAT */
               [BAH].[FEETOT]    * @INVCR,               /* OSFEES */
               [BAH].[OUTLAYTOT] * @INVCR,               /* OSOUTLAY */
               [BAH].[VATTOT]    * @INVCR,               /* OSVAT */
               ISNULL([BAD].[VATCODE], ''),              /* VATCODE */
               [BAH].[PERNO],                            /* PER */
               @CURYEAR,                                 /* YEAR */
               '',                                       /* FEECODE */
               [BAH].[ClearedDate]                       /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [BAH].[MATTER] = [MAT].[Code]
               OUTER APPLY (SELECT TOP 1 ISNULL([BAD].[VATCODE], '') AS [VATCODE]
                              FROM [dbo].[BatchDetails] AS [BAD]
                             WHERE [BAD].[BATCHNO] = [BAH].[BATCHNO]
                               AND [BAD].[OUTLAY] = 'F') AS [BAD]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        INSERT INTO [dbo].[CostTransGathering] (
               [DATE],
               [MATTER],
               [VALUE],
               [ENTRYCURRENCY],
               [CURRENCYVALUE],
               [CURRENCYVAT],
               [HEADPREF],
               [HEADBATCH],
               [ALLOCBATCH],
               [ALLOCPREF],
               [ALLOCREF],
               [ALLOCVALUE],
               [ALLOCWRITEOFF])
        SELECT [BAH].[DATE]                    , /* DATE */
               LTRIM(RTRIM([BAH].[MATTER])),   /* MATTER */
               [BAH].[VALUE],                  /* VALUE */
               LTRIM(RTRIM([BAH].[CURRENCY])), /* ENTRYCURRENCY */
               [BAH].[CURRENCYVALUE],          /* CURRENCYVALUE */
               0,                              /* CURRENCYVAT */
               0,                              /* HEADPREF */
               0,                              /* HEADBATCH */
               [BAH].[BATCHNO],                /* ALLOCBATCH */
               [BAH].[PREF],                   /* ALLOCPREF */
               LTRIM(RTRIM([BAH].[REF])),      /* ALLOCREF */
               [BAH].[VALUE],                  /* ALLOCVALUE */
               'N'                             /* ALLOCWRITEOFF */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[THIRDPARTY] = 'Y'

        -- !if OPEN Invoice then place Invoice number in the matters record 25/09/02 CS
        IF @TIMECOSTING = 'Y'
        BEGIN
            UPDATE [MAT]
               SET [MAT].[OpenInvoiceNo] = [BIH].[BILLNO]
              FROM [dbo].[matters] AS [MAT]
                   INNER JOIN [dbo].[BatchH] AS [BAH]
                           ON [MAT].[Code] = [BAH].[MATTER]
                   INNER JOIN [dbo].[BillHeader] AS [BIH]
                           ON [BIH].[MATTER] = [BAH].[MATTER]
                          AND CONVERT(VARCHAR(10), [BIH].[BILLNO]) = [BAH].[REF]
                          AND [BIH].[DRAFTNO] = [BAH].[DraftBillNo]
             WHERE [BAH].[BATCHNO] = @BATCHNO
        END

        -- !New place due to rollbacks and commits in SQL procedures...  #80
        -- ! Update Time and Outlay for this invoice
        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO
                      AND [BAH].[INVCR] = 'I')
        BEGIN
            EXEC [dbo].[ky_BGProcess] @BATCHNO

            -- !check for errors
            IF ISNULL((SELECT COUNT(1)
                         FROM [dbo].[BGControl] AS [BGC]
                        WHERE [BGC].[BATCHNO] = @BATCHNO), 0) = 0
            BEGIN
                RAISERROR ('No BG Control Error', 16, 99)
            END

            -- ! If this is a Composite Bill in to post the composite JOurnal
            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchH] AS [BAH]
                              INNER JOIN [dbo].[matters] AS [MAT]
                                      ON [BAH].[MATTER] = [MAT].[Code]
                        WHERE [MAT].[CompBillingMatter] = [MAT].[Code]
                          AND [BAH].[BATCHNO] = @BATCHNO)
            BEGIN
                EXEC [dbo].[ky_BGTransfer] @BATCHNO
            END
        END

        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO
                      AND [BAH].[INVCR] = 'C')
        BEGIN
            DECLARE @CREDITINVOICENO INT

            SELECT @CREDITINVOICENO = ISNULL([BAH].[CreditInvoiceNo], 0)
              FROM [dbo].[BatchH] AS [BAH]
             WHERE [BAH].[BATCHNO] = @BATCHNO

            IF @CREDITINVOICENO <> 0
            BEGIN
                EXEC [dbo].[ky_BGReset] @CREDITINVOICENO
            END
            
            -- ! If this is a Composite Bill in to post the composite JOurnal
            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchH] AS [BAH]
                              INNER JOIN [dbo].[matters] AS [MAT]
                                      ON [BAH].[MATTER] = [MAT].[Code]
                        WHERE [MAT].[CompBillingMatter] = [MAT].[Code]
                          AND [BAH].[BATCHNO] = @BATCHNO)
            BEGIN
                EXEC [dbo].[ky_BGTransfer] @BATCHNO
            END

            -- !new stuff if user does not user Billing wizard AT ALL   !#81  took out as credit notes get a NEW bill No in the BAH:Ref field....
            -- !check BGControl for Batch..
            -- !this HAS to be the invoice Number to credit!
            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchH] AS [BAH]
                        WHERE [BAH].[BATCHNO] = @BATCHNO
                          AND [BAH].[DraftBillNo] = 0
                          AND [BAH].[CreditInvoiceNo] <> 0) AND
               NOT EXISTS (SELECT TOP 1 1
                             FROM [dbo].[BGControl] AS [BGC]
                            WHERE [BGC].[BATCHNO] = @BATCHNO)
            BEGIN
                UPDATE [TIE]
                   SET [TIE].[InvoiceNo]     = 0,
                       [TIE].[BilledAmount]  = 0,
                       [TIE].[BillingPeriod] = 0,
                       [TIE].[BillingYear]   = 0
                  FROM [dbo].[TimeEntry] AS [TIE]
                       INNER JOIN [dbo].[BatchH] AS [BAH]
                               ON [BAH].[BATCHNO] = @BATCHNO
                              AND [TIE].[Matter] = [BAH].[MATTER]
                              AND [TIE].[InvoiceNo] = [BAH].[CreditInvoiceNo]
                              AND [TIE].[TimeOrCharge] <> 'B'
                              AND [TIE].[Date] <= [BAH].[WRITEDOWN]
            END
        END

        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                          FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@DEBTORS)) + '"/>' AS [CODE]
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@OUTLAY)) + '"/>' AS [CODE]
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>' AS [CODE]) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
 END
GO

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

CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMJournal] (
       @BATCHNO   INT,
       @POSTFWD   VARCHAR(1),
       @HANDLER   VARCHAR(20))
AS
 /*******************************************************************************************************
 * Journal Posting Logic                                                                                *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMJournal]                                         *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2022-01-13    Balamurugan C        Created                                                           *
 * 2022-02-21    Balamurugan C        Modified - Changed condition as per SAM                           *
 * 2022-03-09    Balamurugan C        Modified - Handled TCL Statements                                 *
 * 2022-07-15    John Ginnane         Refactored the entire procedure                                   *
 * 2024-03-04    Balamurugan C        Added OSOutlay and OROutlay                                       *
 *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON;

    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO)
    BEGIN
        RAISERROR ('Transaction does not exist.', 16, 99)
        RETURN
    END
    
    IF EXISTS (SELECT TOP 1 1
                 FROM [dbo].[BatchH] AS [BAH]
                WHERE [BAH].[BATCHNO] = @BATCHNO
                  AND [BAH].[POSTED] = 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END
    
    BEGIN TRY
        BEGIN TRAN        
        
        UPDATE [BAH]
           SET [BAH].[POSTED]  = 'Y',
               [BAH].[POSTFWD] = 'N'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO         
        
        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = 3064
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END
        
        DECLARE @CURYEAR                   INT
        DECLARE @CURPER                    INT
        DECLARE @VATNOMINAL                VARCHAR(10)
        DECLARE @FEESWRITEOFF              VARCHAR(10)
        DECLARE @TODAY                     DATETIME
        DECLARE @THIRDPARTY                BIT
        DECLARE @SHOWNOBAR                 BIT
        DECLARE @MatterLaunderingCheck     VARCHAR(1)
        DECLARE @MatterOutlayBudgetCheckON VARCHAR(1)
        
        SELECT @CURYEAR       = [CON].[YEAR],
               @CURPER        = [CON].[CURPER],
               @VATNOMINAL    = [CON].[VAT],
               @FEESWRITEOFF   = [CON].[FEESWRITEOFF],
               --@CLCONTROL     = [CON].[CLIENT],
               @SHOWNOBAR     = CASE WHEN [CON].[NOBAR] = 'Y' THEN 1 ELSE 0 END,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY         = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
          FROM [dbo].[control] AS [CON]

        SELECT @MatterOutlayBudgetCheckON = CASE WHEN [SET].[KeyName] = 'MatterOutlayBudgetCheckON'
                                                      THEN [SET].[KeyValue]
                                                 ELSE @MatterOutlayBudgetCheckON END,
               @MatterLaunderingCheck     = CASE WHEN [SET].[KeyName] = 'Money Laundering_MoneyLaunderingCheck'
                                                      THEN [SET].[KeyValue]
                                                 ELSE @MatterLaunderingCheck END
          FROM [dbo].[Settings] AS [SET]
         WHERE [SET].[KeyName] IN ('MatterOutlayBudgetCheckON', 
                                   'Money Laundering_MoneyLaunderingCheck')
        
        SELECT @MatterOutlayBudgetCheckON = ISNULL(@MatterOutlayBudgetCheckON, '')

        UPDATE [BAH]
           SET [BAH].[YEAR]  = @CURYEAR,
               [BAH].[PERNO] = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- Check Money Laundering on all matters
        IF @MatterLaunderingCheck = 'Y'
        BEGIN
            DECLARE @CHECKAMLMATTERS VARCHAR(MAX)

            SELECT @CHECKAMLMATTERS = ISNULL(@CHECKAMLMATTERS, '') +
                                    CASE WHEN @CHECKAMLMATTERS IS NULL
                                              THEN ''
                                         ELSE ', ' END + [CNT].[Code]
              FROM [dbo].[Contacts] AS [CNT]
                   INNER JOIN (SELECT DISTINCT [MAT].[ClientCode]
                                 FROM [dbo].[BatchDetails] AS [BAD]
                                      INNER JOIN [dbo].[matters] AS [MAT]
                                              ON [MAT].[Code] = [BAD].[MATTER]
                                WHERE [BAD].[BATCHNO] = @BATCHNO) AS [BatchContacts]
                           ON [BatchContacts].[ClientCode] = [CNT].[Code]

            IF ISNULL(@CHECKAMLMATTERS, '') <> ''
            BEGIN
                SET @CHECKAMLMATTERS = 'The following clients are not approved for AML: ' + @CLOSEDMATTERS + '. Cannot post.'
                RAISERROR (@CHECKAMLMATTERS, 16, 99)
                RETURN
            END
        END

        -- ! If it should be on the Matter Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),   /* MATTER */
               [BAD].[BATCHNO],         /* BATCHNO */
               [BAD].[PREF],            /* PREF */
               [BAH].[DATE],            /* DATE */
               RTRIM([BAD].[REF]),      /* REF */
               RTRIM([BAD].[NARR]),     /* NARR */
               CASE WHEN [BAD].[OUTLAY] = 'D'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,         /* VALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,         /* VALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,         /* VALUEC */
               [BAD].[FEE],             /* FEE */
               [BAH].[PERNO],           /* PER */
               @CURYEAR,                /* YEAR */
               @TODAY,                  /* ENTRYDATE */
               LEFT([BAD].[MATTER], 6), /* CLIENT */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [BAH].[THIRDPARTY] <> 'Y'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,         /* VALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [BAH].[THIRDPARTY] = 'Y'
                         THEN ISNULL([BAD].[VALUE], 0)
                    ELSE 0 END,         /* VALUECD */
               '',                      /* DEPOSITTYPE */
               CASE WHEN [BAD].[OUTLAY] = 'D'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,         /* CURVALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,         /* CURVALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,         /* CURVALUEC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [BAH].[THIRDPARTY] <> 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,         /* CURVALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [BAH].[THIRDPARTY] = 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0)
                    ELSE 0 END,         /* CURVALUECD */
               '',                      /* BILLED */
               0,                       /* BILLINGYEAR */
               0,                       /* BILLINGPERIOD */
               NULL,                    /* BILLINGDATE */
               0,                       /* BilledOutlayValue */
               0,                       /* InvoiceNo */
               0,                       /* IncludeInBill */
               [BAH].[ClearedDate]      /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] <> 'N'

        -- Check if outlay balance is more than the budget
        IF @MatterOutlayBudgetCheckON = 'Y'
        BEGIN
            DECLARE @MATTERSOUTLAYBALANCES TABLE (
                    [Code]          VARCHAR(20) PRIMARY KEY,
                    [OutlayBudget]  DECIMAL(19, 2),
                    [OutlayBalance] DECIMAL(19, 2))

            ;WITH [CTE_MAT] ([Code], [OutlayBudget]) AS (
            SELECT DISTINCT [BAD].[MATTER], [MAT].[OutlayBud]
              FROM [dbo].[BatchDetails] AS [BAD]
                   INNER JOIN [dbo].[matters] AS [MAT]
                           ON [BAD].[MATTER] = [MAT].[Code]
             WHERE [BAD].[BATCHNO] = @BATCHNO
               AND [BAD].[OUTLAY] <> 'N'),
                  [CTE_MTL] ([Code], [OutlayBudget], [OutlayBal]) AS (
            SELECT [CTE_MAT].[Code],
                   [CTE_MAT].[OutlayBudget],
                   SUM(ISNULL([MTL].[VALUEO], 0))
              FROM [CTE_MAT]
                   LEFT OUTER JOIN [dbo].[MatterLedger] AS [MTL]
                                ON [MTL].[MATTER] = [CTE_MAT].[Code]
                   GROUP BY [CTE_MAT].[Code],
                            [CTE_MAT].[OutlayBudget])
            INSERT INTO @MATTERSOUTLAYBALANCES (
                   [Code],
                   [OutlayBudget],
                   [OutlayBalance])
            SELECT [CTE_MTL].[Code],
                   [CTE_MTL].[OutlayBudget],
                   [CTE_MTL].[OutlayBal]
              FROM [CTE_MTL]

            DECLARE @OVERBUDGETMATTERS VARCHAR(MAX)
            
            SELECT @OVERBUDGETMATTERS = ISNULL(@OVERBUDGETMATTERS, '') +
                                       CASE WHEN @OVERBUDGETMATTERS IS NULL
                                                 THEN ''
                                            ELSE ', ' END + [TMP].[Code]
              FROM @MATTERSOUTLAYBALANCES AS [TMP]
             WHERE [TMP].[OutlayBudget] <> 0
               AND [TMP].[OutlayBalance] > [TMP].[OutlayBudget]
        
            IF ISNULL(@OVERBUDGETMATTERS, '') <> ''
            BEGIN
                SET @OVERBUDGETMATTERS = 'The follow matters will go over their outlay budget: ' + @OVERBUDGETMATTERS + '. Cannot post.'
                RAISERROR (@OVERBUDGETMATTERS, 16, 99)
                RETURN
            END
        END
                
        -- Update matter's last act
        UPDATE [MAT]
           SET [MAT].[LastActType] = CASE [BAD].[OUTLAY]
                                          WHEN 'O' THEN 'Outlay Jnl'
                                          WHEN 'C' THEN 'Client Jnl'
                                          WHEN 'D' THEN 'Bill Jnl'
                                          ELSE [MAT].[LastActType] END,
               [MAT].[LastAct]     = @TODAY,
               [MAT].[LastActWho]  = @HANDLER
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [BAD].[MATTER] = [MAT].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO

         -- ! Update Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT LTRIM(RTRIM([BAD].[CODE])),       /* CODE */
               LTRIM(RTRIM([BAH].[BRANCH])),     /* BRANCH */
               [BAD].[BATCHNO],                  /* BATCHNO */
               [BAD].[PREF],                     /* PREF */
               [BAH].[DATE],                     /* DATE */
               LTRIM(RTRIM([BAD].[REF])),        /* REF */
               LTRIM(RTRIM([BAD].[NARR])),       /* NARR */
               LTRIM(RTRIM([BAD].[MATTER])),     /* MATTER */
               LTRIM(RTRIM([BAD].[SUPP])),       /* SUPP */
               LTRIM(RTRIM([BAD].[FEE])),        /* FEE */
               ISNULL([BAD].[VALUE], 0),         /* VALUE */
               ISNULL([BAD].[CURRENCYVALUE], 0), /* CURRENCYVALUE */
               [BAH].[PERNO],                    /* PER */
               [BAH].[YEAR],                     /* YEAR */
               @TODAY,                           /* ENTRYDATE */
               0,                                /* RECNO */
               [BAH].[ClearedDate]               /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- ! Update Nominal for VAT
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT LTRIM(RTRIM(@VATNOMINAL)),        /* CODE */
               LTRIM(RTRIM([BAH].[BRANCH])),     /* BRANCH */
               [BAD].[BATCHNO],                  /* BATCHNO */
               [BAD].[PREF],                     /* PREF */
               [BAH].[DATE],                     /* DATE */
               LTRIM(RTRIM([BAD].[REF])),        /* REF */
               'VAT on Journal' + ISNULL(LTRIM(RTRIM([BAD].[REF])), ''), /* NARR */
               LTRIM(RTRIM([BAH].[MATTER])),     /* MATTER */
               LTRIM(RTRIM([BAD].[SUPP])),       /* SUPP */
               LTRIM(RTRIM([BAD].[FEE])),        /* FEE */
               ISNULL([BAD].[VATVAL], 0),        /* VALUE */
               ISNULL([BAD].[CURRENCYVAT], 0),   /* CURRENCYVALUE */
               [BAH].[PERNO],                    /* PER */
               [BAH].[YEAR],                     /* YEAR */
               @TODAY,                           /* ENTRYDATE */
               0,                                /* RECNO */
               [BAH].[ClearedDate]               /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND ISNULL([BAD].[VATVAL], 0) <> 0
           AND ISNULL([BAD].[CODE], '') = ISNULL(@FEESWRITEOFF, '')

        -- ! Update Supplier Stuff
        INSERT INTO [dbo].[SupplierLedger] (
               [SUPP],
               [TYPE],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [YEAR],
               [PER],
               [ENTRYDATE],
               [THIRDPARTY],
               [THIRDPARTYVALUE],
               [MATTER],
               [PENDINGOUTLAY])
        SELECT LTRIM(RTRIM([BAD].[SUPP])), /* SUPP */
               LTRIM(RTRIM([BAH].[TYPE])), /* TYPE */
               [BAH].[DATE],               /* DATE */
               LTRIM(RTRIM([BAD].[REF])),  /* REF */
               [BAD].[BATCHNO],            /* BATCHNO */
               [BAD].[PREF],               /* PREF */
               LTRIM(RTRIM([BAD].[NARR])), /* NARR */
               [BAD].[VALUE],              /* ORIGINAL */
               [BAD].[VALUE],              /* OSVALUE */
               @CURYEAR,                   /* YEAR */
               [BAH].[PERNO],              /* PER */
               @TODAY,                     /* ENTRYDATE */
               '',                         /* THIRDPARTY */
               0,                          /* THIRDPARTYVALUE */
               '',                         /* MATTER */
               0                           /* PENDINGOUTLAY */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[SUPP] <> ''

        -- !Set up Allocation records        
        DECLARE @SQL NVARCHAR(MAX)
        SET @SQL = ''

        -- !Update Debtors Ledger
        INSERT INTO [dbo].[DebtorsLedger] (
               [MATTER],
               [TYPE],
               [CLIENT],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [ORFEES],
               [OROUTLAY],
               [ORVAT],
               [OSFEES],
               [OSOUTLAY],
               [OSVAT],
               [VATCODE],
               [PER],
               [YEAR],
               [FEECODE],
               [ClearedDate])
        SELECT LTRIM(RTRIM([BAD].[MATTER])),     /* MATTER */
               'J',                              /* TYPE */
               LTRIM(RTRIM([MAT].[ClientCode])), /* CLIENT */
               [BAH].[DATE],                     /* DATE */
               LTRIM(RTRIM([BAD].[REF])),        /* REF */
               [BAD].[BATCHNO],                  /* BATCHNO */
               [BAD].[PREF],                     /* PREF */
               LTRIM(RTRIM([BAD].[NARR])),       /* NARR */
               [BAD].[VALUE],                    /* ORIGINAL */
               [BAD].[VALUE],                    /* OSVALUE */
               0,                                /* ORFEES */
               [BAD].[VALUE],                    /* OROUTLAY */
               0,                                /* ORVAT */
               0,                                /* OSFEES */
               [BAD].[VALUE],                    /* OSOUTLAY */
               0,                                /* OSVAT */
               '',                               /* VATCODE */
               [BAH].[PERNO],                    /* PER */
               @CURYEAR,                         /* YEAR */
               '',                               /* FEECODE */
               [BAH].[ClearedDate]               /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] = 'D'
           
        -- I have written this procedure to handle multiple allocations simultaneously
        SELECT @SQL = N'<Allocations User="' + @HANDLER + '">' + 
               (SELECT *
                  FROM (SELECT [BAD].[BATCHNO]    AS [ReceiptBatchNo],
                               [BAD].[PREF]       AS [ReceiptPostRef],
                               [BAD].[ALLOCBATCH] AS [InvoiceBatchNo],
                               [BAD].[ALLOCPREF]  AS [InvoicePostRef],
                               [BAD].[VALUE]      AS [AllocateValue],
                               'N'                AS [WriteOffRemainder]
                         FROM [dbo].[BatchH] AS [BAH]
                              INNER JOIN [dbo].[BatchDetails] AS [BAD]
                                      ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
                        WHERE (ISNULL([BAD].[SUPP], '') <> ''
                            OR ISNULL([BAD].[OUTLAY], '') = 'D')
                          AND [BAD].[ALLOCPREF] <> 0 -- Only check PREF because BATCHNO can be 0 for converted data
                          AND [BAH].[BATCHNO] = @BATCHNO) AS [Allocation]
                              FOR XML AUTO) +
               N'</Allocations>'

        IF ISNULL(@SQL, '') <> ''
        BEGIN
            EXEC [dbo].[KAAS_AutoAllocateTransactions] @SQL

            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchDetails] AS [BAD]
                        WHERE [BAD].[BATCHNO] = @BATCHNO
                          AND [BAD].[ALLOCWRITEOFF] = 'Y'
                          AND [BAD].[TYPE] = 'R'
                          AND [BAD].[OUTLAY] = 'D'
                          AND [BAD].[ALLOCPREF] <> 0)
            BEGIN
                RAISERROR ('Auto write-off Journal generated - please update', 5, 99)
            END
        END
        
        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                          FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>' AS [CODE]) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
 END
GO
IF EXISTS (SELECT TOP 1 1
             FROM [sys].[objects] AS [SO]
            WHERE SO.[name] = N'KAAS_UpdatePostingSAMMultiPayment'
              AND SO.[type] = 'P')
BEGIN
    DROP PROCEDURE [dbo].[KAAS_UpdatePostingSAMMultiPayment]
END
GO

CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMMultiPayment] (
       @BATCHNO   INT,
       @POSTFWD   VARCHAR(1),
       @HANDLER   VARCHAR(10))
AS
 /*******************************************************************************************************
 * Update Multi Payment Posting Logic                                                                   * 
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMMultiPayment]                                    *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2021-11-19    Balamurugan C        Created                                                           *
 * 2022-02-14    Balamurugan C        Modified - Implemented Logic as per SAM allocation part           *
 * 2022-02-21    Balamurugan C        Modified - Handled Current Period and Period End Date             *
 * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
 * 2022-10-17    Ghayathri.S.V        Modified - Removed logic setting handler name from handler table  *
 *                                               instead of User Code                                   *
 * 2023-06-12    John Ginnane         Refactored code                                                   *
 * 2024-04-25    Balamurugan C        Modified - Added Allocted Batch, Pref Ref and Value to process    *
												 allocation for supplier ledger                         *
 ********************************************************************************************************/
 BEGIN
    SET NOCOUNT ON
    
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO
                      AND [BAH].[POSTED] <> 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END

    BEGIN TRY
        BEGIN TRAN

        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = @BATCHNO
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END
        
        -- Check Money Laundering on all matters
        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Settings] AS [SET]
                    WHERE [SET].[KeyName] = 'Money Laundering_MoneyLaunderingCheck'
                      AND [SET].[KeyValue] IN ('1', 'true', 'Y'))
        BEGIN            
            DECLARE @CHECKAMLMATTERS VARCHAR(MAX)

            SELECT @CHECKAMLMATTERS = ISNULL(@CHECKAMLMATTERS, '') +
                                    CASE WHEN @CHECKAMLMATTERS IS NULL
                                              THEN ''
                                         ELSE ', ' END + [CNT].[Code]
              FROM [dbo].[Contacts] AS [CNT]
                   INNER JOIN (SELECT DISTINCT [MAT].[ClientCode]
                                 FROM [dbo].[BatchDetails] AS [BAD]
                                      INNER JOIN [dbo].[matters] AS [MAT]
                                              ON [MAT].[Code] = [BAD].[MATTER]
                                WHERE [BAD].[BATCHNO] = @BATCHNO) AS [BatchContacts]
                           ON [BatchContacts].[ClientCode] = [CNT].[Code]
             WHERE ISNULL([CNT].[Approved], 0) = 0

            IF ISNULL(@CHECKAMLMATTERS, '') <> ''
            BEGIN
                SET @CHECKAMLMATTERS = 'The following clients are not approved for AML: ' + @CLOSEDMATTERS + '. Cannot post.'
                RAISERROR (@CHECKAMLMATTERS, 16, 99)
                RETURN
            END        
        END
        
        DECLARE @CURYEAR       INT
        DECLARE @CURPER        INT
        DECLARE @VATNOMINAL    VARCHAR(10)
        DECLARE @CLCONTROL     VARCHAR(10)
        DECLARE @TODAY         DATETIME
        DECLARE @THIRDPARTY    BIT
        DECLARE @SHOWNOBAR     BIT
        
        SELECT @CURYEAR       = [CON].[YEAR],
               @CURPER        = [CON].[CURPER],
               @VATNOMINAL    = [CON].[VAT],
               @CLCONTROL     = [CON].[CLIENT],
               @SHOWNOBAR     = CASE WHEN [CON].[NOBAR] = 'Y' THEN 1 ELSE 0 END,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY         = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
          FROM [dbo].[control] AS [CON]

        SELECT @THIRDPARTY = CASE WHEN ISNULL([BAH].[THIRDPARTY], '') = 'Y'
                                       THEN 1
                                  ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- Make sure transaction is in correct year and period
        UPDATE [BAH]
           SET [BAH].[YEAR]     = @CURYEAR,
               [BAH].[PERNO]    = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END,
               [BAH].[CLIENTAC] = CASE WHEN ISNULL([NOM].[CLIENTAC], '') <> 'Y' THEN 'N' ELSE [BAH].[CLIENTAC] END
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO],
               [BAD].[DATE]  = [BAH].[DATE]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
        
        DECLARE @PRINTCHEQUE BIT
        DECLARE @MULTIBATCH  INT
        DECLARE @BANKAC      VARCHAR(10)
        DECLARE @CLIENTAC    VARCHAR(10)
        DECLARE @EFTYN       VARCHAR(1)

        SELECT @PRINTCHEQUE = CASE WHEN ISNULL([BAH].[THIRDPARTY], '') = 'Y' THEN 1 ELSE 0 END,
               @MULTIBATCH  = [BAH].[BATCHNO],
               @BANKAC      = [BAH].[CODE],
               @CLIENTAC    = [BAH].[CLIENTAC],
               @EFTYN       = ISNULL([BAH].[EFTYorN], '')
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Use table variables instead of TopSpeed (TPS) files
        DECLARE @MultiBD TABLE (
                [id]              INT          PRIMARY KEY     IDENTITY(1, 1),
                [BatchNo]         INT,
                [Type]            VARCHAR(1),
                [Code]            VARCHAR(10),
                [PRef]            INT,
                [Ref]             VARCHAR(50),
                [Date]            DATETIME,
                [Fee]             VARCHAR(10),
                [Narr]            VARCHAR(500),
                [Matter]          VARCHAR(20),
                [Supp]            VARCHAR(10),
                [Value]           DECIMAL(19, 2),
                [VATCode]         VARCHAR(1),
                [VATValue]        DECIMAL(19, 2),
                [ClientYN]        VARCHAR(1),
                [Outlay]          VARCHAR(1),
                [Pending]         VARCHAR(1),
                [Year]            INT,
                [PerNo]           INT,
                [EntryCurrency]   VARCHAR(1),
                [CurrencyValue]   DECIMAL(19, 2),
                [CurrencyVAT]     DECIMAL(19, 2),
                [OutlayCode]      VARCHAR(10),
                [ThirdParty]      VARCHAR(1),
                [Payee]           VARCHAR(500),
                [HeadPRef]        INT,
                [HeadBatch]       INT,
                [AllocBatch]      INT,
                [AllocPRef]       INT,
                [AllocRef]        VARCHAR(10),
                [AllocValue]      DECIMAL(19, 2),
                [AllocWriteOff]   VARCHAR(1),
                [PSupp]           VARCHAR(10),

                [CreditInvoiceNo] INT,
                [DraftBillNo]     INT,
                [EFTFileNumber]   INT,
                [EFTFileName]     VARCHAR(500),
                [ClientCode]      VARCHAR(10),
                [OnceOffPayment]  VARCHAR(1),
                [PayClient]       VARCHAR(1),
                [AssociateCode]   VARCHAR(10),
                [EFTEmailYorN]    VARCHAR(1),
                [PaymentMethod]   INT,
                [Branch]          VARCHAR(10))

        INSERT INTO @MultiBD (
               [BatchNo],
               [Type],
               [Code],
               [PRef],
               [Ref],
               [Branch],
               [Date],
               [Fee],
               [Narr],
               [Matter],
               [Supp],
               [Value],
               [VATCode],
               [VATValue],
               [ClientYN],
               [Outlay],
               [Pending],
               [Year],
               [PerNo],
               [EntryCurrency],
               [CurrencyValue],
               [CurrencyVAT],
               [OutlayCode],
               [ThirdParty],
               [Payee],
               [HeadPRef],
               [HeadBatch],
               [AllocBatch],
               [AllocPRef],
               [AllocRef],
               [AllocValue],
               [AllocWriteOff],
               [PSupp],

               [CreditInvoiceNo],
               [DraftBillNo],
               [EFTFileNumber],
               [EFTFileName],
               [ClientCode],
               [OnceOffPayment],
               [PayClient],
               [AssociateCode],
               [EFTEmailYorN],
               [PaymentMethod])
        SELECT [BAD].[BATCHNO],
               [BAD].[TYPE],
               [BAD].[CODE],
               [BAD].[PREF],
               [BAD].[REF],
               [BAD].[BRANCH],
               [BAD].[DATE],
               [BAD].[FEE],
               [BAD].[NARR],
               [BAD].[MATTER],
               [BAD].[SUPP],
               [BAD].[VALUE],
               [BAD].[VATCODE],
               [BAD].[VATVAL],
               [BAD].[CLIENTYN],
               [BAD].[OUTLAY],
               [BAD].[PENDING],
               [BAD].[YEAR],
               [BAD].[PERNO],
               [BAD].[ENTRYCURRENCY],
               [BAD].[CURRENCYVALUE],
               [BAD].[CURRENCYVAT],
               [BAD].[OUTLAYCODE],
               [BAD].[THIRDPARTY],
               [BAD].[PAYEE],
               [BAD].[HEADPREF],
               [BAD].[HEADBATCH],
               [BAD].[ALLOCBATCH],
               [BAD].[ALLOCPREF],
               [BAD].[ALLOCREF],
               [BAD].[ALLOCVALUE],
               [BAD].[ALLOCWRITEOFF],
               [BAD].[PSUPP],

               -- Not sure why OUTLAY and NOMINAL payments have different values but recreating it for consistency
               CASE WHEN [BAD].[OUTLAY] = 'N' THEN 0  ELSE NULL END,  -- CreditInvoiceNo
               CASE WHEN [BAD].[OUTLAY] = 'N' THEN 0  ELSE NULL END,  -- DraftBillNo
               CASE WHEN [BAD].[OUTLAY] = 'N' THEN 0  ELSE NULL END,  -- EFTFileNumber
               CASE WHEN [BAD].[OUTLAY] = 'N' THEN '' ELSE NULL END,  -- EFTFileName

               CASE WHEN @EFTYN = 'Y' THEN [BAD].[ClientCode]     ELSE CASE WHEN [BAD].[OUTLAY] = 'N' THEN '' ELSE NULL END END,
               CASE WHEN @EFTYN = 'Y' THEN [BAD].[OnceOffPayment] ELSE 'N'  END,
               CASE WHEN @EFTYN = 'Y' THEN [BAD].[PayClient]      ELSE 'N'  END,
               CASE WHEN @EFTYN = 'Y' THEN [BAD].[CaseAssCode]    ELSE CASE WHEN [BAD].[OUTLAY] = 'N' THEN '' ELSE NULL END END,
               CASE WHEN @EFTYN = 'Y' THEN [BAD].[EFTEmailYorN]   ELSE 'N'  END,
               CASE WHEN [BAD].[OUTLAY] = 'N' THEN 0 ELSE NULL END  -- PaymentMethod
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- In Clarion there is a function "RIDELETE:BatchH()" which
        -- looks at the relationships of BatchH and attempts to
        -- apply the delete, cascading to BatchDetails and other
        -- tables. However we're not interested in those tables so
        -- we're just going to ignore them for now
        DELETE [BAD]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        DELETE [BAH]
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Create one batch for each row in @MultiBD
        INSERT INTO [dbo].[BatchH] (
               [BATCHNO],
               [POSTFWD],
               [TYPE],
               [CODE],
               [BRANCH],
               [MATTER],
               [PREF],
               [REF],
               [DATE],
               [FEE],
               [NARR],
               [VALUE],
               [POSTED],
               [CLIENTAC],
               [PERNO],
               [YEAR],
               [PAYEE],
               [THIRDPARTY],
               [SUPP],
               [INVCR],
               [USERCODE],
               [ENTRYDATE],
               [CLIENTBANK],
               [CURRENCY],
               [CURRENCYVALUE],
               [RECNO],
               [SINGLELINE],
               [TEMPLATE],
               [CHEQUEREQNO],
               [CORRECTCOPY],
               [CreditInvoiceNo],
               [DraftBillNo],
               [EFTSent],
               [EFTDate],
               [EFTFileName],
               [EFTFileNumber],
               [EFTYorN],
               [ClientCode],
               --[PayClient],   --Not specified in original code
               [OnceOffPayment],
               [CaseAssCode],
               [EFTEmailYorN],
               [PaymentMethod])
        SELECT [MBD].[HeadBatch],       /* BATCHNO */
               @POSTFWD,                /* POSTFWD */
               'P',                     /* TYPE */
               @BANKAC,                 /* CODE */
               RTRIM([MBD].[Branch]),   /* BRANCH */
               [MBD].[Matter],          /* MATTER */
               [MBD].[HeadPRef],        /* PREF */
               [MBD].[Ref],             /* REF */
               [MBD].[Date],            /* DATE */
               '',                      /* FEE */
               [MBD].[Narr],            /* NARR */
               [MBD].[Value],           /* VALUE */
               'N',                     /* POSTED */
               @CLIENTAC,               /* CLIENTAC */
               @CURPER,                 /* PERNO */
               @CURYEAR,                /* YEAR */
               [MBD].[Payee],           /* PAYEE */
               [MBD].[ThirdParty],      /* THIRDPARTY */
               CASE WHEN @EFTYN = 'Y' THEN [MBD].[Supp] ELSE [MBD].[PSupp] END, /* SUPP */
               '',                      /* INVCR */
               @HANDLER,                /* USERCODE */
               @TODAY,                  /* ENTRYDATE */
               '',                      /* CLIENTBANK */
               [MBD].[EntryCurrency],   /* CURRENCY */
               [MBD].[CurrencyValue],   /* CURRENCYVALUE */
               0,                       /* RECNO */
               '',                      /* SINGLELINE */
               '',                      /* TEMPLATE */
               0,                       /* CHEQUEREQNO */
               '',                      /* CORRECTCOPY */
               [MBD].[CreditInvoiceNo], /* CreditInvoiceNo */
               [MBD].[DraftBillNo],     /* DraftBillNo */
               'N',                     /* EFTSent */
               NULL,                    /* EFTDate */
               [MBD].[EFTFileName],     /* EFTFileName */
               [MBD].[EFTFileNumber],   /* EFTFileNumber */
               @EFTYN,                  /* EFTYorN */
               [MBD].[ClientCode],      /* ClientCode */
               --'N',                   /* PayClient - Not specified in original code */
               [MBD].[OnceOffPayment],  /* OnceOffPayment */
               [MBD].[AssociateCode],   /* CaseAssCode */
               [MBD].[EFTEmailYorN],    /* EFTEmailYorN */
               [MBD].[PaymentMethod]    /* PaymentMethod */
          FROM @MultiBD AS [MBD]

        -- Rather than checking and displaying each EFT error message
        -- I'm going to check all of them and collate the outputs
        -- Then the user can be informed all multiple errors at once
        
        -- !If EFT need to check for bank account details
        DECLARE @EFTERROR VARCHAR(MAX)
        SET @EFTERROR = ''
        
        -- !1: for suppliers
        SELECT @EFTERROR = @EFTERROR + 
                           COALESCE([SUP].[NAME], [SUP].[CODE], '') + 
                           ': Bank Details/EFT Email needs to be set up!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN @MultiBD AS [MBD]
                       ON [MBD].[HeadBatch] = [BAH].[BATCHNO]
                      AND [MBD].[HeadPRef] = [BAH].[PREF]
               INNER JOIN [dbo].[Suppliers] AS [SUP]
                       ON [BAH].[SUPP] = [SUP].[CODE]
         WHERE [BAH].[SUPP] <> ''
           AND @EFTYN = 'Y'
           AND (ISNULL([SUP].[BankSortCode], '')    = ''
             OR ISNULL([SUP].[BankAccNo], '')       = ''
             OR ISNULL([SUP].[IBAN], '')            = ''
             OR ISNULL([SUP].[BIC], '')             = ''
             OR ISNULL([SUP].[EFTEmailAddress], '') = '')
             
        -- !2: for client        
        SELECT @EFTERROR = @EFTERROR + 
                           [BAH].[ClientCode] + ISNULL(', ' + [CNT].[NAME], '') +
                           ': Bank Details/EFT Email needs to be set up!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN @MultiBD AS [MBD]
                       ON [MBD].[HeadBatch] = [BAH].[BATCHNO]
                      AND [MBD].[HeadPRef]  = [BAH].[PREF]
               INNER JOIN [dbo].[Contacts] AS [CNT]
                       ON [BAH].[ClientCode] = [CNT].[CODE]
         WHERE [BAH].[ClientCode] <> ''
           AND [BAH].[PayClient] = 'Y'
           AND @EFTYN = 'Y'
           AND (ISNULL([CNT].[BankSortCode], '')    = ''
             OR ISNULL([CNT].[BankAccNo], '')       = ''
             OR ISNULL([CNT].[IBAN], '')            = ''
             OR ISNULL([CNT].[BIC], '')             = ''
             OR ISNULL([CNT].[EFTEmailAddress], '') = '')

        -- !3: for Case Ass
        SELECT @EFTERROR = @EFTERROR + 
                           [MBD].[AssociateCode] + ISNULL(', ' + [CAN].[NAME], '') +
                           ': Bank Details/EFT Email needs to be set up!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN @MultiBD AS [MBD]
                       ON [MBD].[HeadBatch] = [BAH].[BATCHNO]
                      AND [MBD].[HeadPRef]  = [BAH].[PREF]
               INNER JOIN [dbo].[CaseAssociatesNames] AS [CAN]
                       ON [CAN].[CODE] = [MBD].[AssociateCode]
         WHERE [BAH].[OnceOffPayment] = 'Y'
           AND [MBD].[AssociateCode] <> ''
           AND @EFTYN = 'Y'
           AND (ISNULL([CAN].[BankSortCode], '')    = ''
             OR ISNULL([CAN].[BankAccNo], '')       = ''
             OR ISNULL([CAN].[IBAN], '')            = ''
             OR ISNULL([CAN].[BIC], '')             = ''
             OR ISNULL([CAN].[EFTEmailAddress], '') = '')
             
        IF ISNULL(@EFTERROR, '') <> ''
        BEGIN
            RAISERROR(@EFTERROR, 16, 99)
            RETURN
        END

        -- In clarion there is a "deep assignment" which means that
        -- any columns that are the same in both tables we copy the
        -- values from one to the other
        INSERT INTO [dbo].[BatchDetails] (
               [BATCHNO],
               [TYPE],
               [CODE],
               [PREF],
               [REF],
               [DATE],
               [FEE],
               [BRANCH],
               [NARR],
               [MATTER],
               [SUPP],
               [VALUE],
               [VATCODE],
               [VATVAL],
               [CLIENTYN],
               [OUTLAY],
               [PENDING],
               [YEAR],
               [PERNO],
               [ENTRYCURRENCY],
               [CURRENCYVALUE],
               [CURRENCYVAT],
               [OUTLAYCODE],
               [THIRDPARTY],
               [PAYEE],
               [HEADPREF],
               [HEADBATCH],
               [ALLOCBATCH],
               [ALLOCPREF],
               [ALLOCREF],
               [ALLOCVALUE],
               [ALLOCWRITEOFF],
               [PSUPP],
               [UNDETAKING],
               [CaseAssCode],
               [OnceOffPayment],
               [PayClient],
               [ClientCode],
               [EFTEmailYorN],
               [RegisteredPost],
               [PreBilledOutlay])
        SELECT [BAH].[BatchNo],         /* BATCHNO */
               'P',                     /* TYPE */
               RTRIM([MBD].[Code]),     /* CODE */
               [MBD].[PRef],            /* PREF */
               [MBD].[Ref],             /* REF */
               [MBD].[Date],            /* DATE */
               [MBD].[Fee],             /* FEE */
               RTRIM([MBD].[Branch]),   /* BRANCH */
               [MBD].[Narr],            /* NARR */
               [MBD].[Matter],          /* MATTER */
               [MBD].[Supp],            /* SUPP */
               [MBD].[Value],           /* VALUE */
               [MBD].[VATCode],         /* VATCODE */
               [MBD].[VATValue],        /* VATVAL */
               '',                      /* CLIENTYN */
               [MBD].[Outlay],          /* OUTLAY */
               '',                      /* PENDING */
               [MBD].[Year],            /* YEAR */
               [MBD].[PerNo],           /* PERNO */
               [MBD].[EntryCurrency],   /* ENTRYCURRENCY */
               [MBD].[CurrencyValue],   /* CURRENCYVALUE */
               [MBD].[CurrencyVAT],     /* CURRENCYVAT */
               [MBD].[OutlayCode],      /* OUTLAYCODE */
               [MBD].[ThirdParty],      /* THIRDPARTY */
               [MBD].[Payee],           /* PAYEE */
               [MBD].[PRef],            /* HEADPREF */
               [MBD].[BatchNo],         /* HEADBATCH */
               [MBD].[AllocBatch],      /* ALLOCBATCH */
               [MBD].[AllocPref],       /* ALLOCPREF */
               [MBD].[AllocRef],        /* ALLOCREF */
               [MBD].[AllocValue],      /* ALLOCVALUE */
               '',                      /* ALLOCWRITEOFF */
               [MBD].[PSUPP],           /* PSUPP */
               '',                      /* UNDETAKING */
               ISNULL([MBD].[AssociateCode], ''),   /* CaseAssCode */
               'N',                     /* OnceOffPayment */
               'N',                     /* PayClient */
               'N',                     /* ClientCode */
               'N',                     /* EFTEmailYorN */
               0,                       /* RegisteredPost */
               0                        /* PreBilledOutlay */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN @MultiBD AS [MBD]
                       ON [BAH].[BATCHNO] = [MBD].[HeadBatch]
                      AND [BAH].[PREF] = [MBD].[HeadPRef]

        -- Now we can just call "post payment" procedure
        DECLARE @POSTBATCHNO INT
        DECLARE @I           INT

        SET @I = 0

        WHILE @I <= ISNULL((SELECT MAX([id]) FROM @MultiBD), 0)
        BEGIN
            SET @POSTBATCHNO = NULL

            SELECT @POSTBATCHNO = [TMP].[HeadBatch]
              FROM @MultiBD AS [TMP]
             WHERE [TMP].[id] = @I

            IF @POSTBATCHNO IS NOT NULL
            BEGIN
                PRINT('Sub batch no: ' + ISNULL(CONVERT(VARCHAR(10), @POSTBATCHNO), 'NULL'))
                EXEC [dbo].[KAAS_UpdatePostingSAMPayment] @POSTBATCHNO, @POSTFWD, @HANDLER
            END

            SET @I = @I + 1
        END

        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN            
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                          FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>'
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@CLCONTROL)) + '"/>') AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        PRINT('UpdatePostingSAMMultiPayment CATCH')

        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH

 END
 GO

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

CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMPayment] (
       @BATCHNO    INT,
       @POSTFWD    VARCHAR(1),
       @HANDLER    VARCHAR(10))
AS
 /*******************************************************************************************************
 * Payment Posting Logic                                                                                *
 *                                                                                                      *
 * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMPayment]                                         *
 *                                                                                                      *
 * Modification History:                                                                                *
 * 2022-01-13    Balamurugan C        Created                                                           *
 * 2022-02-01    Balamurugan C        Modified - Added Cast of Date statement for Batch Header          *
 *                                                and Detail Date field                                 *
 * 2022-02-21    Balamurugan C        Modified - Handled Current Period and Period End Date             *
 * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                 *
 * 2022-06-17    John Ginnane         Refactored the entire procedure                                   *
 * 2022-10-17    Ghayathri.S.V        Modified - Depostit Type data in matter ledger                    *
 * 2023-08-16    John Ginnane         Trim codes                                                        *
 ********************************************************************************************************/
BEGIN
    SET NOCOUNT ON;
    
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO)
    BEGIN
        RAISERROR ('Transaction does not exist.', 16, 99)
        RETURN
    END
    
    IF EXISTS (SELECT TOP 1 1
                 FROM [dbo].[BatchH] AS [BAH]
                WHERE [BAH].[BATCHNO] = @BATCHNO
                  AND [BAH].[POSTED] = 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END
    
    BEGIN TRY
        BEGIN TRAN

        UPDATE [BAH]
           SET [BAH].[POSTED]  = 'Y'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
         
        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = 3064
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END
        
        DECLARE @CURYEAR       INT
        DECLARE @CURPER        INT
        DECLARE @VATNOMINAL    VARCHAR(10)
        DECLARE @CLCONTROL     VARCHAR(10)
        DECLARE @TODAY         DATETIME
        DECLARE @THIRDPARTY    BIT
        DECLARE @SHOWNOBAR     BIT
        
        SELECT @CURYEAR       = [CON].[YEAR],
               @CURPER        = [CON].[CURPER],
               @VATNOMINAL    = [CON].[VAT],
               @CLCONTROL     = [CON].[CLIENT],
               @SHOWNOBAR     = CASE WHEN [CON].[NOBAR] = 'Y' THEN 1 ELSE 0 END,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY         = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
          FROM [dbo].[control] AS [CON]

        SELECT @THIRDPARTY = CASE WHEN ISNULL([BAH].[THIRDPARTY], '') = 'Y'
                                       THEN 1
                                  ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Rather than checking and displaying each EFT error message
        -- I'm going to check all of them and collate the outputs
        -- Then the user can be informed all multiple errors at once        
        DECLARE @EFTERROR VARCHAR(MAX)
        SET @EFTERROR = '' 
        
        -- !need to check
        -- !1 if the Bank EFT details are entered!
        SELECT @EFTERROR = @EFTERROR + 
                           COALESCE([NOM].[DESC], [NOM].[CODE], '') + 
                           ': Bank EFT details need to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND (ISNULL([NOM].[IBAN], '')        = ''
             OR ISNULL([NOM].[ACCOUNTNAME], '') = ''
             OR ISNULL([NOM].[SORTCODE], '')    = ''
             OR ISNULL([NOM].[ACCOUNTNO], '')   = ''
             OR ISNULL([NOM].[BIC], '')         = '')

        -- !client as a Payee        
        SELECT @EFTERROR = @EFTERROR + 
                           [CNT].[CODE] + ': ' + ISNULL(RTRIM([CNT].[NAME]), '') +
                           ': Client EFT details needs to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
                            ON [BAH].[ClientCode] = [CNT].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND [BAH].[PayClient] = 'Y'
           AND (ISNULL([CNT].[IBAN], '')         = ''
             OR ISNULL([CNT].[BankSortCode], '') = ''
             OR ISNULL([CNT].[BankAccNo], '')    = ''
             OR ISNULL([CNT].[BIC], '')          = '')
             
        SELECT @EFTERROR = @EFTERROR + 
                           [CNT].[CODE] + ': ' + ISNULL(RTRIM([CNT].[NAME]), '') +
                           ': Client EFT email address needs to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Contacts] AS [CNT]
                            ON [BAH].[ClientCode] = [CNT].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND [BAH].[PayClient] = 'Y'
           AND ISNULL([CNT].[EFTEmailAddress], '') = ''
        
        --!Supplier as a Payee        
        SELECT @EFTERROR = @EFTERROR + 
                           [SUP].[CODE] + ': ' + ISNULL(RTRIM([SUP].[NAME]), '') +
                           ': Supplier EFT details needs to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
                            ON [BAH].[SUPP] = [SUP].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[SUPP] <> ''
           AND [BAH].[EFTYorN] = 'Y'
           AND (ISNULL([SUP].[IBAN], '')         = ''
             OR ISNULL([SUP].[BankSortCode], '') = ''
             OR ISNULL([SUP].[BankAccNo], '')    = ''
             OR ISNULL([SUP].[BIC], '')          = '')
            
        SELECT @EFTERROR = @EFTERROR + 
                           [SUP].[CODE] + ': ' + ISNULL(RTRIM([SUP].[NAME]), '') +
                           ': Supplier EFT email address needs to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Suppliers] AS [SUP]
                            ON [BAH].[SUPP] = [SUP].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[SUPP] <> ''
           AND [BAH].[EFTEmailYorN] = 'Y'
           AND ISNULL([SUP].[EFTEmailAddress], '') = ''
        
        --!Case Associate as Payee
        SELECT @EFTERROR = @EFTERROR +
                           'Case Associate: ' +
                           ISNULL(RTRIM([CAN].[NAME]), [CAN].[CODE]) +
                           ' bank EFT detailed need to be entered!'
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[CaseAssociatesNames] AS [CAN]
                            ON [CAN].[CODE] = [BAH].[CaseAssCode]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[CaseAssCode] <> ''
           AND [BAH].[OnceOffPayment] = 'Y'
           AND (ISNULL([CAN].[IBAN], '') = ''
             OR ISNULL([CAN].[BankName], '') = ''
             OR ISNULL([CAN].[BankSortCode], '') = ''
             OR ISNULL([CAN].[BankAccNo], '') = ''
             OR ISNULL([CAN].[BIC], '') = '')
        
        SELECT @EFTERROR = @EFTERROR +
                           'Case Associate: ' +
                           ISNULL(RTRIM([CAN].[NAME]), [CAN].[CODE]) +
                           ' EFT email address needs to be entered!'
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[CaseAssociatesNames] AS [CAN]
                            ON [CAN].[CODE] = [BAH].[CaseAssCode]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[CaseAssCode] <> ''
           AND [BAH].[OnceOffPayment] = 'Y'
           AND [BAH].[EFTEmailYorN] = 'Y'
           AND ISNULL([CAN].[EFTEmailAddress], '') = ''

        IF ISNULL(@EFTERROR, '') <> ''
        BEGIN
            RAISERROR(@EFTERROR, 16, 99)
            RETURN
        END

        -- Somehow print cheque?
        
        -- Make sure transaction is in correct year and period
        UPDATE [BAH]
           SET [BAH].[YEAR]  = @CURYEAR,
               [BAH].[PERNO] = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Check Money Laundering on all matters
        IF EXISTS (SELECT TOP 1 1
                     FROM [dbo].[Settings] AS [SET]
                    WHERE [SET].[KeyName] = 'Money Laundering_MoneyLaunderingCheck'
                      AND [SET].[KeyValue] IN ('1', 'true', 'Y'))
        BEGIN            
            DECLARE @CHECKAMLMATTERS VARCHAR(MAX)

            SELECT @CHECKAMLMATTERS = ISNULL(@CHECKAMLMATTERS, '') +
                                    CASE WHEN @CHECKAMLMATTERS IS NULL
                                              THEN ''
                                         ELSE ', ' END + [CNT].[Code]
              FROM [dbo].[Contacts] AS [CNT]
                   INNER JOIN (SELECT DISTINCT [MAT].[ClientCode]
                                 FROM [dbo].[BatchDetails] AS [BAD]
                                      INNER JOIN [dbo].[matters] AS [MAT]
                                              ON [MAT].[Code] = [BAD].[MATTER]
                                WHERE [BAD].[BATCHNO] = @BATCHNO) AS [BatchContacts]
                           ON [BatchContacts].[ClientCode] = [CNT].[Code]
             WHERE ISNULL([CNT].[Approved], 0) = 0

            IF ISNULL(@CHECKAMLMATTERS, '') <> ''
            BEGIN
                SET @CHECKAMLMATTERS = 'The following clients are not approved for AML: ' + @CLOSEDMATTERS + '. Cannot post.'
                RAISERROR (@CHECKAMLMATTERS, 16, 99)
                RETURN
            END        
        END

        -- ! If it should be on the Matter Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),   /* MATTER */
               [BAD].[BATCHNO],         /* BATCHNO */
               [BAD].[PREF],            /* PREF */
               [BAH].[DATE],            /* DATE */
               RTRIM([BAD].[REF]),      /* REF */
               RTRIM([BAD].[NARR]),     /* NARR */
               0,                       /* VALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)
                    ELSE 0 END,         /* VALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)
                    ELSE 0 END,         /* VALUEC */
               ISNULL([BAD].[FEE], ''), /* FEE */
               [BAH].[PERNO],           /* PER */
               @CURYEAR,                /* YEAR */
               @TODAY,                  /* ENTRYDATE */
               LEFT([BAD].[MATTER], 6), /* CLIENT */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [NOM].[DepositYN] <> 'Y'
                         THEN ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)
                    ELSE 0 END,         /* VALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [NOM].[DepositYN] = 'Y'
                         THEN ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)
                    ELSE 0 END,         /* VALUECD */
               CASE WHEN [BAD].[OUTLAY] = 'C'
			         THEN [NOM].[DEPOSITTYPE]
			       ELSE '' END,         /* DEPOSITTYPE */
               0,                       /* CURVALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)
                    ELSE 0 END,         /* CURVALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)
                    ELSE 0 END,         /* CURVALUEC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [NOM].[DEPOSITYN] <> 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)
                    ELSE 0 END,         /* CURVALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND [NOM].[DEPOSITYN] = 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)
                    ELSE 0 END,         /* CURVALUECD */
               '',                      /* BILLED */
               0,                       /* BILLINGYEAR */
               0,                       /* BILLINGPERIOD */
               NULL,                    /* BILLINGDATE */
               0,                       /* BilledOutlayValue */
               0,                       /* InvoiceNo */
               0,                       /* IncludeInBill */
               [BAH].[ClearedDate]      /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[Nominal] AS [NOM]
                       ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] <> 'N'
        
        -- Check if client balance will be overdrawn with this posting
        -- Or if the balance dips below the minimum amount
        DECLARE @MATTERSCLIENTBALANCES TABLE (
                [Code]      VARCHAR(20) PRIMARY KEY,
                [ClientMin] DECIMAL(19, 2),
                [ClientCur] DECIMAL(19, 2),
                [ClientDep] DECIMAL(19, 2))

        ;WITH [CTE_MAT] ([Code], [ClientMin]) AS (
        SELECT DISTINCT [MAT].[Code], ISNULL([MAT].[ClientMin], 0)
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = @BATCHNO),
              [CTE_MTL] ([Code], [ClientMin], [ClientCur], [ClientDep]) AS (
        SELECT LTRIM(RTRIM([CTE_MAT].[Code])),
               [CTE_MAT].[ClientMin],
               SUM(ISNULL([MTL].[VALUECC], 0)),
               SUM(ISNULL([MTL].[VALUECD], 0))
          FROM [CTE_MAT]
               LEFT OUTER JOIN [dbo].[MatterLedger] AS [MTL]
                            ON [MTL].[MATTER] = [CTE_MAT].[Code]
               GROUP BY LTRIM(RTRIM([CTE_MAT].[Code])),
                        [CTE_MAT].[ClientMin])
        INSERT INTO @MATTERSCLIENTBALANCES (
               [Code],
               [ClientMin],
               [ClientCur],
               [ClientDep])
        SELECT [CTE_MTL].[Code],
               [CTE_MTL].[ClientMin] * -1,
               [CTE_MTL].[ClientCur],
               [CTE_MTL].[ClientDep]
          FROM [CTE_MTL]
        
        DECLARE @OVERDRAWNMATTERS VARCHAR(MAX)

        SELECT @OVERDRAWNMATTERS = ISNULL(@OVERDRAWNMATTERS, '') +
                                   CASE WHEN @OVERDRAWNMATTERS IS NULL
                                             THEN ''
                                        ELSE ', ' END + [TMP].[Code]
          FROM @MATTERSCLIENTBALANCES AS [TMP]
         WHERE [TMP].[ClientCur] > 0
            OR [TMP].[ClientDep] > 0
        
        IF ISNULL(@OVERDRAWNMATTERS, '') <> ''
        BEGIN
            IF @SHOWNOBAR <> 1
            BEGIN
                SET @OVERDRAWNMATTERS = 'The following matters will be overdrawn: ' + @OVERDRAWNMATTERS + '. Cannot post.'
                RAISERROR (@OVERDRAWNMATTERS, 16, 99)
                RETURN
            END
            ELSE
            BEGIN
                SET @OVERDRAWNMATTERS = 'As a result of this transfer, the client a/c is overdrawn on the following matters: ' + @OVERDRAWNMATTERS + '.'
                RAISERROR (@OVERDRAWNMATTERS, 5, 99)
            END
        END

        DECLARE @CLIENTRESERVEDOVERDRAWN VARCHAR(MAX)
        
        SELECT @CLIENTRESERVEDOVERDRAWN = ISNULL(@CLIENTRESERVEDOVERDRAWN, '') +
                                          CASE WHEN @CLIENTRESERVEDOVERDRAWN IS NULL
                                                    THEN ''
                                               ELSE ', ' END + [TMP].[Code]
          FROM @MATTERSCLIENTBALANCES AS [TMP]
         WHERE (ISNULL([TMP].[ClientCur], 0) + ISNULL([TMP].[ClientDep], 0)) > [TMP].[ClientMin]
        
        IF ISNULL(@CLIENTRESERVEDOVERDRAWN, '') <> ''
        BEGIN
            SET @CLIENTRESERVEDOVERDRAWN = 'As a result of this transfer, the client a/c reserve limit is overdrawn on the following matters: ' + @CLIENTRESERVEDOVERDRAWN + '.'
            RAISERROR (@CLIENTRESERVEDOVERDRAWN, 5, 99)
        END
        
        -- Update matter's last act
        UPDATE [MAT]
           SET [MAT].[LastActType] = CASE [BAD].[OUTLAY]
                                          WHEN 'O' THEN 'Outlay Pmt'
                                          WHEN 'C' THEN 'Client Pmt'
                                          ELSE [MAT].[LastActType] END,
               [MAT].[LastAct]     = @TODAY,
               [MAT].[LastActWho]  = @HANDLER
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [BAD].[MATTER] = [MAT].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- ! Update Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAD].[CODE]),                                               /* CODE */
               RTRIM([BAH].[BRANCH]),                                             /* BRANCH */
               [BAD].[BATCHNO],                                                   /* BATCHNO */
               [BAD].[PREF],                                                      /* PREF */
               [BAH].[DATE],                                                      /* DATE */
               RTRIM([BAD].[REF]),                                                /* REF */
               RTRIM(LEFT([BAD].[NARR], 80)),                                     /* NARR */
               RTRIM([BAD].[MATTER]),                                             /* MATTER */
               RTRIM([BAD].[SUPP]),                                               /* SUPP */
               RTRIM([BAD].[FEE]),                                                /* FEE */
               ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0),              /* VALUE */
               ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0), /* CURRENCYVALUE */
               [BAH].[PERNO],                                                     /* PER */
               @CURYEAR,                                                          /* YEAR */
               @TODAY,                                                            /* ENTRYDATE */
               0,                                                                 /* RECNO */
               [BAH].[ClearedDate]                                                /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- ! Update Nominal for VAT
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM(@VATNOMINAL),                    /* CODE */
               RTRIM([BAH].[BRANCH]),          /* BRANCH */
               [BAD].[BATCHNO],                /* BATCHNO */
               [BAD].[PREF],                   /* PREF */
               [BAH].[DATE],                   /* DATE */
               RTRIM([BAD].[REF]),             /* REF */
               RTRIM([BAD].[NARR]),            /* NARR */
               RTRIM([BAD].[MATTER]),          /* MATTER */
               RTRIM([BAD].[SUPP]),            /* SUPP */
               RTRIM([BAD].[FEE]),             /* FEE */
               ISNULL([BAD].[VATVAL], 0),      /* VALUE */
               ISNULL([BAD].[CURRENCYVAT], 0), /* CURRENCYVALUE */
               [BAH].[PERNO],                  /* PER */
               @CURYEAR,                       /* YEAR */
               @TODAY,                         /* ENTRYDATE */
               0,                              /* RECNO */
               [BAH].[ClearedDate]             /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND ISNULL([BAD].[VATVAL], 0) <> 0

        -- ! Update Supplier Stuff
        INSERT INTO [dbo].[SupplierLedger] (
               [SUPP],
               [TYPE],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [YEAR],
               [PER],
               [ENTRYDATE],
               [THIRDPARTY],
               [THIRDPARTYVALUE],
               [MATTER],
               [PENDINGOUTLAY])
        SELECT RTRIM([BAD].[SUPP]), /* SUPP */
               RTRIM([BAH].[TYPE]), /* TYPE */
               [BAH].[DATE],        /* DATE */
               RTRIM([BAD].[REF]),  /* REF */
               [BAD].[BATCHNO],     /* BATCHNO */
               [BAD].[PREF],        /* PREF */
               RTRIM([BAD].[NARR]), /* NARR */
               [BAD].[VALUE],       /* ORIGINAL */
               [BAD].[VALUE],       /* OSVALUE */
               @CURYEAR,            /* YEAR */
               [BAH].[PERNO],       /* PER */
               @TODAY,              /* ENTRYDATE */
               '',                  /* THIRDPARTY */
               0,                   /* THIRDPARTYVALUE */
               '',                  /* MATTER */
               0                    /* PENDINGOUTLAY */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[SUPP] <> ''

        -- !Set up Allocation records 
        DECLARE @SQL NVARCHAR(MAX)        
        SET @SQL = ''

        -- I have written this procedure to handle multiple allocations simultaneously
        SELECT @SQL = N'<Allocations User="' + @HANDLER + '">' + 
               (SELECT *
                  FROM (SELECT [BAD].[BATCHNO]    AS [ReceiptBatchNo],
                               [BAD].[PREF]       AS [ReceiptPostRef],
                               [BAD].[ALLOCBATCH] AS [InvoiceBatchNo],
                               [BAD].[ALLOCPREF]  AS [InvoicePostRef],
                               [BAD].[VALUE]      AS [AllocateValue],
                               CASE WHEN ISNULL([BAD].[ALLOCWRITEOFF], '') <> 'Y'
                                         THEN 'N'
                                    ELSE 'Y' END  AS [WriteOffRemainder]
                         FROM [dbo].[BatchH] AS [BAH]
                              INNER JOIN [dbo].[BatchDetails] AS [BAD]
                                      ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
                        WHERE ISNULL([BAD].[SUPP], '') <> ''
                          AND [BAD].[ALLOCPREF] <> 0 -- Only check PREF because BATCHNO can be 0 for converted data
                          AND [BAH].[BATCHNO] = @BATCHNO) AS [Allocation]
                              FOR XML AUTO) +
               N'</Allocations>'

        IF ISNULL(@SQL, '') <> ''
        BEGIN
            EXEC [dbo].[KAAS_AutoAllocateTransactions] @SQL

            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchDetails] AS [BAD]
                        WHERE [BAD].[BATCHNO] = @BATCHNO
                          AND [BAD].[ALLOCWRITEOFF] = 'Y'
                          AND [BAD].[TYPE] = 'R'
                          AND [BAD].[OUTLAY] = 'D'
                          AND [BAD].[ALLOCPREF] <> 0)
            BEGIN
                RAISERROR ('Auto write-off Journal generated - please update', 5, 99)
            END
        END
        
        -- ! Update Nominal Header Record
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAH].[CODE]),                   /* CODE */
               RTRIM([BAH].[BRANCH]),                 /* BRANCH */
               [BAH].[BATCHNO],                       /* BATCHNO */
               [BAH].[PREF],                          /* PREF */
               [BAH].[DATE],                          /* DATE */
               RTRIM([BAH].[REF]),                    /* REF */
               RTRIM([BAH].[NARR]),                   /* NARR */
               RTRIM([BAH].[MATTER]),                 /* MATTER */
               CASE WHEN [BAH].[EFTYorN] = 'Y'
                     AND [BAH].[OnceOffPayment] = 'Y'
                         THEN ''
                    ELSE RTRIM([BAH].[SUPP]) END,     /* SUPP */
               RTRIM([BAH].[FEE]),                    /* FEE */
               ISNULL([BAH].[VALUE], 0) * -1,         /* VALUE */
               ISNULL([BAH].[CURRENCYVALUE], 0) * -1, /* CURRENCYVALUE */
               [BAH].[PERNO],                         /* PER */
               @CURYEAR,                              /* YEAR */
               @TODAY,                                /* ENTRYDATE */
               0,                                     /* RECNO */
               [BAH].[ClearedDate]                    /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
        
        -- !#74 Supplier Remittance
        IF     EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchH] AS [BAH]
                              INNER JOIN [dbo].[Suppliers] AS [SUP]
                                      ON [BAH].[SUPP] = [SUP].[CODE]
                        WHERE [BAH].[BATCHNO] = @BATCHNO
                          AND [BAH].[POSTED] = 'Y'
                          AND [BAH].[VALUE] > 0
                          AND [BAH].[SUPP] <> '')
           AND EXISTS (SELECT TOP 1 1
                         FROM [dbo].[Settings] AS [SET]
                        WHERE [SET].[KeyName] = 'SupplierRemittance_On'
                          AND [SET].[KeyValue] = 'Y')
           AND EXISTS (SELECT TOP 1 1
                         FROM [dbo].[Allocations] AS [ALO]
                        WHERE [ALO].[BATCHNO] = @BATCHNO)
        BEGIN
            SELECT 'RunReportToCase'    AS [Function],
                   'SupplierRemittance' AS [Report],
                   0                    AS [Confirm],
                   @BATCHNO             AS [P1]
        END

        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN            
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                          FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>'
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@CLCONTROL)) + '"/>') AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
 END
GO

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

CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMPurchaseBill] (
       @BATCHNO    INT,
       @POSTFWD    VARCHAR(1),
       @HANDLER    VARCHAR(10))
AS
  /******************************************************************************************************
  * Update Purchase Bill Posting Logic                                                                  *
  *                                                                                                     *
  * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMPurchaseBill]                                   *
  *                                                                                                     *
  * Modification History:                                                                               *
  * 2021-11-17    Balamurugan C        Created                                                          *
  * 2022-02-17    John Ginnane         Refactored code                                                  *
  * 2022-06-16    John Ginnane         Added error handling                                             *
  * 2022-10-17    Ghayathri.S.V        Modified - Fee and Matter data in Matter Ledger and 
                                                  Nominal Ledger respectively.                          *
  * 2024-01-22    Revathy.D            Handled creating multiple records in supplier ledger
                                       Ticket Id- 17680                                                 *
  * 2024-01-23    Revathy.D            Finely tuned the join - 17680                                    *
  * 2024-02-29    Balamurugan.C        Changed outlaypending column to pending outlay from control      *
  *******************************************************************************************************/
BEGIN
    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO
                      AND [BAH].[POSTED] <> 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END
    
    BEGIN TRY
        BEGIN TRAN
        
        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = 3064
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END

        DECLARE @CURYEAR       INT
        DECLARE @CURPER        INT
        DECLARE @PENDINGOUTLAY VARCHAR(10)
        DECLARE @VATNOMINAL    VARCHAR(10)
        DECLARE @CREDITORS     VARCHAR(10)
        DECLARE @INVCR         INT
        DECLARE @TODAY         DATETIME
        
        SELECT @CURYEAR       = [CON].[YEAR],
               @CURPER        = [CON].[CURPER],
               @PENDINGOUTLAY = [CON].[PENDINGOUTLAY],
               @VATNOMINAL    = [CON].[VAT],
               @CREDITORS     = [CON].[CREDITOR],
               @INVCR         = 1,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY         = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
          FROM [dbo].[control] AS [CON]

        SELECT @INVCR = CASE WHEN [BAH].[INVCR] = 'C' THEN -1 ELSE @INVCR END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Make sure transaction is in correct year and period
        UPDATE [BAH]
           SET [BAH].[YEAR]  = @CURYEAR,
               [BAH].[PERNO] = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Matter Ledger
        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT [BAD].[MATTER],                 /* MATTER */
               [BAD].[BATCHNO],                /* BATCHNO */
               [BAD].[PREF],                   /* PREF */
               [BAD].[DATE],                   /* DATE */
               [BAD].[REF],                    /* REF */
               [BAD].[NARR],                   /* NARR */
               0,                              /* VALUED */
               [BAD].[VALUE] * @INVCR,         /* VALUEO */
               0,                              /* VALUEC */
               [BAD].[FEE],                    /* FEE */
               [BAD].[PERNO],                  /* PER */
               [BAD].[YEAR],                   /* YEAR */
               @TODAY,                         /* ENTRYDATE */
               LEFT([BAD].[MATTER], 6),        /* CLIENT */
               0,                              /* VALUECC */
               0,                              /* VALUECD */
               '',                             /* DEPOSITTYPE */
               0,                              /* CURVALUED */
               [BAD].[CURRENCYVALUE] * @INVCR, /* CURVALUEO */
               0,                              /* CURVALUEC */
               0,                              /* CURVALUECC */
               0,                              /* CURVALUECD */
               '',                             /* BILLED */
               0,                              /* BILLINGYEAR */
               0,                              /* BILLINGPERIOD */
               NULL,                           /* BILLINGDATE */
               0,                              /* BilledOutlayValue */
               0,                              /* InvoiceNo */
               0,                              /* IncludeInBill */
               NULL                            /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] = 'O'

        -- Pending Outlay
        IF @PENDINGOUTLAY = 'Y'
        BEGIN
            INSERT INTO [dbo].[PendingOutlay] (
                   [MATTER],
                   [DATE],
                   [SUPPLIER],
                   [REF],
                   [NARRATIVE],
                   [VALUE])
            SELECT [BAD].[MATTER],
                   [BAD].[DATE],
                   [BAH].[SUPP],
                   [BAD].[REF],
                   [BAD].[NARR],
                   [BAD].[VALUE] * @INVCR
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[BatchDetails] AS [BAD]
                           ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
             WHERE [BAH].[BATCHNO] = @BATCHNO
               AND [BAD].[OUTLAY] = 'O'
        END

        -- Log last activity
        UPDATE [MAT]
           SET [MAT].[LastAct]     = @TODAY,
               [MAT].[LastActType] = 'Outlay Inv',
               [MAT].[LastActWho]  = @HANDLER
          FROM [dbo].[matters] AS [MAT]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAD].[MATTER] = [MAT].[Code]
         WHERE [BAD].[BATCHNO] = @BATCHNO

        -- NominalLedger entry for BatchDetails
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT [BAD].[CODE],                   /* CODE */
               [BAH].[BRANCH],                 /* BRANCH */
               [BAD].[BATCHNO],                /* BATCHNO */
               [BAD].[PREF],                   /* PREF */
               [BAD].[DATE],                   /* DATE */
               [BAD].[REF],                    /* REF */
               [BAD].[NARR],                   /* NARR */
               [BAD].[MATTER],                 /* MATTER */
               [BAD].[SUPP],                   /* SUPP */
               [BAD].[FEE],                    /* FEE */
               [BAD].[VALUE] * @INVCR,         /* VALUE */
               [BAD].[CURRENCYVALUE] * @INVCR, /* CURRENCYVALUE */
               [BAH].[PERNO],                  /* PER */
               @CURYEAR,                       /* YEAR */
               @TODAY,                         /* ENTRYDATE */
               0,                              /* RECNO */
               NULL                            /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- NominalLedger entry for VAT details
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT @VATNOMINAL,                    /* CODE */
               [BAH].[BRANCH],                 /* BRANCH */
               [BAD].[BATCHNO],                /* BATCHNO */
               [BAD].[PREF],                   /* PREF */
               [BAD].[DATE],                   /* DATE */
               [BAD].[REF],                    /* REF */
               [BAD].[NARR],                   /* NARR */
               [BAD].[MATTER],                 /* MATTER */
               [BAD].[SUPP],                   /* SUPP */
               [BAD].[FEE],                    /* FEE */
               [BAD].[VATVAL] * @INVCR,        /* VALUE */
               [BAD].[CURRENCYVAT] * @INVCR,   /* CURRENCYVALUE */
               [BAH].[PERNO],                  /* PER */
               @CURYEAR,                       /* YEAR */
               @TODAY,                         /* ENTRYDATE */
               0,                              /* RECNO */
               NULL                            /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[VATVAL] <> 0

        -- Nominal Ledger entry for BatchH
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT @CREDITORS,                          /* CODE */
               [BAH].[BRANCH],                      /* BRANCH */
               [BAH].[BATCHNO],                     /* BATCHNO */
               [BAH].[PREF],                        /* PREF */
               [BAH].[DATE],                        /* DATE */
               [BAH].[REF],                         /* REF */
               [BAH].[NARR],                        /* NARR */
               [BAD].[MATTER],                      /* MATTER */
               [BAH].[SUPP],                        /* SUPP */
               [BAH].[FEE],                         /* FEE */
               [BAH].[VALUE] * -1 * @INVCR,         /* VALUE */
               [BAH].[CURRENCYVALUE] * -1 * @INVCR, /* CURRENCYVALUE */
               [BAH].[PERNO],                       /* PER */
               @CURYEAR,                            /* YEAR */
               @TODAY,                              /* ENTRYDATE */
               0,                                   /* RECNO */
               NULL                                 /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
		  INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- SupplierLedger entry
        INSERT INTO [dbo].[SupplierLedger] (
               [SUPP],
               [TYPE],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [YEAR],
               [PER],
               [ENTRYDATE],
               [THIRDPARTY],
               [THIRDPARTYVALUE],
               [MATTER],
               [PENDINGOUTLAY])
        SELECT [BAH].[SUPP],                /* SUPP */
               'B',                         /* TYPE */
               [BAH].[DATE],                /* DATE */
               [BAH].[REF],                 /* REF */
               [BAH].[BATCHNO],             /* BATCHNO */
               [BAH].[PREF],                /* PREF */
               [BAH].[NARR],                /* NARR */
               [BAH].[VALUE] * -1 * @INVCR, /* ORIGINAL */
               [BAH].[VALUE] * -1 * @INVCR, /* OSVALUE */
               @CURYEAR,                    /* YEAR */
               [BAH].[PERNO],               /* PER */
               @TODAY,                      /* ENTRYDATE */
               '',                          /* THIRDPARTY */
               0,                           /* THIRDPARTYVALUE */
               [BADETALS].[MATTER],         /* MATTER */
               ISNULL([BAD].[Pending], 0)			/* PENDINGOUTLAY */
          FROM [dbo].[BatchH] AS [BAH]
               OUTER APPLY (SELECT SUM([BAD].[VALUE] * @INVCR) AS [Pending]
                              FROM [dbo].[BatchDetails] AS [BAD]
                             WHERE [BAD].[BATCHNO] = [BAH].[BATCHNO]
                               AND [BAD].[OUTLAY] = 'O'
                               AND @PENDINGOUTLAY = 'Y') AS [BAD]
		 LEFT JOIN (SELECT TOP 1 Matter,BatchNo 
		            FROM [dbo].[BatchDetails]		             
					WHERE [BATCHNO] = @BATCHNO
					ORDER BY Pref DESC)  AS [BADETALS]
                       ON [BAH].[BATCHNO] = [BADETALS].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Finally we mark the transaction as posted
        UPDATE [BAH]
           SET [BAH].[POSTED] = 'Y',
               [BAH].[POSTFWD] = 'N'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN            
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>'
                     UNIOn
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@CREDITORS)) + '"/>') AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END

        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
END
GO

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

CREATE PROCEDURE [dbo].[KAAS_UpdatePostingSAMReceipts] (
       @BATCHNO    INT,
       @POSTFWD    VARCHAR(1),
       @HANDLER    VARCHAR(10))
AS
  /******************************************************************************************************
  * Update Receipts Logic                                                                               *
  *                                                                                                     *
  * Stored Procedure Name : [dbo].[KAAS_UpdatePostingSAMReceipts]                                       *
  *                                                                                                     *
  * Modification History:                                                                               *
  * 2022-01-13    Balamurugan C        Created                                                          *
  * 2022-02-01    Balamurugan C        Modified - Added Cast of Date statement for Batch Header         *
  *                                                and Detail Date field                                *
  * 2022-02-03    Balamurugan C        Modifed - Allocation Logic and Transfer Client Logic             *
  * 2022-02-21    Balamurugan C        Modified - Handled Current Period and Period End Date            *
  * 2022-03-09    Balamurugan.C        Modified - Handled TCL Statements                                *
  * 2022-06-02    John Ginnane         Refactored code                                                  *
  * 2023-05-16    Sadiq				   Modified   Updated @CLIENTRESERVEDOVERDRAWN Raise Error message  *
												  to return the value in SQL Exception in web api
  * 2023-10-11    Vignesh M            Modified - Instead of raising fatal error we raised user level 
									   custom error for the following exception
									   "As a result of this transfer, the client a/c reserve limit is 
										overdrawn on the following matters: "
  *******************************************************************************************************/
BEGIN
    SET NOCOUNT ON

    IF NOT EXISTS (SELECT TOP 1 1
                     FROM [dbo].[BatchH] AS [BAH]
                    WHERE [BAH].[BATCHNO] = @BATCHNO
                      AND [BAH].[POSTED] <> 'Y')
    BEGIN
        RAISERROR ('Transaction is already posted.', 16, 99)
        RETURN
    END

    BEGIN TRY
        BEGIN TRAN
        
        -- Rather than checking and displaying each EFT error message
        -- I'm going to check all of them and collate the outputs
        -- Then the user can be informed all multiple errors at once        
        DECLARE @EFTERROR VARCHAR(MAX)
        SET @EFTERROR = ''
        
        -- !need to check
        -- !1 if the Bank EFT details are entered!
        SELECT @EFTERROR = @EFTERROR + 
                           COALESCE([NOM].[DESC], [NOM].[CODE], '') + 
                           ': Bank EFT details need to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND [BAH].[THIRDPARTY] = 'Y'
           AND (ISNULL([NOM].[IBAN], '')        = ''
             OR ISNULL([NOM].[ACCOUNTNAME], '') = ''
             OR ISNULL([NOM].[SORTCODE], '')    = ''
             OR ISNULL([NOM].[ACCOUNTNO], '')   = ''
             OR ISNULL([NOM].[BIC], '')         = '')
             
        -- !need to check
        -- !1 if the Bank EFT details are entered!  
        SELECT @EFTERROR = @EFTERROR + 
                           COALESCE([NOM].[DESC], [NOM].[CODE], '') + 
                           ': Client EFT details needs to be entered!' + CHAR(13) + CHAR(10)
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CLIENTBANK] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAH].[EFTYorN] = 'Y'
           AND [BAH].[THIRDPARTY] = 'Y'
           AND (ISNULL([NOM].[IBAN], '')        = ''
             OR ISNULL([NOM].[ACCOUNTNAME], '') = ''
             OR ISNULL([NOM].[SORTCODE], '')    = ''
             OR ISNULL([NOM].[ACCOUNTNO], '')   = ''
             OR ISNULL([NOM].[BIC], '')         = '')
             
        IF ISNULL(@EFTERROR, '') <> ''
        BEGIN
            RAISERROR(@EFTERROR, 16, 99)
            RETURN
        END

        -- Make sure all matters are open
        DECLARE @CLOSEDMATTERS VARCHAR(MAX)

        SELECT @CLOSEDMATTERS = ISNULL(@CLOSEDMATTERS, '') +
                                CASE WHEN @CLOSEDMATTERS IS NULL
                                          THEN ''
                                     ELSE ', ' END + [MAT].[Code]
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = 3064
           AND [MAT].[Closed] = 'Y'

        IF ISNULL(@CLOSEDMATTERS, '') <> ''
        BEGIN
            SET @CLOSEDMATTERS = 'The following matters are closed: ' + @CLOSEDMATTERS + '. Cannot post.'
            RAISERROR (@CLOSEDMATTERS, 16, 99)
            RETURN
        END

        DECLARE @CURYEAR       INT
        DECLARE @CURPER        INT
        DECLARE @VATNOMINAL    VARCHAR(10)
        DECLARE @CLCONTROL     VARCHAR(10)
        DECLARE @TODAY         DATETIME
        DECLARE @THIRDPARTY    BIT
        DECLARE @SHOWNOBAR     BIT
        
        SELECT @CURYEAR       = [CON].[YEAR],
               @CURPER        = [CON].[CURPER],
               @VATNOMINAL    = [CON].[VAT],
               @CLCONTROL     = [CON].[CLIENT],
               @SHOWNOBAR     = CASE WHEN [CON].[NOBAR] = 'Y' THEN 1 ELSE 0 END,
               -- Get today's DATE and not TIME. This is to make sure it stil works with Clarion apps
               @TODAY         = DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)
          FROM [dbo].[control] AS [CON]

        SELECT @THIRDPARTY = CASE WHEN ISNULL([BAH].[THIRDPARTY], '') = 'Y'
                                       THEN 1
                                  ELSE 0 END
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- Make sure transaction is in correct year and period
        UPDATE [BAH]
           SET [BAH].[YEAR]     = @CURYEAR,
               [BAH].[PERNO]    = @CURPER + CASE WHEN @POSTFWD = 'Y' THEN 1 ELSE 0 END,
               [BAH].[CLIENTAC] = CASE WHEN ISNULL([NOM].[CLIENTAC], '') <> 'Y' THEN 'N' ELSE [BAH].[CLIENTAC] END
          FROM [dbo].[BatchH] AS [BAH]
               LEFT OUTER JOIN [dbo].[Nominal] AS [NOM]
                            ON [BAH].[CODE] = [NOM].[CODE]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        UPDATE [BAD]
           SET [BAD].[YEAR]  = [BAH].[YEAR],
               [BAD].[PERNO] = [BAH].[PERNO],
               [BAD].[DATE]  = [BAH].[DATE]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        DECLARE @DEPOSITAC   VARCHAR(1)
        DECLARE @DEPOSITTYPE VARCHAR(4)

        IF @THIRDPARTY = 0
        BEGIN
            SELECT @DEPOSITAC   = [NOM].[DEPOSITYN],
                   @DEPOSITTYPE = [NOM].[DEPOSITTYPE]
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Nominal] AS [NOM]
                           ON [BAH].[CODE] = [NOM].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
        END
        ELSE
        BEGIN
            SELECT @DEPOSITAC   = [NOM].[DEPOSITYN],
                   @DEPOSITTYPE = [NOM].[DEPOSITTYPE]
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Nominal] AS [NOM]
                           ON [BAH].[CLIENTBANK] = [NOM].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
        END

        IF @THIRDPARTY = 1
        BEGIN
            INSERT INTO [dbo].[MatterLedger] (
                   [MATTER],
                   [BATCHNO],
                   [PREF],
                   [DATE],
                   [REF],
                   [NARR],
                   [VALUED],
                   [VALUEO],
                   [VALUEC],
                   [FEE],
                   [PER],
                   [YEAR],
                   [ENTRYDATE],
                   [CLIENT],
                   [VALUECC],
                   [VALUECD],
                   [DEPOSITTYPE],
                   [CURVALUED],
                   [CURVALUEO],
                   [CURVALUEC],
                   [CURVALUECC],
                   [CURVALUECD],
                   [BILLED],
                   [BILLINGYEAR],
                   [BILLINGPERIOD],
                   [BILLINGDATE],
                   [BilledOutlayValue],
                   [InvoiceNo],
                   [IncludeInBill],
                   [ClearedDate])
            SELECT RTRIM([BAD].[MATTER]),                                                         /* MATTER */
                   [BAD].[BATCHNO],                                                               /* BATCHNO */
                   [BAD].[PREF],                                                                  /* PREF */
                   [BAD].[DATE],                                                                  /* DATE */
                   RTRIM([BAD].[REF]),                                                            /* REF */
                   RTRIM(LEFT([BAD].[NARR], 80)),                                                 /* NARR */
                   0,                                                                             /* VALUED */
                   0,                                                                             /* VALUEO */
                   ISNULL([BAD].[VALUE], 0),                                                      /* VALUEC */
                   RTRIM([BAD].[FEE]),                                                            /* FEE */
                   [BAD].[PERNO],                                                                 /* PER */
                   @CURYEAR,                                                                      /* YEAR */
                   @TODAY,                                                                        /* ENTRYDATE */
                   LEFT([BAD].[MATTER], 6),                                                       /* CLIENT */
                   CASE WHEN @DEPOSITAC  = 'Y' THEN 0 ELSE ISNULL([BAD].[VALUE], 0) END,          /* VALUECC */                                                                            
                   CASE WHEN @DEPOSITAC <> 'Y' THEN 0 ELSE ISNULL([BAD].[VALUE], 0) END,          /* VALUECD */
                   @DEPOSITTYPE,                                                                  /* DEPOSITTYPE */
                   0,                                                                             /* CURVALUED */
                   0,                                                                             /* CURVALUEO */
                   ISNULL([BAD].[CURRENCYVALUE], 0),                                              /* CURVALUEC */
                   CASE WHEN @DEPOSITAC  = 'Y' THEN 0 ELSE ISNULL([BAD].[CURRENCYVALUE], 0) END,  /* CURVALUECC */
                   CASE WHEN @DEPOSITAC <> 'Y' THEN 0 ELSE ISNULL([BAD].[CURRENCYVALUE], 0) END,  /* CURVALUECD */
                   '',                                                                            /* BILLED */
                   0,                                                                             /* BILLINGYEAR */
                   0,                                                                             /* BILLINGPERIOD */
                   NULL,                                                                          /* BILLINGDATE */
                   0,                                                                             /* BilledOutlayValue */
                   0,                                                                             /* InvoiceNo */
                   0,                                                                             /* IncludeInBill */
                   [BAH].[ClearedDate]                                                            /* ClearedDate */
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[BatchDetails] AS [BAD]
                           ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
             WHERE [BAH].[BATCHNO] = @BATCHNO
               AND [BAD].[OUTLAY] <> 'N'
        END

        INSERT INTO [dbo].[MatterLedger] (
               [MATTER],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [VALUED],
               [VALUEO],
               [VALUEC],
               [FEE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [CLIENT],
               [VALUECC],
               [VALUECD],
               [DEPOSITTYPE],
               [CURVALUED],
               [CURVALUEO],
               [CURVALUEC],
               [CURVALUECC],
               [CURVALUECD],
               [BILLED],
               [BILLINGYEAR],
               [BILLINGPERIOD],
               [BILLINGDATE],
               [BilledOutlayValue],
               [InvoiceNo],
               [IncludeInBill],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),                                                        /* MATTER */
               [BAD].[BATCHNO],                                                              /* BATCHNO */
               [BAD].[PREF],                                                                 /* PREF */
               [BAD].[DATE],                                                                 /* DATE */
               RTRIM([BAD].[REF]),                                                           /* REF */
               RTRIM(LEFT([BAD].[NARR], 80)),                                                /* NARR */
               CASE WHEN [BAD].[OUTLAY] = 'D' THEN ISNULL([BAD].[VALUE], 0) * -1 ELSE 0 END, /* VALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O' THEN ISNULL([BAD].[VALUE], 0) * -1 ELSE 0 END, /* VALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C' THEN ISNULL([BAD].[VALUE], 0) * -1 ELSE 0 END, /* VALUEC */
               RTRIM([BAD].[FEE]),                                                           /* FEE */
               [BAH].[PERNO],                                                                /* PER */
               @CURYEAR,                                                                     /* YEAR */
               @TODAY,                                                                       /* ENTRYDATE */
               LEFT([BAD].[MATTER], 6),                                                      /* CLIENT */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @DEPOSITAC <> 'Y'
                         THEN ISNULL([BAD].[VALUE], 0) * -1
                    ELSE 0 END,                                                              /* VALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @DEPOSITAC = 'Y'
                         THEN ISNULL([BAD].[VALUE], 0) * -1
                    ELSE 0 END,                                                              /* VALUECD */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @DEPOSITAC = 'Y'
                         THEN @DEPOSITTYPE
                    ELSE '' END,                                                             /* DEPOSITTYPE */
               CASE WHEN [BAD].[OUTLAY] = 'D'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                                                              /* CURVALUED */
               CASE WHEN [BAD].[OUTLAY] = 'O'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                                                              /* CURVALUEO */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                                                              /* CURVALUEC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @DEPOSITAC <> 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                                                              /* CURVALUECC */
               CASE WHEN [BAD].[OUTLAY] = 'C'
                     AND @DEPOSITAC  = 'Y'
                         THEN ISNULL([BAD].[CURRENCYVALUE], 0) * -1
                    ELSE 0 END,                                                              /* CURVALUECD */
               '',                                                                           /* BILLED */
               0,                                                                            /* BILLINGYEAR */
               0,                                                                            /* BILLINGPERIOD */
               NULL,                                                                         /* BILLINGDATE */
               0,                                                                            /* BilledOutlayValue */
               0,                                                                            /* InvoiceNo */
               0,                                                                            /* IncludeInBill */
               [BAH].[ClearedDate]                                                           /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] <> 'N'
        
        -- Check if client balance will be overdrawn with this posting
        -- Or if the balance dips below the minimum amount
        DECLARE @MATTERSCLIENTBALANCES TABLE (
                [Code]      VARCHAR(20) PRIMARY KEY,
                [ClientMin] DECIMAL(19, 2),
                [ClientCur] DECIMAL(19, 2),
                [ClientDep] DECIMAL(19, 2))

        ;WITH [CTE_MAT] ([Code], [ClientMin]) AS (
        SELECT DISTINCT [MAT].[Code], ISNULL([MAT].[ClientMin], 0)
          FROM [dbo].[BatchDetails] AS [BAD]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [MAT].[Code] = [BAD].[MATTER]
         WHERE [BAD].[BATCHNO] = @BATCHNO),
              [CTE_MTL] ([Code], [ClientMin], [ClientCur], [ClientDep]) AS (
        SELECT LTRIM(RTRIM([CTE_MAT].[Code])),
               [CTE_MAT].[ClientMin],
               SUM(ISNULL([MTL].[VALUECC], 0)),
               SUM(ISNULL([MTL].[VALUECD], 0))
          FROM [CTE_MAT]
               LEFT OUTER JOIN [dbo].[MatterLedger] AS [MTL]
                            ON [MTL].[MATTER] = [CTE_MAT].[Code]
               GROUP BY LTRIM(RTRIM([CTE_MAT].[Code])),
                        [CTE_MAT].[ClientMin])
        INSERT INTO @MATTERSCLIENTBALANCES (
               [Code],
               [ClientMin],
               [ClientCur],
               [ClientDep])
        SELECT [CTE_MTL].[Code],
               [CTE_MTL].[ClientMin] * -1,
               [CTE_MTL].[ClientCur],
               [CTE_MTL].[ClientDep]
          FROM [CTE_MTL]
        
        DECLARE @OVERDRAWNMATTERS VARCHAR(MAX)

        SELECT @OVERDRAWNMATTERS = ISNULL(@OVERDRAWNMATTERS, '') +
                                   CASE WHEN @OVERDRAWNMATTERS IS NULL
                                             THEN ''
                                        ELSE ', ' END + [TMP].[Code]
          FROM @MATTERSCLIENTBALANCES AS [TMP]
         WHERE [TMP].[ClientCur] > 0
            OR [TMP].[ClientDep] > 0
        
        IF ISNULL(@OVERDRAWNMATTERS, '') <> ''
        BEGIN
            IF @SHOWNOBAR <> 1
            BEGIN
                SET @OVERDRAWNMATTERS = 'The following matters will be overdrawn: ' + @OVERDRAWNMATTERS + '. Cannot post.'
                RAISERROR (@OVERDRAWNMATTERS, 16, 99)
                RETURN
            END
            ELSE
            BEGIN
                SET @OVERDRAWNMATTERS = 'As a result of this transfer, the client a/c is overdrawn on the following matters: ' + @OVERDRAWNMATTERS + '.'
                RAISERROR (@OVERDRAWNMATTERS, 5, 99)
            END
        END

        DECLARE @CLIENTRESERVEDOVERDRAWN VARCHAR(MAX)
        
        SELECT @CLIENTRESERVEDOVERDRAWN = ISNULL(@CLIENTRESERVEDOVERDRAWN, '') +
                                          CASE WHEN @CLIENTRESERVEDOVERDRAWN IS NULL
                                                    THEN ''
                                               ELSE ', ' END + [TMP].[Code]
          FROM @MATTERSCLIENTBALANCES AS [TMP]
         WHERE (ISNULL([TMP].[ClientCur], 0) + ISNULL([TMP].[ClientDep], 0)) > [TMP].[ClientMin]
        
        IF ISNULL(@CLIENTRESERVEDOVERDRAWN, '') <> ''
        BEGIN
            SET @CLIENTRESERVEDOVERDRAWN = 'As a result of this transfer, the client a/c reserve limit is overdrawn on the following matters: ' + @CLIENTRESERVEDOVERDRAWN + '.'
            RAISERROR (@CLIENTRESERVEDOVERDRAWN, 5, 99)
        END

        -- Update matter's last act
        UPDATE [MAT]
           SET [MAT].[LastActType] = CASE [BAD].[OUTLAY]
                                          WHEN 'D' THEN 'Debtor Rec'
                                          WHEN 'O' THEN 'Outlay Rec'
                                          WHEN 'C' THEN 'Client Rec'
                                          ELSE [MAT].[LastActType] END,
               [MAT].[LastAct]     = @TODAY,
               [MAT].[LastActWho]  = @HANDLER
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[matters] AS [MAT]
                       ON [BAD].[MATTER] = [MAT].[Code]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- "If transfer from client a/c"
        -- We will rebuild all relevant matter and client balances in a procedure later

        -- ! Update Nominal for Detail Lines
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAD].[CODE]),                                                      /* CODE */
               RTRIM([BAH].[BRANCH]),                                                    /* BRANCH */
               [BAD].[BATCHNO],                                                          /* BATCHNO */
               [BAD].[PREF],                                                             /* PREF */
               [BAD].[DATE],                                                             /* DATE */
               RTRIM([BAD].[REF]),                                                       /* REF */
               RTRIM([BAD].[NARR]),                                                      /* NARR */
               RTRIM([BAD].[MATTER]),                                                    /* MATTER */
               RTRIM([BAD].[SUPP]),                                                      /* SUPP */
               RTRIM([BAD].[FEE]),                                                       /* FEE */
               (ISNULL([BAD].[VALUE], 0) - ISNULL([BAD].[VATVAL], 0)) * -1,              /* VALUE */
               (ISNULL([BAD].[CURRENCYVALUE], 0) - ISNULL([BAD].[CURRENCYVAT], 0)) * -1, /* CURRENCYVALUE */
               [BAH].[PERNO],                                                            /* PER */
               @CURYEAR,                                                                 /* YEAR */
               @TODAY,                                                                   /* ENTRYDATE */
               0,                                                                        /* RECNO */
               [BAH].[ClearedDate]                                                       /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        -- ! Update Nominal for VAT
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM(@VATNOMINAL),                  /* CODE */
               RTRIM([BAH].[BRANCH]),               /* BRANCH */
               [BAD].[BATCHNO],                     /* BATCHNO */
               [BAD].[PREF],                        /* PREF */
               [BAD].[DATE],                        /* DATE */
               RTRIM([BAD].[REF]),                  /* REF */
               RTRIM([BAD].[NARR]),                 /* NARR */
               RTRIM([BAD].[MATTER]),               /* MATTER */
               RTRIM([BAD].[SUPP]),                 /* SUPP */
               RTRIM([BAD].[FEE]),                  /* FEE */
               ISNULL([BAD].[VATVAL], 0) * -1,      /* VALUE */
               ISNULL([BAD].[CURRENCYVAT], 0) * -1, /* CURRENCYVALUE */
               [BAH].[PERNO],                       /* PER */
               @CURYEAR,                            /* YEAR */
               @TODAY,                              /* ENTRYDATE */
               0,                                   /* RECNO */
               [BAH].[ClearedDate]                  /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[VATVAL] <> 0

        -- ! Update Nominal Client Ledger Control for Client A/c Transfer
        IF @THIRDPARTY = 1
        BEGIN
            INSERT INTO [dbo].[NominalLedger] (
                   [CODE],
                   [BRANCH],
                   [BATCHNO],
                   [PREF],
                   [DATE],
                   [REF],
                   [NARR],
                   [MATTER],
                   [SUPP],
                   [FEE],
                   [VALUE],
                   [CURRENCYVALUE],
                   [PER],
                   [YEAR],
                   [ENTRYDATE],
                   [RECNO],
                   [ClearedDate])
            SELECT RTRIM(@CLCONTROL),                /* CODE */
                   RTRIM([BAH].[BRANCH]),            /* BRANCH */
                   [BAD].[BATCHNO],                  /* BATCHNO */
                   [BAD].[PREF],                     /* PREF */
                   [BAD].[DATE],                     /* DATE */
                   RTRIM([BAD].[REF]),               /* REF */
                   RTRIM([BAD].[NARR]),              /* NARR */
                   RTRIM([BAD].[MATTER]),            /* MATTER */
                   RTRIM([BAD].[SUPP]),              /* SUPP */
                   RTRIM([BAD].[FEE]),               /* FEE */
                   ISNULL([BAD].[VALUE], 0),         /* VALUE */
                   ISNULL([BAD].[CURRENCYVALUE], 0), /* CURRENCYVALUE */
                   [BAH].[PERNO],                    /* PER */
                   @CURYEAR,                         /* YEAR */
                   @TODAY,                           /* ENTRYDATE */
                   0,                                /* RECNO */
                   [BAH].[ClearedDate]               /* ClearedDate */
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[BatchDetails] AS [BAD]
                           ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
             WHERE [BAH].[BATCHNO] = @BATCHNO
        END

        -- ! Nominal Updated for Client A/c Transfer
        INSERT INTO [dbo].[DebtorsLedger] (
               [MATTER],
               [TYPE],
               [CLIENT],
               [DATE],
               [REF],
               [BATCHNO],
               [PREF],
               [NARR],
               [ORIGINAL],
               [OSVALUE],
               [ORFEES],
               [OROUTLAY],
               [ORVAT],
               [OSFEES],
               [OSOUTLAY],
               [OSVAT],
               [VATCODE],
               [PER],
               [YEAR],
               [FEECODE],
               [ClearedDate])
        SELECT RTRIM([BAD].[MATTER]),                       /* MATTER */
               'R',                                         /* TYPE */
               RTRIM([MAT].[ClientCode]),                   /* CLIENT */
               [BAD].[DATE],                                /* DATE */
               RTRIM([BAD].[REF]),                          /* REF */
               [BAD].[BATCHNO],                             /* BATCHNO */
               [BAD].[PREF],                                /* PREF */
               RTRIM(RIGHT(RTRIM([BAD].[NARR]), 80)),       /* NARR */
               [BAD].[VALUE] * -1,                          /* ORIGINAL */
               CASE WHEN [BAH].[SINGLELINE] = 'Y'
                     AND [BAD].[ALLOCBATCH] = 0
                         THEN 0
                    ELSE ISNULL([BAD].[VALUE], 0) * -1 END, /* OSVALUE */
               0,                                           /* ORFEES */
               0,                                           /* OROUTLAY */
               0,                                           /* ORVAT */
               0,                                           /* OSFEES */
               0,                                           /* OSOUTLAY */
               0,                                           /* OSVAT */
               '',                                          /* VATCODE */
               [BAH].[PERNO],                               /* PER */
               @CURYEAR,                                    /* YEAR */
               '',                                          /* FEECODE */
               [BAH].[ClearedDate]                          /* ClearedDate */
           FROM [dbo].[BatchH] AS [BAH]
                INNER JOIN [dbo].[BatchDetails] AS [BAD]
                        ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
                INNER JOIN [dbo].[matters] AS [MAT]
                        ON [BAD].[MATTER] = [MAT].[Code]
          WHERE [BAH].[BATCHNO] = @BATCHNO
            AND [BAD].[OUTLAY] = 'D'

        -- ! If Receipt Correction
        -- !no allocation
        UPDATE [DTL]
           SET [DTL].[OSVALUE]  = 0,
               [DTL].[OSFEES]   = 0,
               [DTL].[OSOUTLAY] = 0,
               [DTL].[OSVAT]    = 0
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
               INNER JOIN [dbo].[DebtorsLedger] AS [DTL]
                       ON [BAD].[HEADBATCH] = [DTL].[BATCHNO]
                      AND [BAD].[HEADPREF] = [DTL].[PREF]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] = 'D'
           AND [BAH].[SINGLELINE] = 'Y'
           AND [BAD].[ALLOCBATCH] = 0

        -- Automatically allocate receipt
        DECLARE @SQL NVARCHAR(MAX)        
        SET @SQL = ''

        -- I have written this procedure to handle multiple allocations simultaneously
        SELECT @SQL = N'<Allocations User="' + @HANDLER + '">' + 
               (SELECT *
                  FROM (SELECT [BAD].[BATCHNO]    AS [ReceiptBatchNo],
                               [BAD].[PREF]       AS [ReceiptPostRef],
                               [BAD].[ALLOCBATCH] AS [InvoiceBatchNo],
                               [BAD].[ALLOCPREF]  AS [InvoicePostRef],
                               [BAD].[VALUE]      AS [AllocateValue],
                               CASE WHEN ISNULL([BAD].[ALLOCWRITEOFF], '') <> 'Y'
                                         THEN 'N'
                                    ELSE 'Y' END  AS [WriteOffRemainder]
                         FROM [dbo].[BatchH] AS [BAH]
                              INNER JOIN [dbo].[BatchDetails] AS [BAD]
                                      ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
                        WHERE [BAH].[TYPE] = 'R'
                          AND [BAD].[OUTLAY] = 'D'
                          AND [BAD].[ALLOCPREF] <> 0 -- Only check PREF because BATCHNO can be 0 for converted data
                          AND [BAH].[BATCHNO] = @BATCHNO) AS [Allocation]
                              FOR XML AUTO) +
               N'</Allocations>'

        IF ISNULL(@SQL, '') <> ''
        BEGIN
            EXEC [dbo].[KAAS_AutoAllocateTransactions] @SQL

            IF EXISTS (SELECT TOP 1 1
                         FROM [dbo].[BatchDetails] AS [BAD]
                        WHERE [BAD].[BATCHNO] = @BATCHNO
                          AND [BAD].[ALLOCWRITEOFF] = 'Y'
                          AND [BAD].[TYPE] = 'R'
                          AND [BAD].[OUTLAY] = 'D'
                          AND [BAD].[ALLOCPREF] <> 0)
            BEGIN
                RAISERROR ('Auto write-off Journal generated - please update', 5, 99)
            END
        END

        -- Iterate over each batch detail and call ky_BGPaid if BAD.AllocBatch <> 0        
        DECLARE @ALLOCATIONS TABLE ([InvoiceBatchNo] INT)

        INSERT INTO @ALLOCATIONS ([InvoiceBatchNo])
        SELECT [BAD].[ALLOCBATCH]
          FROM [dbo].[BatchH] AS [BAH]
               INNER JOIN [dbo].[BatchDetails] AS [BAD]
                       ON [BAH].[BATCHNO] = [BAD].[BATCHNO]
         WHERE [BAH].[BATCHNO] = @BATCHNO
           AND [BAD].[OUTLAY] = 'D'
           AND [BAD].[ALLOCPREF] <> 0
        
        DECLARE @ALLOCBATCH INT
        WHILE EXISTS (SELECT TOP 1 1 FROM @ALLOCATIONS)
        BEGIN
            SELECT TOP 1 @ALLOCBATCH = [TMP].[InvoiceBatchNo]
              FROM @ALLOCATIONS AS [TMP]

            EXEC [dbo].[KAAS_BGPaid] NULL, @ALLOCBATCH, 0, 0, 0

            DELETE [TMP]
              FROM @ALLOCATIONS AS [TMP]
             WHERE [TMP].[InvoiceBatchNo] = @ALLOCBATCH
        END

        -- ! Update Nominal for Batch Header
        INSERT INTO [dbo].[NominalLedger] (
               [CODE],
               [BRANCH],
               [BATCHNO],
               [PREF],
               [DATE],
               [REF],
               [NARR],
               [MATTER],
               [SUPP],
               [FEE],
               [VALUE],
               [CURRENCYVALUE],
               [PER],
               [YEAR],
               [ENTRYDATE],
               [RECNO],
               [ClearedDate])
        SELECT RTRIM([BAH].[CODE]),              /* CODE */
               RTRIM([BAH].[BRANCH]),            /* BRANCH */
               [BAH].[BATCHNO],                  /* BATCHNO */
               [BAH].[PREF],                     /* PREF */
               [BAH].[DATE],                     /* DATE */
               RTRIM([BAH].[REF]),               /* REF */
               RTRIM([BAH].[NARR]),              /* NARR */
               RTRIM([BAH].[MATTER]),            /* MATTER */
               RTRIM([BAH].[SUPP]),              /* SUPP */
               RTRIM([BAH].[FEE]),               /* FEE */
               ISNULL([BAH].[VALUE], 0),         /* VALUE */
               ISNULL([BAH].[CURRENCYVALUE], 0), /* CURRENCYVALUE */
               [BAH].[PERNO],                    /* PER */
               @CURYEAR,                         /* YEAR */
               @TODAY,                           /* ENTRYDATE */
               0,                                /* RECNO */
               [BAH].[ClearedDate]               /* ClearedDate */
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO

        IF @THIRDPARTY = 1
        BEGIN
            INSERT INTO [dbo].[NominalLedger] (
                   [CODE],
                   [BRANCH],
                   [BATCHNO],
                   [PREF],
                   [DATE],
                   [REF],
                   [NARR],
                   [MATTER],
                   [SUPP],
                   [FEE],
                   [VALUE],
                   [CURRENCYVALUE],
                   [PER],
                   [YEAR],
                   [ENTRYDATE],
                   [RECNO],
                   [ClearedDate])
            SELECT RTRIM([BAH].[CLIENTBANK]),             /* CODE */
                   RTRIM([BAH].[BRANCH]),                 /* BRANCH */
                   [BAH].[BATCHNO],                       /* BATCHNO */
                   [BAH].[PREF],                          /* PREF */
                   [BAH].[DATE],                          /* DATE */
                   RTRIM([BAH].[REF]),                    /* REF */
                   RTRIM([BAH].[NARR]),                   /* NARR */
                   RTRIM([BAH].[MATTER]),                 /* MATTER */
                   RTRIM([BAH].[SUPP]),                   /* SUPP */
                   RTRIM([BAH].[FEE]),                    /* FEE */
                   ISNULL([BAH].[VALUE], 0) * -1,         /* VALUE */
                   ISNULL([BAH].[CURRENCYVALUE], 0) * -1, /* CURRENCYVALUE */
                   [BAH].[PERNO],                         /* PER */
                   @CURYEAR,                              /* YEAR */
                   @TODAY,                                /* ENTRYDATE */
                   0,                                     /* RECNO */
                   [BAH].[ClearedDate]                    /* ClearedDate */
              FROM [dbo].[BatchH] AS [BAH]
             WHERE [BAH].[BATCHNO] = @BATCHNO
        END

        -- !Client A/c Bank Transfer Post
        UPDATE [BAH]
           SET [BAH].[POSTED]  = 'Y',
               [BAH].[POSTFWD] = 'N'
          FROM [dbo].[BatchH] AS [BAH]
         WHERE [BAH].[BATCHNO] = @BATCHNO
        
        -- After we're done try to recalculate only the relevant balances
        IF OBJECT_ID(N'KAAS_RebuildBalances', N'P') IS NOT NULL
        BEGIN            
            /* Get list of affected matters, suppliers, and nominals to rebuild */
            DECLARE @REBUILDXML NVARCHAR(MAX)
            SET @REBUILDXML = N'<data><matters>'

            SELECT @REBUILDXML = @REBUILDXML + [A].[MATTER]
              FROM (SELECT N'<matter code="' + [BAH].[MATTER] + '"/>' AS [MATTER]
                          FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAH].[MATTER]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                    UNION
                    SELECT N'<matter code="' + [BAD].[MATTER] + '"/>' AS [MATTER]
                      FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[matters] AS [MAT]
                                   ON [MAT].[Code] = [BAD].[MATTER]
                     WHERE [BAD].[BATCHNO] = @BATCHNO) AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</matters><nominals>'
            
            SELECT @REBUILDXML = @REBUILDXML + [A].[CODE]
              FROM (SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CODE])) + '"/>' AS [CODE]
                      FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CODE] = [NOM].[CODE]
                     WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION 
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAH].[CLIENTBANK])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchH] AS [BAH]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAH].[CLIENTBANK] = [NOM].[CODE]
                      WHERE [BAH].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM([BAD].[CODE])) + '"/>' AS [CODE]
                       FROM [dbo].[BatchDetails] AS [BAD]
                           INNER JOIN [dbo].[Nominal] AS [NOM]
                                   ON [BAD].[CODE] = [NOM].[CODE]
                      WHERE [BAD].[BATCHNO] = @BATCHNO
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@VATNOMINAL)) + '"/>'
                     UNION
                     SELECT N'<nominal code="' + LTRIM(RTRIM(@CLCONTROL)) + '"/>') AS [A]

            SET @REBUILDXML = @REBUILDXML + N'</nominals><suppliers>'

            SELECT @REBUILDXML = @REBUILDXML + N'<supplier code="' + LTRIM(RTRIM([BAH].[SUPP])) + '"/>'
              FROM [dbo].[BatchH] AS [BAH]
                   INNER JOIN [dbo].[Suppliers] AS [SUP]
                           ON [BAH].[SUPP] = [SUP].[CODE]
             WHERE [BAH].[BATCHNO] = @BATCHNO
             
            SET @REBUILDXML = @REBUILDXML + N'</suppliers></data>'

            EXEC [dbo].[KAAS_RebuildBalances] @REBUILDXML
        END
        
        COMMIT TRAN
    END TRY
    BEGIN CATCH
        DECLARE @ErrorMsg      NVARCHAR(4000)
        DECLARE @ErrorSeverity INT
        DECLARE @ErrorState    INT

        SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''),
               @ErrorSeverity = ERROR_SEVERITY(),
               @ErrorState    = ERROR_STATE()

        RAISERROR (@ErrorMsg, @ErrorSeverity, @ErrorState)

        IF @@TRANCOUNT > 0
        BEGIN
            ROLLBACK TRANSACTION
        END
    END CATCH
 END
GO

IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_UpdateSAMApprovedChequeRequisition' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_UpdateSAMApprovedChequeRequisition] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_UpdateSAMApprovedChequeRequisition]
	(
		@Date			DATETIME     = NULL,
		@OutlayCode		VARCHAR(4)	 = '',
		@ThirdParty		CHAR(1)      = '',
		@Narrative		VARCHAR(100) = '',
		@Note			VARCHAR(100) = '',
		@ReqNo			INT			 = 0
	)
AS
/*******************************************************************************************************
* Update the Approved Cheque Reqisition Details                                                       * 
*                                                                                                      *
* Stored Procedure Name : [dbo].[dbo].[KAAS_UpdateSAMApprovedChequeRequisition]      				   *
*                                                                                                      *
* Modification History:                                                                                *
* 2021-09-14    Balamurugan.C        Created                                                           *
 *******************************************************************************************************/
BEGIN
	IF EXISTS
		(
			SELECT TOP 1 1 
				  FROM [dbo].[ChequeRequisitionHeader]
				 WHERE [ReqNo] = @ReqNo
		)
	BEGIN
			UPDATE [dbo].[ChequeRequisitionHeader]
			   SET [Date]		  = @Date,
				   [OutlayCode]   = @OutlayCode,
				   [ThirdParty]   = @ThirdParty,
				   [Narrative]    = @Narrative,
				   [ReturnReason] = @Note
			 WHERE [ReqNo]		  = @ReqNo 
	END
END

GO


IF EXISTS(SELECT
             TOP 1 1
            FROM sys.[objects] SO
           WHERE SO.[name] = N'KAAS_UpdateSAMFNLDetails'
             AND SO.[type] = 'P'
		  ) 
BEGIN 
 DROP PROCEDURE [dbo].[KAAS_UpdateSAMFNLDetails] 
END
GO
CREATE PROCEDURE [dbo].[KAAS_UpdateSAMFNLDetails] 
			(
                     @MatterCode    VARCHAR(20),
                     @FNLDate       DATETIME,
                     @FNLName       VARCHAR(50),
                     @FNLAddress    VARCHAR(100),
                     @FNLFees       DECIMAL,
                     @FNLVat        DECIMAL,
                     @FNLOutlay     DECIMAL,
                     @FNLTotal      DECIMAL,
                     @ClientMin     DECIMAL,
					 @User          VARCHAR(30) = '',
                     @Result        TINYINT OUTPUT         
    		) 
AS
/*************************************************************************************************************************************************
*                                                                                                                                                *
*Used to list the matter ledger                                                                                                                  *
* Stored Procedure Name: [dbo].[KAAS_UpdateSAMFNLDetails]	'000001/0000','2021-04-12 17:54:13.453','RAJ','SET ADDRESS','40','20','10','70',50,0 * 
* Modification History:                                                                                                                          *
* 2021-03-11 Natarajan S        Created		                                                                                                     *
* 2021-07-13 Natarajan S        Modified - Added Formatting		                                                                                 *
* 2022-03-08 Balamurugan.C      Modified - Handled TCL Statements and Formatting                                                                 *     
* 2023-10-25 Revathy.D          Modified - Added the missed param 'Handler code' to KAAS_INSERTSAMMatterLedgerComment                            *     
**************************************************************************************************************************************************/
BEGIN
	BEGIN TRY 
	 BEGIN TRANSACTION

		  DECLARE @Narrative VARCHAR(80) 
		  DECLARE @SpaceVal  INT 
		  DECLARE @NameLen   INT
		  DECLARE @CurrDate  DATETIME
			  SET @CurrDate = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](GETDATE(), @User)), 0)
            
		  UPDATE [OMO]
			 SET [OMO].[FNL_Date]      = @FNLDate,
				 [OMO].[FNL_Name]      = @FNLName,
				 [OMO].[FNL_Address]   = @FNLAddress,
				 [OMO].[FNL_Fees]      = @FNLFees,
				 [OMO].[FNL_VAT]       = @FNLVat,
				 [OMO].[FNL_Outlay]    = @FNLOutlay
			FROM [dbo].[OpenMattersOnly] [OMO]
		   WHERE [OMO].[Code]          = @MatterCode
         
		  UPDATE [MAT]
			 SET [MAT].[FNL_Date]      = @FNLDate,
				 [MAT].[FNL_Name]      = @FNLName,
				 [MAT].[FNL_Address]   = @FNLAddress,
				 [MAT].[FNL_Fees]      = @FNLFees,
				 [MAT].[FNL_VAT]       = @FNLVat,
				 [MAT].[FNL_Outlay]    = @FNLOutlay,
				 [MAT].[FNL_Total]     = @FNLTotal
			FROM [dbo].[Matters] [MAT]
		   WHERE [MAT].[Code]          = @MatterCode
                    
			 SET @NameLen              = LEN(@FNLName);
			 SET @SpaceVal             = 50 - @NameLen;
			 SET @Narrative            = CONCAT('FNL: €', @FNLTotal,        SPACE(2),
												@FNLName, SPACE(@SpaceVal), SPACE(2),
											   'Fees: €', @FNLFees,         SPACE(2),
											   'O/L: €',  @FNLOutlay) 

			EXEC [dbo].[KAAS_INSERTSAMMatterLedgerComment] @MatterCode, @Narrative, @ClientMin, @CurrDate,@User, @Result
     
			 SET @Result = 1
				  
	 COMMIT TRANSACTION                      
	END TRY

	BEGIN CATCH
				SET @Result = 0
			DECLARE @ErrorMsg      NVARCHAR(4000), 
					@ErrorSeverity INT,
					@ErrorState    INT; 

			 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
					@ErrorSeverity = ERROR_SEVERITY(), 
					@ErrorState    = ERROR_STATE()

		  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
				 IF @@TRANCOUNT > 0  
					BEGIN
						ROLLBACK TRANSACTION;
					END     
	END CATCH
END
GO

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

go 

CREATE PROCEDURE 
	   [dbo].[KAAS_UPDATESAMMatterLedgerComment] 
	  (@MatterCode  VARCHAR(20),
	   @Narrative   VARCHAR(MAX),
	   @HandlerCode VARCHAR(20),
	   @LRef	    VARCHAR(20),
	   @Result	    TINYINT OUTPUT) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].[KAAS_UPDATESAMMatterLedgerComment]									 * 
  * Modification History:                                                                                *
  * 2023-05-09 Vignesh M          Created									                             *     
  ********************************************************************************************************/
  BEGIN 
   	  BEGIN TRY
		BEGIN TRAN
			  
			  UPDATE [MAT]
				 SET [MAT].[NARR] = @Narrative,
					 [MAT].[REF]  = @HandlerCode
				FROM [dbo].[MatterLedger] [MAT]
			   WHERE [MAT].[MATTER] = @MatterCode AND [MAT].[LREF] = @LRef AND [MAT].[BATCHNO] = 0


			   SET @Result = 1

		COMMIT TRAN
	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
			 IF @@TRANCOUNT > 0  
				BEGIN
					ROLLBACK TRANSACTION;
				END   
	 END CATCH
  END 

GO
 IF EXISTS (SELECT TOP 1 1 
             FROM sys.[objects] SO 
            WHERE SO.[name] = N'KAAS_UpdateSAMSystemOptionsDetails' 
              AND SO.[type] = 'P') 
  BEGIN 
      DROP PROCEDURE [dbo].[KAAS_UpdateSAMSystemOptionsDetails] 
  END 
GO 
CREATE PROCEDURE [dbo].[KAAS_UpdateSAMSystemOptionsDetails]
       (
			@TabName				   VARCHAR(50)  = '',
			@Licencee				   VARCHAR(40)  = '',
			@VatNo					   VARCHAR(20)  = '',
			@Year					   INT		    = 0,
			@DebtorsControlAc		   VARCHAR(10)  = '',
			@CreditorsControlAc		   VARCHAR(10)  = '',
			@CurrentPeriod			   INT		    = 0,
			@NextPeriodEnd			   DATETIME	    = NULL,
			@OutlayControlAc		   VARCHAR(10)  = '',
			@VatAc					   VARCHAR(10)  = '',
			@YearEndDate			   DATETIME     = NULL,
			@ProfitLossAc			   VARCHAR(10)  = '',
			@ClientLedgerControl	   VARCHAR(10)  = '',
			@StdOutlayBudget		   DECIMAL      = 0,
			@FeeWriteOffAc			   VARCHAR(10)  = '',
			@OutlayWriteOffAc		   VARCHAR(10)  = '',
			@LastBillNo				   INT          = 0,
			@VatExclusionCode		   VARCHAR(1)   = '',
			@PurchBillWriteOffAc	   VARCHAR(10)  = '',
			@DefaultOfficeAc		   VARCHAR(10)  = '',
			@DefaultVat				   VARCHAR(1)   = '',
			@FeeExclusionCode		   VARCHAR(10)  = '',
			@DefaultClientDepositAc    VARCHAR(10)  = '',
			@MiscOutlay				   VARCHAR(10)  = '',
			@DefaultMiscOutlayFee	   VARCHAR(10)  = '',
			@DefaultPettyCash		   VARCHAR(10)  = '',
			@WithHoldingTax			   VARCHAR(10)  = '',
			@EnableFNL				   VARCHAR(10)  = '',
			@ShowConvertedLedgerBtn	   VARCHAR(1)   = '',
			@EnableClientDB			   VARCHAR(1)   = '',
			@UK						   VARCHAR(1)   = '',
			@EnableDeedWills		   VARCHAR(1)   = '',
			@YearEndCompleted		   VARCHAR(1)   = '',
			@EnableFileManager		   VARCHAR(1)   = '',
			@UseOutlayType			   VARCHAR(1)   = '',
			@PendingOutlay			   VARCHAR(1)   = '',
			@UseBranches			   VARCHAR(1)   = '',
			@EnableBankRec			   VARCHAR(1)   = '',
			@BillPrinting			   VARCHAR(1)   = '',
			@UniqueMatterNumber		   VARCHAR(1)   = '',
			@TaggedBatches			   VARCHAR(1)   = '',
			@OverdrawnClientAc		   VARCHAR(1)   = '',
			@IntrestCalculator		   VARCHAR(1)   = '',
			@WordPerfect			   VARCHAR(1)   = '',
			@Indicator24			   VARCHAR(1)   = '',
			@Indicator25			   VARCHAR(1)   = '',
			@Indicator26			   VARCHAR(1)   = '',
			@Indicator27			   VARCHAR(1)   = '',
			@Indicator28			   VARCHAR(1)   = '',
			@Indicator29			   VARCHAR(1)   = '',
			@Indicator30			   VARCHAR(1)   = '',
			@DemoExpire				   INT          = 0,
			@MaxMatter				   DECIMAL      = 0,
			@CaseMgrLink			   VARCHAR(1)   = '',
			@TimeCostingInstalled	   VARCHAR(1)   = '',
			@ForceFeeEarner			   VARCHAR(1)   = '',
			@LabelPrinter			   VARCHAR(1)   = '',
			@FeeReporting			   VARCHAR(10)  = '',
			@CompositeBilling		   VARCHAR(1)   = '',
			@AllowFwPostingJournals		   VARCHAR(1)   = '',
			@SolicitorCategory		   VARCHAR(6)   = '',
			@OtherPartyCategory		   VARCHAR(6)   = '',
			@SupplierCategory		   VARCHAR(6)   = '',
			@SystemCategoryType		   VARCHAR(6)   = '',
			@AutoNumberClient		   VARCHAR(1)   = '',
			@AutoAlphaNumbering 	   VARCHAR(1)   = '',
			@CloseMatterTimeBarred 	   VARCHAR(1)   = '',
			@SupplierRemittance 	   VARCHAR(1)   = '',
			@EFTDefaultON		 	   VARCHAR(1)   = '',
			@EFTEmailToSend		 	   VARCHAR(1)   = '',
			@EFTTransactionLimit	   DECIMAL		= 0.00,
			@EFTNoOfTransactionLimit   INT			= 0,
			@EFTEmailSubject		   VARCHAR(250)   = '',
			@EFTEmailMessage		   VARCHAR(1000)   = '',
			@DefaultPrebilledOutlay    VARCHAR(1)   = '',
			@MatterOutlayBudgetChkON   VARCHAR(1)   = '',
			@ThirdPartyLimit		   DECIMAL      = 0,
			@DatePastValidation		   INT          = 0,
			@DateFutureValidation	   INT		    = 0,
			@ConversionRate			   DECIMAL	    = 0,
			@PromptRef1				   VARCHAR(20)  = '',
			@PromptRef2				   VARCHAR(20)  = '',
			@PromptRef3				   VARCHAR(20)  = '',
			@NextFile				   INT          = 0,
			@ClosedFileNo			   INT          = 0,
			@ChequeType				   VARCHAR(2)   = '',
			@EnableChequePrinting	   VARCHAR(1)   = '',
			@LabelNo                   VARCHAR(2)   = '',									    
			@InvoiceApproverEmail      VARCHAR(100) = '',   
			@ChequeApproverEmail       VARCHAR(100) = '',
			@NotifyReturnInvoice       VARCHAR(1)   = '',
			@NotifyApprovedInvoice     VARCHAR(1)   = '',
			@NotifyReturnCheque        VARCHAR(1)   = '',
			@NotifyApprovedCheque      VARCHAR(1)   = '',
			@SMTPMailServer			   VARCHAR(100) = '',
			@MoneyLaunderingCheck	   VARCHAR(1)   = '',
			@MoneyLaunderingDept	   VARCHAR(20)  = '',
			@MoneyLaunderingFE	       VARCHAR(20)  = '',
			@MoneyLaunderingWorkType   VARCHAR(20)  = '',
			@ClientLabel	           VARCHAR(100)  = '',
			@ContactLabel	           VARCHAR(100)  = '',
			@MatterLabel	           VARCHAR(100)  = '',
			@CaseLabel	               VARCHAR(100)  = '',
			@CaseMatterLabel	       VARCHAR(100)  = '',
			@FeeEarnerLabel	           VARCHAR(100)  = '',
			@PartnerLabel	           VARCHAR(100)  = '',
			@AssociateLabel	           VARCHAR(100)  = '',
			@BranchLabel	           VARCHAR(100)  = '',
			@PostalCodeLabel	       VARCHAR(100)  = '',
			@ManualClientCode	       VARCHAR(100)  = '',
			@ShowMatterCode	           VARCHAR(100)  = '',
			@AutoNumberIfBlank	       VARCHAR(100)  = '',
			@AutoNumber	               VARCHAR(20)  = '',
			@AutoAlphaClientNumbering  VARCHAR(20)  = '',
			@UniqueMatterCodeNumbering VARCHAR(20)  = '',
			@AzureBlobStorageClientFolder				   VARCHAR(100)   = '',
			@AzureBlobStorageClientVersionsFolder		   VARCHAR(100)  = '',
			@AzureBlobStorageTemplatesFolder		       VARCHAR(100)  = ''


	   )
        
AS
/*******************************************************************************************************
* This SP used to update the System Options details								                       *
*                                                                                                      *
* Stored Procedure Name	: [dbo].[KAAS_UpdateSAMSystemOptionsDetails]								   *
* Copied From           : ky_NETSYSCONUpdateConfigurationSettings10								       *						   
*                                                                                                      *
* Modification History	:                                                                              *
* 2021-08-09	Balamurugan.C		Created			                                                   *
* 2021-09-20    Balamurugan.C       Modified- Removed Year End Date from control table and used        *
									           srettings table year end date                           *
* 2022-02-28    Balamurugan.C       Modified - Handled TCL Statements                                  *
* 2022-11-24    Ghayathri.S.V       Modified - Handled updaing values from code configuration tab      *
* 2024-01-23    Ghayathri.S.V       Modified- Handled updating values DefaultPrebilledOutlay           * 
* 2024-02-28    Sadiq				Modified- Added Azure Container dynamic values					   *
* 2024-03-25    Ghayathri.S.V		Modified- Added EFT Default values					   			   *
*******************************************************************************************************/

BEGIN
	SET NOCOUNT ON
	 BEGIN TRY
	  BEGIN TRAN
		IF(@TabName = 'SystemOptions')
			BEGIN

				-- Log changes to LastBill
				DECLARE @CURLASTBILL VARCHAR(20)
				    SELECT TOP 1 @CURLASTBILL = CONVERT(VARCHAR(20), ISNULL(CON.[LASTBILL], 0))
					  FROM [dbo].[control] AS CON

				IF ISNULL(@CURLASTBILL, '') <> ISNULL(@LastBillNo, '')
				  BEGIN
				 	INSERT 
				 	  INTO [dbo].[Log] 
				 	   (
				 		   [DATE],
				 		   [USER],
				 		   [EVENT]
				 	   )
				 	SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0),
				 		   [dbo].[ky_NETFNGetLoggedOnHandler](),
				 		   'System Options Change (Last Bill No) from: ' + ISNULL(@CURLASTBILL, '') + ' to: ' + ISNULL(@LastBillNo, '')
				  END

					UPDATE [dbo].[Control]
					   SET [Name]				        = @Licencee,
						   [VatNo]				        = @VatNo,
						   [Year]				        = @Year,
						   [Debtors]			        = @DebtorsControlAc,
						   [Creditor]			        = @CreditorsControlAc,
						   [CurPer]				        = @CurrentPeriod,
						   [Outlay]				        = @OutlayControlAc,
						   [Vat]				        = @VatAc,
						   [Pl]					        = @ProfitLossAc,
						   [Client]				        = @ClientLedgerControl,
						   [OutlayBudget]		        = @StdOutlayBudget,
						   [FeesWriteOff]		        = @FeeWriteOffAc,
						   [OutlayWriteOff]		        = @OutlayWriteOffAc,
						   [LastBill]			        = @LastBillNo,
						   [VatExclude]			        = @VatExclusionCode,
						   [BillsWriteOff]		        = @PurchBillWriteOffAc,
						   [DefaultOfficeAc]	        = @DefaultOfficeAc,
						   [DefaultVat]			        = @DefaultVat,
						   [FeeExclude]			        = @FeeExclusionCode,
						   [DefaultClientDep]	        = @DefaultClientDepositAc,
						   [MiscOutlay]			        = @MiscOutlay,
						   [MiscFE]				        = @DefaultMiscOutlayFee,
						   [PettyCash]			        = @DefaultPettyCash,
						   [WithTax]			        = @WithHoldingTax,
						   [EnableFNL]			        = @EnableFNL,
						   [PeriodEnd]					= (SELECT [dbo].[KAAS_FN_ConvertDateToClarion](@NextPeriodEnd))

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'Options_Conversion'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @ShowConvertedLedgerBtn  
					 WHERE [KeyName]	 = 'Options_Conversion'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'Options_Conversion',
						    @ShowConvertedLedgerBtn
						)


				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'YearEndDate'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  CONVERT(VARCHAR(10), CAST(@YearEndDate AS DATE),103)   
					 WHERE [KeyName]	 = 'YearEndDate'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'YearEndDate',
						    CONVERT(VARCHAR(10), CAST(@YearEndDate AS DATE),103)
						)
			END								        
												        
		IF(@TabName = 'Keyhouse')				        
			BEGIN							        
					UPDATE [dbo].[Control]		        
					   SET [EnableCDB]			        = @EnableClientDB,
						   [UK]					        = @UK,
						   [EnableDW]			        = @EnableDeedWills,
						   [YearEndCompleted]	        = @YearEndCompleted,
						   [EnableFM]			        = @EnableFileManager,
						   [UseOutlayType]		        = @UseOutlayType,
						   [PendingOutlay]		        = @PendingOutlay,
						   [Indicator22]		        = @UseBranches,
						   [RecInstalled]		        = @EnableBankRec,
						   [Indicator18]		        = @BillPrinting,
						   [Indicator19]		        = @UniqueMatterNumber,	
						   [Indicator23]		        = @TaggedBatches,	
						   [NoBar]				        = @OverdrawnClientAc,	
						   [Indicator20]		        = @IntrestCalculator,	
						   [WordPerfect]		        = @WordPerfect,	
						   [Indicator24]		        = @Indicator24,	
						   [Indicator25]		        = @Indicator25,	
						   [Indicator26]		        = @Indicator26,	
						   [Indicator27]		        = @Indicator27,	
						   [Indicator28]		        = @Indicator28,	
						   [Indicator29]		        = @Indicator29,
						   [Indicator30]		        = @Indicator30,	
						   [DemoExpire]			        = @DemoExpire,	
						   [MaxNumberofMatters]	        = @MaxMatter,	
						   [OpSisLink]			        = @CaseMgrLink,	
						   [TimeCosting]		        = @TimeCostingInstalled,	
						   [ForceFE]			        = @ForceFeeEarner,	
						   [LabelPrinter]		        = @LabelPrinter,	
						   [FeesRepSeq]			        = @FeeReporting

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'CompositeBilling'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @CompositeBilling  
					 WHERE [KeyName]	 = 'CompositeBilling'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'CompositeBilling',
						    @CompositeBilling
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'AllowFwPostingJournals'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @AllowFwPostingJournals  
					 WHERE [KeyName]	 = 'AllowFwPostingJournals'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'AllowFwPostingJournals',
						    
							@AllowFwPostingJournals
						)

				--To update AzureBlobStorageClientFolder
				IF(@AzureBlobStorageClientFolder<>'' AND @AzureBlobStorageClientFolder IS NOT NULL)
				BEGIN
						IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'AzureBlobStorageClientFolder'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @AzureBlobStorageClientFolder  
					 WHERE [KeyName]	 = 'AzureBlobStorageClientFolder'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'AzureBlobStorageClientFolder',
						    @AzureBlobStorageClientFolder
						)
				END

				
				--To update AzureBlobStorageClientVersionsFolder

				IF(@AzureBlobStorageClientVersionsFolder<>'' AND @AzureBlobStorageClientVersionsFolder<>NULL)
				BEGIN
						IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'AzureBlobStorageClientVersionsFolder'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @AzureBlobStorageClientVersionsFolder  
					 WHERE [KeyName]	 = 'AzureBlobStorageClientVersionsFolder'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'AzureBlobStorageClientVersionsFolder',
						    @AzureBlobStorageClientVersionsFolder
						)
				END

				
				--To update AzureBlobStorageClientVersionsFolder

				IF(@AzureBlobStorageTemplatesFolder<>'' AND @AzureBlobStorageTemplatesFolder<>NULL)
				BEGIN
					IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'AzureBlobStorageTemplatesFolder'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @AzureBlobStorageTemplatesFolder  
					 WHERE [KeyName]	 = 'AzureBlobStorageTemplatesFolder'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'AzureBlobStorageTemplatesFolder',
						    @AzureBlobStorageTemplatesFolder
						)

				END

				

			END								        
		IF(@TabName = 'More')					        
			BEGIN							        
					UPDATE [dbo].[Control]		        
					   SET [Solicitor]			        = @SolicitorCategory,
						   [OthParty]			        = @OtherPartyCategory,
						   [SupplierCategory]           = @SupplierCategory,
						   [DefaultCategory]            = @SystemCategoryType,
						   [AutoNumber]			        = @AutoNumberClient,	
						   [AutoAlphaClientNumbering]   = @AutoAlphaNumbering,
						   [ThirdPartyLimit]			= @ThirdPartyLimit,
						   [DatePastValidation]			= @DatePastValidation,
						   [DateFutValidation]			= @DateFutureValidation,
						   [EiConvert]					= @ConversionRate,
						   [UserPrompt1]				= @PromptRef1,
						   [UserPrompt2]				= @PromptRef2,
						   [UserPrompt3]				= @PromptRef3,
						   [NextFile]					= @NextFile,
						   [ClosedFileNo]				= @ClosedFileNo,
						   [ChequePrinting]				= @ChequeType,
						   [EnableCP]					= @EnableChequePrinting


				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'TimeBarred'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @CloseMatterTimeBarred  
					 WHERE [KeyName]	 = 'TimeBarred'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'TimeBarred',
						    @CloseMatterTimeBarred
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'SupplierRemittance_On'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @SupplierRemittance  
					 WHERE [KeyName]	 = 'SupplierRemittance_On'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'SupplierRemittance_On',
						    @SupplierRemittance
						)
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'DefaultPrebilledOutlay'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @DefaultPrebilledOutlay
					 WHERE [KeyName]	 = 'DefaultPrebilledOutlay'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'DefaultPrebilledOutlay',
						    @DefaultPrebilledOutlay
						)
						   			
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'MatterOutlayBudgetCheckON'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @MatterOutlayBudgetChkON  
					 WHERE [KeyName]	 = 'MatterOutlayBudgetCheckON'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'MatterOutlayBudgetCheckON',
						    @MatterOutlayBudgetChkON
						) 
						
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'CASE_LabelNo'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @LabelNo  
					 WHERE [KeyName]	 = 'CASE_LabelNo'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'CASE_LabelNo',
						    @LabelNo
						) 					   				
						   					
			END
		
		IF(@TabName = 'EFT Defaults')					        
			BEGIN	
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EFTDefaultON'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @EFTDefaultON  
					 WHERE [KeyName]	 = 'EFTDefaultON'

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EFTEmailToSend'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @EFTEmailToSend  
					 WHERE [KeyName]	 = 'EFTEmailToSend'
					 
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EFTTransactionLimit'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @EFTTransactionLimit  
					 WHERE [KeyName]	 = 'EFTTransactionLimit'				
		
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EFTNoOfTransactionLimit'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @EFTNoOfTransactionLimit  
					 WHERE [KeyName]	 = 'EFTNoOfTransactionLimit'			
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EFTEmailSubject'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @EFTEmailSubject 
					 WHERE [KeyName]	 = 'EFTEmailSubject'

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EFTEmailMessage'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @EFTEmailMessage 
					 WHERE [KeyName]	 = 'EFTEmailMessage'

			 END
		
		
		IF(@TabName = 'NotifyByEmail')
			BEGIN

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'InvoiceApprover'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @InvoiceApproverEmail  
					 WHERE [KeyName]	 = 'InvoiceApprover'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'InvoiceApprover',
						    @InvoiceApproverEmail
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'ChequeApprover'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @ChequeApproverEmail  
					 WHERE [KeyName]	 = 'ChequeApprover'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'ChequeApprover',
						    @ChequeApproverEmail
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'NotifyReleasedInv'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @NotifyReturnInvoice  
					 WHERE [KeyName]	 = 'NotifyReleasedInv'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'NotifyReleasedInv',
						    @NotifyReturnInvoice
						)


				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'NotifyApprovedInv'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @NotifyApprovedInvoice 
					 WHERE [KeyName]	 = 'NotifyApprovedInv'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'NotifyApprovedInv',
						    @NotifyApprovedInvoice
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'NotifyReleasedChq'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @NotifyReturnCheque 
					 WHERE [KeyName]	 = 'NotifyReleasedChq'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'NotifyReleasedChq',
						    @NotifyReturnCheque
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'NotifyApprovedChq'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @NotifyApprovedCheque 
					 WHERE [KeyName]	 = 'NotifyApprovedChq'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'NotifyApprovedChq',
						    @NotifyApprovedCheque
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'EMailServer'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @SMTPMailServer 
					 WHERE [KeyName]	 = 'EMailServer'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'EMailServer',
						    @SMTPMailServer
						)

			END
		IF(@TabName = 'MoneyLaundering')
			BEGIN
				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'Money Laundering_MoneyLaunderingCheck'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @MoneyLaunderingCheck 
					 WHERE [KeyName]	 = 'Money Laundering_MoneyLaunderingCheck'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'Money Laundering_MoneyLaunderingCheck',
						    @MoneyLaunderingCheck
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'Money Laundering_Dept'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @MoneyLaunderingDept 
					 WHERE [KeyName]	 = 'Money Laundering_Dept'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'Money Laundering_Dept',
						    @MoneyLaunderingDept
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'Money Laundering_FeeEarner'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @MoneyLaunderingFE 
					 WHERE [KeyName]	 = 'Money Laundering_FeeEarner'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'Money Laundering_FeeEarner',
						    @MoneyLaunderingFE
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'Money Laundering_WorkType'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @MoneyLaunderingWorkType
					 WHERE [KeyName]	 = 'Money Laundering_WorkType'  
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'Money Laundering_WorkType',
						    @MoneyLaunderingWorkType
						)


			END	
		IF(@TabName = 'CodeConfiguration')					        
			BEGIN							        
					UPDATE [dbo].[Control]		        
					   SET [AUTONUMBER]			        = @AutoNumber,
						   [AUTOALPHACLIENTNUMBERING]	= @AutoAlphaClientNumbering,
						   [INDICATOR19]                = @UniqueMatterCodeNumbering


				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'ClientLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @ClientLabel  
					 WHERE [KeyName]	 = 'ClientLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'ClientLabel',
						    @ClientLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'ContactLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @ContactLabel  
					 WHERE [KeyName]	 = 'ContactLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'ContactLabel',
						    @ContactLabel
						)



				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'MatterLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @MatterLabel  
					 WHERE [KeyName]	 = 'MatterLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'MatterLabel',
						    @MatterLabel
						)
			

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'CaseLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @CaseLabel  
					 WHERE [KeyName]	 = 'CaseLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'CaseLabel',
						    @CaseLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'CaseMatterLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @CaseMatterLabel  
					 WHERE [KeyName]	 = 'CaseMatterLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'CaseMatterLabel',
						    @CaseMatterLabel
						)


				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'FeeEarnerLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @FeeEarnerLabel  
					 WHERE [KeyName]	 = 'FeeEarnerLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'FeeEarnerLabel',
						    @FeeEarnerLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'PartnerLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @PartnerLabel  
					 WHERE [KeyName]	 = 'PartnerLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'PartnerLabel',
						    @PartnerLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'AssociateLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @AssociateLabel 
					 WHERE [KeyName]	 = 'AssociateLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'AssociateLabel',
						    @AssociateLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'BranchLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @BranchLabel 
					 WHERE [KeyName]	 = 'BranchLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'BranchLabel',
						    @BranchLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'PostalCodeLabel'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @PostalCodeLabel 
					 WHERE [KeyName]	 = 'PostalCodeLabel'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'PostalCodeLabel',
						    @PostalCodeLabel
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'AutoNumberIfBlank'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @AutoNumberIfBlank 
					 WHERE [KeyName]	 = 'AutoNumberIfBlank'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'AutoNumberIfBlank',
						    @AutoNumberIfBlank
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'ManualClientCode'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @ManualClientCode 
					 WHERE [KeyName]	 = 'ManualClientCode'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'ManualClientCode',
						    @ManualClientCode
						)

				IF EXISTS
				   (
				    SELECT TOP 1 1 
				      FROM [dbo].[Settings] 
				     WHERE [KeyName]     = 'ShowMatterCode'
				   )  	
					UPDATE [dbo].[Settings]  
					   SET [KeyValue]    =  @ShowMatterCode 
					 WHERE [KeyName]	 = 'ShowMatterCode'
				ELSE  
					INSERT
					  INTO [dbo].[Settings]
					    ( 
						   [KeyName],
						   [KeyValue]
						) 
				    VALUES 
				        (
						   'ShowMatterCode',
						    @ShowMatterCode
						)

			END

     		COMMIT TRAN

	 END TRY
	 BEGIN CATCH
		DECLARE @ErrorMsg      NVARCHAR(4000), 
				@ErrorSeverity INT,
				@ErrorState    INT; 

		 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
				@ErrorSeverity = ERROR_SEVERITY(), 
				@ErrorState    = ERROR_STATE()

	  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 

		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END  
	 END CATCH
	SET NOCOUNT OFF
END

GO



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

GO 

CREATE PROCEDURE 
       [dbo].[KAAS_UpdateSAMUndertakingDetails] (
	   
	     @Type                        VARCHAR(10),
	     @Details                     VARCHAR(MAX),
	     @Who                         VARCHAR(MAX),
	     @GivenOrReceived             VARCHAR(10),
	     @DealingNumber               VARCHAR(10),
	     @Notes                       VARCHAR(MAX),
	     @CommercialOrNonCommerical   VARCHAR(10),
	     @Status                      VARCHAR(50),
	     @Date                        DATETIME,
	     @Value                       DECIMAL,
	     @AuthorizedByFE              VARCHAR(10),
	     @UndertakingTo               VARCHAR(10),
	     @Text1                       VARCHAR(max),
	     @ActionID                    INT,
	     @IsDischarge                 BIT,
	     @DiaryWarningDate            DATETIME,
	     @DischargeDate               DATETIME = null,
	     @Handler                     VARCHAR(10),
		 @AddCommentLedger			  BIT,
	     @Result	                  TINYINT OUTPUT
) 
AS 
  /*******************************************************************************************************
  *                                                                                                      *
  *Used to list the matter ledger                                                                        *
  * Stored Procedure Name: [dbo].[KAAS_UpdateSAMUndertakingDetails]										 * 
  * Modification History:                                                                                *
  * 2021-03-26 Natarajan S        Created																 *    
  * 03 DEC 2021 Vinodhkumar M      Modified - Added add comment Ledger field							 *
  * 08 Mar 2022 Balamurugan.C      Modified - Handled TCL Statements and Formatting                      *      
   *******************************************************************************************************/
BEGIN
  BEGIN TRY
  BEGIN TRANSACTION
                SET @Type                      = SUBSTRING(@Type, 1, 1)
                SET @GivenOrReceived           = SUBSTRING(@GivenOrReceived, 1, 1)
                SET @CommercialOrNonCommerical = SUBSTRING(@CommercialOrNonCommerical, 1, 1)
  	         
             UPDATE [UTG]
  	            SET [UTG].[Type]               = @Type,
  	         	    [UTG].[Description]        = @Details,
  	         	    [UTG].[Who]                = @Who,
  	         	    [UTG].[GivenOrReceived]    = @GivenOrReceived,
  	         	    [UTG].[DealingNumber]      = @DealingNumber,
  	         	    [UTG].[Notes]              = @Notes,
  	         	    [UTG].[CommercialOrNon]    = @CommercialOrNonCommerical,
  	         	    [UTG].[Status]             = @Status,
  	         	    [UTG].[Date]               = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0),
  	         	    [UTG].[UNDDate]            = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0),
  	         	    [UTG].[Value]              = @Value,
  	         	    [UTG].[UNDValue]           = @Value,
  	         	    [UTG].[AuthorisedByFE]     = @AuthorizedByFE,
  	         	    [UTG].[Handler]            = @Handler,
  	         	    [UTG].[UndertakingTo]      = @UndertakingTo,
  	         	    [UTG].[CaseContact]        = @UndertakingTo,
					[UTG].[AddCommentLedger]   = @AddCommentLedger,
  	         	    [UTG].[DischargeDate]      = CASE @IsDischarge WHEN 1 
												 THEN DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@diaryWarningDate, @Handler)), 0) 
  	         							    	 ELSE NULL END
               FROM [dbo].[Undertakings] [UTG]
              WHERE [UTG].[ActionID]           = @ActionID
            
             UPDATE [DIA] 
  	            SET [DIA].[Date]               = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@diaryWarningDate, @Handler)), 0),
  	         	    [DIA].[DueDate]            = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0),
  	         	    [DIA].[Text1]              = @Text1 
               FROM [dbo].[diary] [DIA]
              WHERE [DIA].[ActionId]           = @ActionID
            
             UPDATE [DEL]
  	            SET [DEL].[Date]               = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@diaryWarningDate, @Handler)), 0),
  	         	    [DEL].[DueDate]            = DATEADD(DAY, DATEDIFF(DAY, 0, [dbo].[KAAS_FNConvertDateToUTC](@Date, @Handler)), 0)
               FROM [dbo].[DiaryDelegations] [DEL]	
              WHERE [ActionId]                 = @ActionID
            
  	            SET @Result = 1

  COMMIT TRANSACTION           
	
  END TRY
  BEGIN CATCH
	DECLARE @ErrorMsg      NVARCHAR(4000), 
			@ErrorSeverity INT,
			@ErrorState    INT; 

	 SELECT @ErrorMsg      = ISNULL(ERROR_MESSAGE(),''), 
			@ErrorSeverity = ERROR_SEVERITY(), 
			@ErrorState    = ERROR_STATE()

  RAISERROR(@ErrorMsg, @ErrorSeverity, @ErrorState); 
		 IF @@TRANCOUNT > 0  
			BEGIN
				ROLLBACK TRANSACTION;
			END   
  END CATCH
END
GO



