USE [HCITools]
GO

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

USE [HCITools]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO




CREATE PROCEDURE [dbo].[AMR_Check] 
                 @in_debug  int = null,
                 @in_CheckType smallint
AS 
/*============================================================================= 

  Explication du traitement realise par la SP
  -------------------------------------------
    Cette SP sert à controler le nombre d'AMR générés et traités par la connectique
 
  Contexte d'utilisation
  ----------------------
    Cette SP est appelée par le job DR92130 - Monitoring AMR
 
  Parametres  
  ----------  
    @in_debug : non utilisé 
    @in_CheckType : 1 = Sauvegarde du nombre d'AMR générés et traités
                    2 = Check si nombre d'AMR important (>= 50 0000)
                    
 
  Creation : 24.05.18 / FLA

  Modification : 
  03.07.19 / SPE - TFS53431 - Optimize MonitoringAMR into HCITools
  08.04.21 / SPE - Add (NOLOCK) in select AMR table
  17.03.22 / FLA : Change DBA mail
  12.02.24 / FLA : Remove ArizonaCASH
=============================================================================*/ 
 
set nocount on;

declare @result_sp int,
        @errno     int,
        @errmsg    varchar(255)
 
/*------------------- Declaration des variables --------------------*/
declare @Message                                      varchar(8000),
        @OutParam                                     varchar(255),
        @DatabaseName                                 varchar(255),
        @ConnecticUser                                varchar(255),
        @LatestReplicatedNonPriorizedMonitorRowId     int,
        @LatestReplicatedNonPriorizedMonitorRowIdCASH int,
        @LatestReplicatedPriorizedMonitorRowId        int,
        @LatestReplicatedPriorizedMonitorRowIdCASH    int,
        @MaxDate                                      DateTime,
        @Threshold                                    int,
        @Table                                        sysname,
        @RowsPrioToDo                                 int,
        @RowsToDo                                     int,
        @Hour                                         tinyint,
        @Minutes                                      tinyint,
        @dateRef                                      Datetime
		        
 
/*------------ Affectation des parametres aux variables ------------*/
SET @message = ''
SET @DatabaseName = 'Arizona'	
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 = 'cvConnecticAMRUser', @out_default_value = @OutParam OUTPUT, @out_param_int_1 = NULL
SET @ConnecticUser = @OutParam 
SET @dateRef = dateadd(minute,-16,GETDATE())

SELECT @LatestReplicatedNonPriorizedMonitorRowId     = ActiveSystemServer.amr.GetLatestReplicatedMonitorRowId(@DatabaseName,0)
SELECT @LatestReplicatedPriorizedMonitorRowId        = ActiveSystemServer.amr.GetLatestReplicatedMonitorRowId(@DatabaseName,1)

/*-------------------------- Traitement ---------------------------*/
BEGIN TRY
   
    IF (@in_CheckType = 1)
    BEGIN
    
      INSERT INTO HCITools.dbo.[MonitoringAMR]
		  SELECT GETDATE(),
            @DatabaseName [Database],
            amt.AMT_table_name [Table],
            SUM(CASE WHEN (amr.AMR_user = @ConnecticUser) and (amr.APS_monitor_row_id > @LatestReplicatedPriorizedMonitorRowId) THEN 1 ELSE 0 END), -- AMR priorisés non traités 
            SUM(CASE WHEN (amr.AMR_user = @ConnecticUser) and (amr.APS_monitor_row_id <= @LatestReplicatedPriorizedMonitorRowId) THEN 1 ELSE 0 END), -- AMR priorisés traités
            SUM(CASE WHEN (ISNULL(amr.AMR_user, '') <> @ConnecticUser) and (amr.APS_monitor_row_id > @LatestReplicatedNonPriorizedMonitorRowId) THEN 1 ELSE 0 END),
            SUM(CASE WHEN (ISNULL(amr.AMR_user, '') <> @ConnecticUser) and (amr.APS_monitor_row_id <= @LatestReplicatedNonPriorizedMonitorRowId) THEN 1 ELSE 0 END)
       FROM Arizona.dbo.APS_monitor_row amr (nolock)
 INNER JOIN Arizona.dbo.APS_monitor_table amt (nolock)
         ON amr.AMR_APS_monitor_table = amt.APS_monitor_table_id
      WHERE amr.AMR_row_GUID IS NOT NULL
      -- Remove non transactional and not committed records.
    AND NOT (amt.AMT_wait_for_commit = 1 AND amr.AMR_user = @ConnecticUser AND amr.AMR_type_of_change <> 6)
        AND amt.AMT_used_by_connectic = 1
        AND AMR_APS_TS >= @dateRef
   GROUP BY amt.AMT_table_name

    END
    ELSE IF (@in_CheckType = 2)
    BEGIN
      
      select @Hour = DATEPART(HOUR,GETDATE())
      select @Minutes = DATEPART(MINUTE,GETDATE())
      
      IF (@Hour in (8,12,16) AND @Minutes < 15)
      BEGIN
            select @MaxDate = MAX(MA_Date) 
              from [dbo].[MonitoringAMR]

            SELECT @Threshold = SUM(MA_RowsPrioToDo+MA_RowsToDo) 
              FROM [dbo].[MonitoringAMR]
              WHERE MA_Date = @MaxDate
       
            IF @Threshold >= 50000 
            BEGIN
               
                SET @message = @message +'AMR to process in pharmacy :'+CHAR(13)+CHAR(10)+CHAR(13)+CHAR(10)
                                        +'Database'+CHAR(9)+CHAR(9)
                                        +'Table'+CHAR(9)+CHAR(9)+CHAR(9)+CHAR(9)
                                        +'Prioritized AMR'+CHAR(9)+CHAR(9)+CHAR(9)
                                        +'Not prioritized AMR'+CHAR(13)+CHAR(10)
               
                   declare c_AMR cursor local forward_only static for
		                SELECT MA_Database,MA_Table,MA_RowsPrioToDo,MA_RowsToDo 
                      FROM [dbo].[MonitoringAMR]
                     WHERE MA_Date = @MaxDate
                       AND (MA_RowsPrioToDo+MA_RowsToDo) > 0
                  ORDER BY MA_Database,MA_Table
                    		
		                  open c_AMR

		       FETCH NEXT FROM c_AMR
		                  into @DatabaseName, @Table, @RowsPrioToDo, @RowsToDo

		                 while @@fetch_status <> -1
		                 begin

			                   SET @message = @message + @DatabaseName +CHAR(9)+CHAR(9)+CHAR(9)
                                                 + @Table +CHAR(9)+CHAR(9)+CHAR(9)+CHAR(9)
                                                 + CAST(@RowsPrioToDo AS VARCHAR(50)) +CHAR(9)+CHAR(9)+CHAR(9)+CHAR(9)
                                                 + CAST(@RowsToDo AS VARCHAR(50))+CHAR(13)+CHAR(10)
                    			
			                  FETCH NEXT FROM c_AMR
		                               into @DatabaseName, @Table, @RowsPrioToDo, @RowsToDo
		                    END
		                    
		                 close c_AMR
		            deallocate c_AMR

            END
            
            IF @message <> ''
            BEGIN
              exec aps_Send_Mail_with_template 
                   @in_param_varchar_2 = 'DBA_operator;',
                   @in_job_type = 3, /* 3 = warning */
                   @in_param_varchar_3 = @Message
            END
      END
    END
	ELSE IF (@in_CheckType = 3)  /* Purge history < 3 Months */
    BEGIN
      DELETE [dbo].[MonitoringAMR]
      WHERE MA_Date < DATEADD(MONTH, -3, GETDATE())
    END

/*---------------------- Traitement des erreurs ----------------------*/ 
END TRY
BEGIN CATCH

    /* Traitement des erreurs (avec RaiseError) */
    EXEC dbo.get_Error_Info @in_RaiseError = 1

END CATCH 

GO
