From c536d1e292aaca31da529bf8875a42082dc004ad Mon Sep 17 00:00:00 2001
From: Laurent Laffont <llaffont@afi-sa.fr>
Date: Tue, 25 Apr 2017 12:20:14 +0200
Subject: [PATCH] hotline #55142 add debug log to digital resources

---
 .../php/integration/integration_phase.php     |  8 ++--
 cosmogramme/php/integre_traite_main.php       | 14 +++---
 library/Class/Album.php                       |  7 ++-
 library/Class/Cata/Log.php                    |  7 +--
 .../Cosmogramme/Integration/PhasePanier.php   |  2 +-
 .../Cosmogramme/Integration/PhasePatrons.php  |  2 +-
 .../BibNumerique/RessourceNumerique.php       | 34 +++++++++++++-
 tests/fixtures/onedtouch_oai.xml              |  7 +++
 tests/library/Class/Batch/DilicomTest.php     | 30 ++++++++++++-
 tests/library/Class/Cata/LogTest.php          |  9 +++-
 .../Class/WebService/OneDTouchTest.php        | 45 +++++++++++++++++--
 11 files changed, 134 insertions(+), 31 deletions(-)

diff --git a/cosmogramme/php/integration/integration_phase.php b/cosmogramme/php/integration/integration_phase.php
index 643288124c7..3b45b89bb04 100644
--- a/cosmogramme/php/integration/integration_phase.php
+++ b/cosmogramme/php/integration/integration_phase.php
@@ -29,14 +29,14 @@ function startIntegrationPhase($name) {
     $mode_cron,
     $reprise,
     $log,
-    $log_warning,
-    $log_error,
+    $log_debug,
     $compteur;
 
   $logs = (new Class_Cata_Log())
     ->addDefaultTarget($log)
-    ->addTarget('error', $log_error)
-    ->addTarget('warning', $log_warning);
+    ->addTarget('debug', $log_error);
+
+  Class_WebService_BibNumerique_RessourceNumerique::setLogger($logs);
 
 	$integration_class_name = 'Class_Cosmogramme_Integration_Phase'.ucfirst($name);
 
diff --git a/cosmogramme/php/integre_traite_main.php b/cosmogramme/php/integre_traite_main.php
index 5394cca21d1..ebc159141b5 100644
--- a/cosmogramme/php/integre_traite_main.php
+++ b/cosmogramme/php/integre_traite_main.php
@@ -49,8 +49,7 @@ require_once 'integration/integration_phase.php';
 
 // Instanciations
 $log = new Class_log('integration');
-$log_erreur = new Class_log('erreur', false);
-$log_warning = new Class_log('warning', false);
+$log_debug = new Class_log('debug', false);
 $chrono = new chronometre();
 $chrono_fichier = new chronometre();
 $chrono100notices = new chronometre();
@@ -82,8 +81,7 @@ $should_skip_records = false;
 // ----------------------------------------------------------------
 if ($_REQUEST['reprise'] == 'oui') {
 	$log->open(true);
-	$log_erreur->open(true);
-	$log_warning->open(true);
+	$log_debug->open(true);
 	restaureContext();
 	$reprise = true;
 
@@ -93,8 +91,7 @@ if ($_REQUEST['reprise'] == 'oui') {
 	setVariable('traitement_warnings', 0);
 	setVariable('traitement_phase', 'Déplacement des fichiers');
 	$log->open(false);
-	$log_erreur->open(false);
-	$log_warning->open(false);
+	$log_debug->open(false);
 	$log->log('<h4>Début du traitement</h4>');
 	$log->log('Date : ' . date('d-m-Y') . BR);
 	$log->log('Heure : ' . date('G:i:s') . BR);
@@ -626,8 +623,7 @@ for ($i = 1; $i < count($lib); $i++)
 $log->log('</table>');
 
 $log->close();
-$log_erreur->close();
-$log_warning->close();
+$log_debug->close();
 print(BR . BR . '</body></html>');
 
 
@@ -636,7 +632,7 @@ print(BR . BR . '</body></html>');
 // ----------------------------------------------------------------
 function traceTraitementNotice()
 {
-	global $log, $log_erreur, $log_warning;
+	global $log, $log_debug;
 	global $notice, $compteur, $phase_data, $nb_notices, $chrono100notices, $debug_level;
 	global $nom_bib, $libelle_type_operation, $ret;
 
diff --git a/library/Class/Album.php b/library/Class/Album.php
index da1bcef2ece..0c66bb9263a 100644
--- a/library/Class/Album.php
+++ b/library/Class/Album.php
@@ -1123,11 +1123,14 @@ class Class_Album extends Storm_Model_Abstract {
     $this->check((0==(int)$this->getAnnee())
                  || (($this->getAnnee() >= self::ANNEE_MIN)
                      and ($this->getAnnee() <= $next_year)),
-                 sprintf("L'année doit être comprise entre %s et %s",
+                 sprintf($this->_("L'année doit être comprise entre %s et %s"),
                          self::ANNEE_MIN,
                          $next_year));
 
-    $this->check($this->hasTypeDocId(), 'L\'album doit avoir un type de document');
+    $this->check($this->hasTitre(),
+                 $this->_('Le titre est obligatoire'));
+    $this->check($this->hasTypeDocId(),
+                 $this->_('L\'album doit avoir un type de document'));
   }
 
 
diff --git a/library/Class/Cata/Log.php b/library/Class/Cata/Log.php
index 4fa5ab855c4..84a19f16d6b 100644
--- a/library/Class/Cata/Log.php
+++ b/library/Class/Cata/Log.php
@@ -77,11 +77,8 @@ class Class_Cata_Log {
     if (!is_array($targets))
       $targets = [$targets];
 
-    $loggers =  array_intersect_key($this->_targets,
-                                    array_combine($targets, $targets));
-    return $loggers
-      ? $loggers
-      : [$this->_targets[static::DEFAULT_TARGET]];
+    return array_intersect_key($this->_targets,
+                               array_combine($targets, $targets));
   }
 }
 ?>
\ No newline at end of file
diff --git a/library/Class/Cosmogramme/Integration/PhasePanier.php b/library/Class/Cosmogramme/Integration/PhasePanier.php
index f0fa6567d8f..48a62a06989 100644
--- a/library/Class/Cosmogramme/Integration/PhasePanier.php
+++ b/library/Class/Cosmogramme/Integration/PhasePanier.php
@@ -41,7 +41,7 @@ class Class_Cosmogramme_Integration_PhasePanier extends Class_Cosmogramme_Integr
         && false === array_search('MAIL', $fields))
       $errors[] = 'Configuration: colonne IDABON ou MAIL requise';
 
-    array_map([$this->_log, 'addError'], $errors);
+    array_map([$this->_log, 'error'], $errors);
 
     return empty($errors);
   }
diff --git a/library/Class/Cosmogramme/Integration/PhasePatrons.php b/library/Class/Cosmogramme/Integration/PhasePatrons.php
index 53bf88d6e7a..3da2a30e1bd 100644
--- a/library/Class/Cosmogramme/Integration/PhasePatrons.php
+++ b/library/Class/Cosmogramme/Integration/PhasePatrons.php
@@ -121,7 +121,7 @@ class Class_Cosmogramme_Integration_PhasePatrons extends Class_Cosmogramme_Integ
                                      ['IDABON']
                            ));
 
-    array_map([$this->_log, 'addError'], $errors);
+    array_map([$this->_log, 'error'], $errors);
 
     return empty($errors);
   }
diff --git a/library/Class/WebService/BibNumerique/RessourceNumerique.php b/library/Class/WebService/BibNumerique/RessourceNumerique.php
index fdffff34f6a..a85f5c82bcc 100644
--- a/library/Class/WebService/BibNumerique/RessourceNumerique.php
+++ b/library/Class/WebService/BibNumerique/RessourceNumerique.php
@@ -21,6 +21,7 @@
 
 
 class Class_WebService_BibNumerique_RessourceNumerique {
+  protected static $_logger;
 
   protected
     $_id,
@@ -43,6 +44,24 @@ class Class_WebService_BibNumerique_RessourceNumerique {
     $_authors = [];
 
 
+  static public function getLogger() {
+    if (!static::$_logger)
+      static::$_logger = new Class_Cata_Log();
+    return static::$_logger;
+  }
+
+
+  static public function setLogger($logger) {
+    static::$_logger = $logger;
+  }
+
+
+  protected function _debug($message) {
+    $this->getLogger()->log('[' . get_class($this) . '] ' . $message,
+                            'debug');
+  }
+
+
   public function setId($id) {
     $this->_id = $id;
     return $this;
@@ -246,6 +265,7 @@ class Class_WebService_BibNumerique_RessourceNumerique {
 
 
   public function import() {
+    $this->_debug('import "' . $this->getTitle() . '" (' . $this->getId() . ')');
     if ($album = $this->findAlbumInDB())
       return $this->updateAlbum($album);
 
@@ -256,6 +276,11 @@ class Class_WebService_BibNumerique_RessourceNumerique {
   protected function updateAlbum($album) {
     $album->setRessources($this->getRessources());
     $album->save();
+
+    $this->_debug('update album id:' . $album->getId());
+    if ($album->hasErrors())
+      $this->_debug('errors: ' . implode(',', $album->getErrors()));
+
     Class_Album::clearCache();
     Class_AlbumRessource::clearCache();
     return $album;
@@ -263,6 +288,8 @@ class Class_WebService_BibNumerique_RessourceNumerique {
 
 
   protected function createAlbum($album) {
+    $this->_debug('create new album');
+
     $categorie = $this->getOrCreateRessourceCategorie();
 
     $album
@@ -286,8 +313,13 @@ class Class_WebService_BibNumerique_RessourceNumerique {
     $this->fillAlbumTypeDoc($album);
     $this->updateRessourceNumeriqueNotes($album);
 
-    if ($album->save())
+    if ($album->save()) {
+      $this->_debug('new album id: ' . $album->getId());
       Class_WebService_BibNumerique_Vignette::getInstance()->updateAlbum($album);
+    }
+
+    if ($album->hasErrors())
+      $this->_debug('errors: ' . implode(',', $album->getErrors()));
 
     Class_Album::clearCache();
     Class_AlbumRessource::clearCache();
diff --git a/tests/fixtures/onedtouch_oai.xml b/tests/fixtures/onedtouch_oai.xml
index 3dd5b5b1d65..a8cf7077a92 100644
--- a/tests/fixtures/onedtouch_oai.xml
+++ b/tests/fixtures/onedtouch_oai.xml
@@ -5,6 +5,13 @@
   <request metadataPrefix="oai1dtouch_dc" verb="ListRecords">http://dev.1dtouch.com/oai
   </request>
   <ListRecords>
+    <record>
+      <header status="deleted">
+	<identifier>oai:oai1dtouch.com/album2</identifier>
+	<datestamp>2017-02-22T12:46:19Z</datestamp>
+	<setSpec>music</setSpec>
+      </header>
+    </record>
     <record>
       <header>
 	<identifier>oai:oai1dtouch.com:124
diff --git a/tests/library/Class/Batch/DilicomTest.php b/tests/library/Class/Batch/DilicomTest.php
index d597396837c..d9b4e1d6cc4 100644
--- a/tests/library/Class/Batch/DilicomTest.php
+++ b/tests/library/Class/Batch/DilicomTest.php
@@ -24,7 +24,8 @@ require_once 'tests/fixtures/DilicomFixtures.php';
 abstract class Class_Batch_DilicomTestCase extends ModelTestCase {
   protected
     $_storm_default_to_volatile = true,
-    $_log = '';
+    $_log = '',
+    $_debug_log = '';
 
   public function setUp() {
     parent::setUp();
@@ -35,7 +36,11 @@ abstract class Class_Batch_DilicomTestCase extends ModelTestCase {
     return $this->logger = $this->mock()
                                 ->whenCalled('log')
                                 ->willDo(
-                                         function($message) {
+                                         function($message, $target = '') {
+                                           if ($target == 'debug') {
+                                             $this->_debug_log .= $message . "\n";
+                                             return;
+                                           }
                                            $this->_log .= $message;
                                          });
   }
@@ -138,6 +143,8 @@ abstract class Class_Batch_DilicomJobOnixTestCase extends Class_Batch_DilicomTes
 
     Class_Batch_DilicomJobOnix::setFileSystem($file_system);
 
+    Class_WebService_BibNumerique_RessourceNumerique::setLogger($this->getLogger());
+
     (new Class_Batch_DilicomJobOnix(new Class_Batch_Dilicom))
       ->setFtpClient($this->getFtpClient())
       ->setLogger($this->getLogger())
@@ -145,6 +152,12 @@ abstract class Class_Batch_DilicomJobOnixTestCase extends Class_Batch_DilicomTes
   }
 
 
+  public function tearDown() {
+    Class_WebService_BibNumerique_RessourceNumerique::setLogger(null);
+    parent::tearDown();
+  }
+
+
   protected function _prepareFixtures() { }
 
 
@@ -297,6 +310,19 @@ class Class_Batch_DilicomJobOnixWithFullTest extends Class_Batch_DilicomJobOnixT
     $this->assertEquals('diffusion_pnb_3056309900005_20150728T050431Z.xml',
                         (new Class_Batch_Dilicom)->getModel()->getData());
   }
+
+
+  /** @test */
+  public function debugLogShouldContainsImportLaReineDesNeiges() {
+    $this->assertContains('Class_WebService_BibNumerique_Dilicom_Book] import "La Reine des Neiges" (Dilicom-9782290123409)',
+                          $this->_debug_log);
+
+    $this->assertContains('create new album',
+                          $this->_debug_log);
+
+    $this->assertContains('new album id: 1',
+                          $this->_debug_log);
+  }
 }
 
 
diff --git a/tests/library/Class/Cata/LogTest.php b/tests/library/Class/Cata/LogTest.php
index de89a277b0f..ce7150ed0d1 100644
--- a/tests/library/Class/Cata/LogTest.php
+++ b/tests/library/Class/Cata/LogTest.php
@@ -68,8 +68,7 @@ class Class_Cata_LogTest extends ModelTestCase {
                     '250g Sugar',
                     '250g Butter',
                     'Not enough Butter',
-                    'Go buy butter',
-                    'Then eat']],
+                    'Go buy butter']],
 
        ['error', ['Trying 2.0 version',
                   '1.0 was buggy',
@@ -91,5 +90,11 @@ class Class_Cata_LogTest extends ModelTestCase {
   public function targetShouldContainLines($target, $lines) {
     $this->assertEquals($this->_logs[$target], $lines);
   }
+
+
+  /** @test */
+  public function catalogWithoutDefaultTargeShouldBeSilent() {
+    (new Class_Cata_Log())->log('no exception please');
+  }
 }
 ?>
\ No newline at end of file
diff --git a/tests/library/Class/WebService/OneDTouchTest.php b/tests/library/Class/WebService/OneDTouchTest.php
index 1846ddbdae9..ca0f4fe945a 100644
--- a/tests/library/Class/WebService/OneDTouchTest.php
+++ b/tests/library/Class/WebService/OneDTouchTest.php
@@ -20,7 +20,7 @@
  */
 include_once('tests/fixtures/RessourcesNumeriquesFixtures.php');
 
-class OneDTouchTest extends ModelTestCase {
+class OneDTouchFullTest extends ModelTestCase {
   protected $_storm_default_to_volatile = true;
 
   public function setUp() {
@@ -144,11 +144,29 @@ class OneDTouchTest extends ModelTestCase {
 
 
 class OneDTouchIncTest extends ModelTestCase {
-  protected $_storm_default_to_volatile = true;
+  protected
+    $_storm_default_to_volatile = true,
+    $_debug_log = '';
+
+
+  protected function _setupLogger() {
+    $logger = $this->mock()
+                   ->whenCalled('log')
+                   ->willDo(
+                            function($message, $target = '') {
+                              if ($target != 'debug')
+                                return;
+                              $this->_debug_log .= $message . "\n";
+                            });
+    Class_WebService_BibNumerique_RessourceNumerique::setLogger($logger);
+  }
+
 
   public function setUp() {
     parent::setUp();
 
+    $this->_setupLogger();
+
     RessourcesNumeriquesFixtures::activate1Dtouch();
     $catalogue_xml = file_get_contents(realpath(dirname(__FILE__)). '/../../../fixtures/onedtouch_oai.xml');
 
@@ -198,6 +216,12 @@ class OneDTouchIncTest extends ModelTestCase {
   }
 
 
+  public function tearDown() {
+    Class_WebService_BibNumerique_RessourceNumerique::setLogger(null);
+    parent::tearDown();
+  }
+
+
   /** @test */
   public function shouldHave4Albums() {
     $this->assertEquals(4, count(Class_Album::findAll()));
@@ -212,8 +236,21 @@ class OneDTouchIncTest extends ModelTestCase {
 
 
   /** @test */
-  public function albumShouldHaveBeenUpdated() {
-    $this->assertEquals(1, Class_Album::findFirstBy(['titre' => 'WOLFEP026'])->getId());
+  public function album1DTouchRessourcesShouldHaveBeenUpdated() {
+    $this->assertCount(4,
+                       Class_Album::findFirstBy(['titre' => '1Dtouch res'])->getRessources());
+  }
+
+
+  /** @test */
+  public function debugLogShouldContainsUpdateAlbumOne() {
+    $this->assertContains('update album id:1', $this->_debug_log);
+  }
+
+
+  /** @test */
+  public function debugLogShouldContainsTitleMandatory() {
+    $this->assertContains('errors: Le titre est obligatoire', $this->_debug_log);
   }
 }
 
-- 
GitLab