From 063c3789f18fd5a76bc1e528bcd2d739e385efe3 Mon Sep 17 00:00:00 2001
From: Laurent Laffont <llaffont@afi-sa.fr>
Date: Wed, 4 Jan 2017 15:48:59 +0100
Subject: [PATCH] rel #52281 push system report at end of cosmogramme
 integration process

---
 cosmogramme/php/integre_traite_main.php       |   5 +-
 library/Class/AdminVar.php                    |   2 +-
 .../Integration/PhaseEndProcess.php           |  34 ++++++
 .../Integration/PhasePrepareIntegrations.php  |   9 +-
 library/Class/Systeme/Report/Publication.php  |  23 +++-
 library/ZendAfi/View/Helper/Status/Json.php   |   1 -
 .../Integration/PhaseEndProcessTest.php       | 106 ++++++++++++++++++
 .../PhasePrepareIntegrationsTest.php          |   2 +-
 8 files changed, 170 insertions(+), 12 deletions(-)
 create mode 100644 library/Class/Cosmogramme/Integration/PhaseEndProcess.php
 create mode 100644 tests/library/Class/Cosmogramme/Integration/PhaseEndProcessTest.php

diff --git a/cosmogramme/php/integre_traite_main.php b/cosmogramme/php/integre_traite_main.php
index af80b939a9f..d7b182124fa 100644
--- a/cosmogramme/php/integre_traite_main.php
+++ b/cosmogramme/php/integre_traite_main.php
@@ -601,8 +601,11 @@ if ($phase == 21)
 // ----------------------------------------------------------------
 setVariable("clef_traitements", "0");
 setVariable("traitement_phase", "Traitement terminé");
+
+startIntegrationPhase('EndProcess');
+
 $chrono->timeStart = $timeStart;
-$log->ecrire("<h4>Fin des traitements</h4>");
+
 $log->ecrire("Déblocage de la base<br>");
 $log->ecrire("Heure :  " . date("G:i:s") . BR);
 $log->ecrire('Temps de traitement : ' . $chrono->end() . BR);
diff --git a/library/Class/AdminVar.php b/library/Class/AdminVar.php
index 105c7640337..ab235a5d563 100644
--- a/library/Class/AdminVar.php
+++ b/library/Class/AdminVar.php
@@ -169,7 +169,7 @@ class Class_AdminVarLoader extends Storm_Model_Loader {
                     'PACK_MOBILE' => Class_AdminVar_Meta::newOnOff($this->_('Activation des fonctions avancées du téléphone'))->bePrivate(),
                     'CNIL_CONSENT_ENABLE' => Class_AdminVar_Meta::newOnOff('Affiche la demande de consentement avant l\'insertion de cookies ou autres traceurs'),
                     'BUID' => Class_AdminVar_Meta::newRawText($this->_('Identifiant unique (attention: la modification de cette variable impactera les outils de suivi de cette installation)'))->bePrivate(),
-                    'STATUS_REPORT_PUSH_URL' => Class_AdminVar_Meta::newRawText($this->_('URL destinataire du rapport d\'état du système'))->bePrivate()],
+                    'STATUS_REPORT_PUSH_URL' => Class_AdminVar_Meta::newRawText($this->_('URL destinataire du rapport d\'état du système (0 pour désactiver)'), ['value' => 'http://pola.afi-sa.net/smile.php'])->bePrivate()],
 
        'cosmogramme' => [
                          'DATE_LAST_FULL_INTEGRATION_USERS' => Class_AdminVar_Meta::newDefault($this->_('Date du dernier import total des abonnés (modifié par cosmogramme)')),
diff --git a/library/Class/Cosmogramme/Integration/PhaseEndProcess.php b/library/Class/Cosmogramme/Integration/PhaseEndProcess.php
new file mode 100644
index 00000000000..13514aeaa44
--- /dev/null
+++ b/library/Class/Cosmogramme/Integration/PhaseEndProcess.php
@@ -0,0 +1,34 @@
+<?php
+/**
+ * Copyright (c) 2012-2014, Agence Française Informatique (AFI). All rights reserved.
+ *
+ * BOKEH is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
+ * the Free Software Foundation.
+ *
+ * There are special exceptions to the terms and conditions of the AGPL as it
+ * is applied to this software (see README file).
+ *
+ * BOKEH is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
+ *
+ * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * along with BOKEH; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
+ */
+
+
+class Class_Cosmogramme_Integration_PhaseEndProcess extends Class_Cosmogramme_Integration_PhaseAbstract {
+  const MY_ID = 22;
+
+  protected $_label = 'Fin des traitements';
+
+  protected function _init($phase) {}
+
+  protected function _execute() {
+    (new Class_Systeme_Report_Publication())->push($this->_log);
+  }
+}
+?>
\ No newline at end of file
diff --git a/library/Class/Cosmogramme/Integration/PhasePrepareIntegrations.php b/library/Class/Cosmogramme/Integration/PhasePrepareIntegrations.php
index 71abeda87c2..97e59880772 100644
--- a/library/Class/Cosmogramme/Integration/PhasePrepareIntegrations.php
+++ b/library/Class/Cosmogramme/Integration/PhasePrepareIntegrations.php
@@ -27,7 +27,7 @@ class Class_Cosmogramme_Integration_PhasePrepareIntegrations extends Class_Cosmo
   protected
     $_ftp_path,
     $_integration_path,
-    $_label = 'Déplacement des intégrations en file d\'attente';
+    $_label = 'Préparation des intégrations';
 
 
 
@@ -46,11 +46,10 @@ class Class_Cosmogramme_Integration_PhasePrepareIntegrations extends Class_Cosmo
 
 
   public function _execute() {
-    $this->_log->addInfo($this->_('Publication du rapport système'));
-    xdebug_break();
-    (new Class_Systeme_Report_Publication())->push();
+    (new Class_Systeme_Report_Publication())->push($this->_log);
 
-    $this->_log->ecrire('<table class="blank" cellspacing="0" cellpadding="5px">');
+    $this->_log->addInfo($this->_('Déplacement des intégrations en file d\'attente'));
+    $this->_log->ecrire('<br><table class="blank" cellspacing="0" cellpadding="5px">');
 
     foreach (Class_IntMajAuto::findAllBy(['order' => 'rang']) as $majauto)
       $this->_runOne($majauto);
diff --git a/library/Class/Systeme/Report/Publication.php b/library/Class/Systeme/Report/Publication.php
index 25a4162d24e..942f95f6ba4 100644
--- a/library/Class/Systeme/Report/Publication.php
+++ b/library/Class/Systeme/Report/Publication.php
@@ -21,10 +21,27 @@
 
 
 class Class_Systeme_Report_Publication extends Class_WebService_Abstract {
-  public function push() {
+  use Trait_Translator;
+
+  public function push($log) {
+    if (!$url = Class_AdminVar::getValueOrDefault('STATUS_REPORT_PUSH_URL'))
+      return $this;
+
+    if (!(new ZendAfi_Validate_Url())->isValid($url))
+      return $this;
+
+    $log->addInfo($this->_('Publication du rapport système'));
+
     $json = (new ZendAfi_View_Helper_Status_Json())->status_Json();
-    $this->getHttpClient()->postData(Class_AdminVar::get('STATUS_REPORT_PUSH_URL'),
-                                     ['report' => $json]);
+
+    try {
+      $this->getHttpClient()->postData($url,
+                                       ['report' => $json]);
+    } catch (Exception $e) {
+      $log->addError($this->_('Echec de la publication du rapport sur %s (%s)',
+                              $url,
+                              $e->getMessage()));
+    }
   }
 }
 ?>
\ No newline at end of file
diff --git a/library/ZendAfi/View/Helper/Status/Json.php b/library/ZendAfi/View/Helper/Status/Json.php
index 65cd2ba4d45..89cb4ed67bd 100644
--- a/library/ZendAfi/View/Helper/Status/Json.php
+++ b/library/ZendAfi/View/Helper/Status/Json.php
@@ -44,7 +44,6 @@ class ZendAfi_View_Helper_Status_Json extends ZendAfi_View_Helper_Status_Abstrac
 
 
   public function visitDatetime($id, $label, $value) {
-    xdebug_break();
     $this->visitData($id, $label,  date('c', $value));
   }
 
diff --git a/tests/library/Class/Cosmogramme/Integration/PhaseEndProcessTest.php b/tests/library/Class/Cosmogramme/Integration/PhaseEndProcessTest.php
new file mode 100644
index 00000000000..d3d375eb2f9
--- /dev/null
+++ b/tests/library/Class/Cosmogramme/Integration/PhaseEndProcessTest.php
@@ -0,0 +1,106 @@
+<?php
+/**
+ * Copyright (c) 2012-2014, Agence Française Informatique (AFI). All rights reserved.
+ *
+ * BOKEH is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
+ * the Free Software Foundation.
+ *
+ * There are special exceptions to the terms and conditions of the AGPL as it
+ * is applied to this software (see README file).
+ *
+ * BOKEH is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
+ *
+ * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * along with BOKEH; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
+ */
+
+
+class PhaseEndProcessTest extends Class_Cosmogramme_Integration_PhaseTestCase {
+  protected $_http_client;
+
+  protected function _getPreviousPhase() {
+    return (new Class_Cosmogramme_Integration_Phase(21))->beCron();
+  }
+
+
+  public function setUp() {
+    parent::setUp();
+
+    $this->_http_client = $this->mock()
+                               ->whenCalled('postData')
+                               ->answers('');
+
+    Class_Systeme_Report_Publication::setDefaultHttpClient($this->_http_client);
+    $this->fixture('Class_Profil',  ['id' => 1, 'libelle' => 'My Bokeh']);
+  }
+
+
+  public function tearDown() {
+    Class_Systeme_Report_Publication::resetHttpClient();
+    parent::tearDown();
+  }
+
+
+  /** @test */
+  public function reportShouldBePushedToPola() {
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $this->assertEquals('http://pola.afi-sa.net/smile.php',
+                        $this->_http_client->getFirstAttributeForLastCallOn('postData'));
+  }
+
+
+  /** @test */
+  public function logShouldContainsReportPublished() {
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $this->assertLogContains('Publication du rapport système');
+  }
+
+
+  /** @test */
+  public function pushedRequestToPolaShouldIncludeReport() {
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $report = $this->_http_client->getAttributesForLastCallOn('postData')[1]['report'];
+    $this->assertEquals('My Bokeh', json_decode($report, true)['portal']['label']);
+  }
+
+
+  /** @test */
+  public function withNoPushUrlShouldNotPushReport() {
+    Class_AdminVar::set('STATUS_REPORT_PUSH_URL', '0');
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $this->assertFalse($this->_http_client->methodHasBeenCalled('postData'));
+  }
+
+
+  /** @test */
+  public function withInvalidPushUrlShouldNotPushReport() {
+    Class_AdminVar::set('STATUS_REPORT_PUSH_URL', 'no');
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $this->assertFalse($this->_http_client->methodHasBeenCalled('postData'));
+  }
+
+
+  /** @test */
+  public function withInvalidPushUrlLogShouldNotContainsReportPublished() {
+    Class_AdminVar::set('STATUS_REPORT_PUSH_URL', 'no');
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $this->assertNotLogContains('Publication du rapport système');
+  }
+
+
+  /** @test */
+  public function withExceptionShouldNotPushReport() {
+    $this->_http_client
+      ->whenCalled('postData')
+      ->willDo(function() { throw new RunTimeException('no more paper'); });
+
+    $this->_phase = $this->_buildPhase('EndProcess')->run();
+    $this->assertLogContains('Echec de la publication du rapport sur http://pola.afi-sa.net/smile.php (no more paper)');
+  }
+}
+?>
\ No newline at end of file
diff --git a/tests/library/Class/Cosmogramme/Integration/PhasePrepareIntegrationsTest.php b/tests/library/Class/Cosmogramme/Integration/PhasePrepareIntegrationsTest.php
index e3208779072..07d6aa04f33 100644
--- a/tests/library/Class/Cosmogramme/Integration/PhasePrepareIntegrationsTest.php
+++ b/tests/library/Class/Cosmogramme/Integration/PhasePrepareIntegrationsTest.php
@@ -1,4 +1,4 @@
-<?php
+~<?php
 /**
  * Copyright (c) 2012-2014, Agence Française Informatique (AFI). All rights reserved.
  *
-- 
GitLab