USE [HCITools];
GO
IF EXISTS (   SELECT *
                FROM sys.objects
               WHERE object_id                                 = OBJECT_ID(N'[dbo].[mon_Change_Tracking]')
                 AND OBJECTPROPERTY(object_id, N'IsProcedure') = 1)
    DROP PROCEDURE [dbo].[mon_Change_Tracking];
GO

CREATE PROCEDURE [mon_Change_Tracking]
    @in_threshold INT = 50000,
    @in_debug INT = NULL
AS
/*===========================================================================================

	Description
	-----------
	This procedure is called by job DR92290 - Monitoring Change Tracking

	Parameters
	----------
	@in_threshold limit tolerate, over this limit a mail is sent to DBA
	@in_debug display result per table and more infos
	
	Creation : 12.04.2023 / RTC
	
	Modifications
	-------------


================================================================================================*/

BEGIN
    DECLARE @cvCurrentOrganizationalUnit INT,
            @subsidiary_id               INT,
            @DWHVersion                  BIGINT,
            @sqlstmt                     NVARCHAR(MAX),
            @tableName                   NVARCHAR(128),
            @out_default_value           VARCHAR(60),
            @format                      VARCHAR(4),
            @schema                      VARCHAR(4),
            @ou                          VARCHAR(3),
            @total                       INT,
            @message                     VARCHAR(MAX);

    /* Initialize variables */
    SELECT @sqlstmt = N'',
           @cvCurrentOrganizationalUnit = NULL,
           @subsidiary_id = NULL,
           @total = 0;

    /* Temp table with amount of records */
    DECLARE @tableResult TABLE (ChangesCount INT NULL,
                                [Schema] VARCHAR(10) NULL,
                                TableName VARCHAR(800) NULL);

    /* Get the cvCurrentOrganizationalUnit */
    EXEC Arizona.dbo.sp_bmc_Bmc_Applic_Default @in_job_type = 3,
                                               @in_param_int_1 = NULL,
                                               @in_param_int_2 = NULL,
                                               @in_param_varchar_1 = 'cvCurrentOrganizationalUnit',
                                               @out_default_value = @out_default_value OUTPUT,
                                               @out_param_int_1 = NULL;

    SELECT @cvCurrentOrganizationalUnit = CONVERT(INT, @out_default_value);

    /* Check if we have a value, if not leave this SP */
    IF @cvCurrentOrganizationalUnit IS NULL
    BEGIN
        RAISERROR('(APS) Error cvCurrentOrganizationalUnit does not exist!', 13, 13);
    END;

    /* Get the subsidiary id and OU code */
    SELECT @subsidiary_id = ou.OU_subsidiary,
           @ou = ou.OU_code
      FROM Arizona.dbo.Organizational_unit ou
     WHERE ou.Organizational_unit_ID = @cvCurrentOrganizationalUnit;

    /* Check if we have a value, if not leave this SP */
    IF @subsidiary_id IS NULL
    BEGIN
        RAISERROR('(APS) Error subsidiary_id does not exist!', 13, 13);
    END;

    /* Get the current format */
    SELECT @format = sub.SUB_code
      FROM Arizona.dbo.Subsidiary sub
     WHERE sub.Subsidiary_ID = @subsidiary_id;

    /* Check if we have a value, if not leave this SP */
    IF @format IS NULL
    BEGIN
        RAISERROR('(APS) Error format does not exist!', 13, 13);
    END;

    /* Change the value into a compatible format */
    IF @format = 'COOP'
    BEGIN
        SET @format = 'CVI';
    END;

    IF @format = 'CENT'
    BEGIN
        SET @format = 'SUN';
    END;

    IF @format = '000'
    BEGIN
        SET @format = 'AAI';
    END;

    SELECT @DWHVersion = DBACTD.DBACTD_DWH_version
      FROM ARIZONACASH.Arizona.dbo.DBA_change_tracking_DWH DBACTD
     WHERE DBACTD.DBACTD_format              = @format
       AND DBACTD.DBACTD_organizational_unit = @ou
       AND DBACTD.DBACTD_update_date         > GETDATE() - 3; /* Get only last 3 days */

    /* Display Ou infos */
    IF @in_debug > 0
        SELECT @ou [OU],
               @format [Format],
               @DWHVersion [DWH_CT_Version];

    DECLARE c_ct_table CURSOR READ_ONLY LOCAL FORWARD_ONLY STATIC FOR
    SELECT st.name
      FROM Arizona.sys.change_tracking_tables ct
      JOIN Arizona.sys.tables st
        ON ct.object_id = st.object_id;
    OPEN c_ct_table;
    FETCH NEXT FROM c_ct_table
     INTO @tableName;
    WHILE @@fetch_status = 0
    BEGIN

        SELECT @schema = sh.[name]
          FROM Arizona.sys.tables st
          JOIN Arizona.sys.schemas sh
            ON st.schema_id = sh.schema_id
         WHERE st.[name] = @tableName;

        SET @sqlstmt
            = N'SELECT count(*),''' + @schema + N''',''' + @tableName + N'''  FROM CHANGETABLE(CHANGES Arizona.'
              + @schema + N'.' + @tableName + N', ' + CONVERT(VARCHAR(MAX), ISNULL(@DWHVersion, 0)) + N') AS CT';
        INSERT INTO @tableResult
        EXEC (@sqlstmt);

        FETCH NEXT FROM c_ct_table
         INTO @tableName;
    END;
    CLOSE c_ct_table;
    DEALLOCATE c_ct_table;

    /* Display count details per table*/
    IF @in_debug > 0
        SELECT ChangesCount,
               [Schema],
               TableName
          FROM @tableResult;

    SELECT @total = SUM(ChangesCount)
      FROM @tableResult;

    /* The datamart truggles when there is more than 35000 lies for document line */
    IF (@total >= @in_threshold)
    OR EXISTS (   SELECT 1
                    FROM @tableResult
                   WHERE TableName    = 'Document_line'
                     AND ChangesCount >= 35000)
    BEGIN
        SELECT @message = 'Total: ' + CONVERT(CHAR(9), @total) + CHAR(13) + CHAR(13);
        SELECT @message = @message + '[Table Name]		[Schema]		[Changes Count]' + CHAR(13);
        SELECT @message
            = @message + TableName + '		' + CONVERT(CHAR(9), ISNULL([Schema], ''))
              + CONVERT(CHAR(9), ISNULL(ChangesCount, '')) + CHAR(13)
          FROM @tableResult
         WHERE ChangesCount > 1
         ORDER BY ChangesCount DESC;

        EXEC dbo.aps_Send_Mail_with_template @in_param_varchar_2 = 'DBA_operator',
                                             @in_param_varchar_3 = @message,
                                             @in_job_type = 3; /* 0:sans template; 1/NULL:echec; 2:succes; 3:warning; 4:message*/
    END;
END;