From a51af83c45b89e6483ff333b94e5f25811bc66ff Mon Sep 17 00:00:00 2001
From: pbarroca <pbarroca@afi-sa.fr>
Date: Mon, 28 Aug 2017 17:25:00 +0200
Subject: [PATCH] dev #51538 : add pickday property on batch

---
 VERSIONS_WIP/51538                            |  1 +
 .../admin/controllers/BatchController.php     |  2 +-
 .../admin/views/scripts/batch/index.phtml     | 18 +-----
 cosmogramme/sql/patch/patch_334.php           |  9 +++
 library/Class/Batch.php                       | 16 +++++
 library/Class/Repeat/WeekDays.php             | 59 +++++++++++++++++++
 .../Controller/Plugin/Manager/Batch.php       | 54 +++++++++++++++++
 .../Plugin/ResourceDefinition/Batch.php       |  4 +-
 library/ZendAfi/Form/Admin/Batch.php          | 25 +++++++-
 library/ZendAfi/Form/Element/WeekDays.php     | 37 ++++++++++++
 .../admin/controllers/BatchControllerTest.php | 46 +++++++++++++++
 tests/db/UpgradeDBTest.php                    | 19 +++++-
 12 files changed, 269 insertions(+), 21 deletions(-)
 create mode 100644 VERSIONS_WIP/51538
 create mode 100644 cosmogramme/sql/patch/patch_334.php
 create mode 100644 library/Class/Repeat/WeekDays.php
 create mode 100644 library/ZendAfi/Controller/Plugin/Manager/Batch.php
 create mode 100644 library/ZendAfi/Form/Element/WeekDays.php

diff --git a/VERSIONS_WIP/51538 b/VERSIONS_WIP/51538
new file mode 100644
index 00000000000..324c170bdfb
--- /dev/null
+++ b/VERSIONS_WIP/51538
@@ -0,0 +1 @@
+ - ticket #51538 : Administration : Ajout de la possibilité de spécifier les jours de lancement des batchs
\ No newline at end of file
diff --git a/application/modules/admin/controllers/BatchController.php b/application/modules/admin/controllers/BatchController.php
index d51f363ebfc..3ba79907d67 100644
--- a/application/modules/admin/controllers/BatchController.php
+++ b/application/modules/admin/controllers/BatchController.php
@@ -23,7 +23,7 @@ class Admin_BatchController extends ZendAfi_Controller_Action {
 
   public function getPlugins() {
     return ['ZendAfi_Controller_Plugin_ResourceDefinition_Batch',
-            'ZendAfi_Controller_Plugin_Manager_Manager'];
+            'ZendAfi_Controller_Plugin_Manager_Batch'];
   }
 
 
diff --git a/application/modules/admin/views/scripts/batch/index.phtml b/application/modules/admin/views/scripts/batch/index.phtml
index 827623b90f9..b9cd06f6f30 100644
--- a/application/modules/admin/views/scripts/batch/index.phtml
+++ b/application/modules/admin/views/scripts/batch/index.phtml
@@ -18,22 +18,8 @@ echo $this->tagModelTable(
   [$this->_('Libelle'), $this->_('Dernière exécution')],
   ['Libelle', 'last_run'],
   [
-    function($batch) use ($id_placeholder, $delete_url) {
-      if(!$batch->isDeletable())
-        return '';
-
-      return $this->tagAnchor(str_replace($id_placeholder, $batch->getId(), $delete_url),
-                              $this->boutonIco('type=del'));
-    },
-
-    function($batch) use ($id_placeholder, $run_url, $run_ajax_url) {
-      if(!$batch->isManuallyRunnable())
-        return '';
-
-      $url = $batch->isAjaxRunnable() ? $run_ajax_url : $run_url;
-
-      return $this->tagAnchor(str_replace($id_placeholder, $batch->getId(), $url),
-                              $this->boutonIco('type=test', 'bulle=Lancer'));
+    function($batch) {
+      return $this->renderPluginsActions($batch);
     }
   ],
   'batchs');
diff --git a/cosmogramme/sql/patch/patch_334.php b/cosmogramme/sql/patch/patch_334.php
new file mode 100644
index 00000000000..ffe797a19ba
--- /dev/null
+++ b/cosmogramme/sql/patch/patch_334.php
@@ -0,0 +1,9 @@
+<?php
+$adapter = Zend_Db_Table_Abstract::getDefaultAdapter();
+
+try {
+  $adapter->query('select pick_day from batchs limit 1');
+} catch (Exception $e) {
+  $adapter->query('ALTER TABLE `batchs` ADD COLUMN `pick_day` VARCHAR(255) NULL DEFAULT NULL;');
+}
+?>
\ No newline at end of file
diff --git a/library/Class/Batch.php b/library/Class/Batch.php
index c8469a79541..088ff14d8bc 100644
--- a/library/Class/Batch.php
+++ b/library/Class/Batch.php
@@ -107,12 +107,20 @@ class Class_BatchLoader extends Storm_Model_Loader {
 }
 
 
+
+
 class Class_Batch extends Storm_Model_Abstract {
   protected $_table_name = 'batchs';
   protected $_loader_class = 'Class_BatchLoader';
   protected $_default_attribute_values = ['type'=> '',
+                                          'pick_day' => '',
                                           'last_run' => ''];
 
+  public function __construct() {
+    parent::__construct();
+    $this->_default_attribute_values['pick_day'] = (new Class_Repeat_WeekDays())->allDaysSerialized();
+  }
+
 
   public function getLibelle() {
     return $this->withBatchDo(function($batch) { return $batch->getLabel(); },
@@ -175,4 +183,12 @@ class Class_Batch extends Storm_Model_Abstract {
                      Class_Batch_AutocompleteRecordAuthor::TYPE,
                      Class_Batch_IndexRessourcesNumeriques::TYPE]);
   }
+
+
+  public function setPickDay($value) {
+    if (is_array($value))
+      $value = (new Class_Repeat_WeekDays())->serialize($value);
+
+    return parent::_set('pick_day', $value);
+  }
 }
diff --git a/library/Class/Repeat/WeekDays.php b/library/Class/Repeat/WeekDays.php
new file mode 100644
index 00000000000..2ff865874af
--- /dev/null
+++ b/library/Class/Repeat/WeekDays.php
@@ -0,0 +1,59 @@
+<?php
+/**
+ * Copyright (c) 2012-2017, 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_Repeat_WeekDays {
+  use Trait_Translator;
+
+  const SEPARATOR = ';';
+
+  protected $_days;
+
+  public function __construct() {
+    $this->_days = ['1' => $this->_('lundi'),
+                    '2' => $this->_('mardi'),
+                    '3' => $this->_('mercredi'),
+                    '4' => $this->_('jeudi'),
+                    '5' => $this->_('vendredi'),
+                    '6' => $this->_('samedi'),
+                    '0' => $this->_('dimanche')];
+  }
+
+
+  public function allDaysSerialized() {
+    return implode(static::SEPARATOR, array_keys($this->_days));
+  }
+
+
+  public function allDays() {
+    return $this->_days;
+  }
+
+
+  public function unserialize($value) {
+    return explode(static::SEPARATOR, $value);
+  }
+
+
+  public function serialize($value) {
+    return implode(static::SEPARATOR, $value);
+  }
+}
\ No newline at end of file
diff --git a/library/ZendAfi/Controller/Plugin/Manager/Batch.php b/library/ZendAfi/Controller/Plugin/Manager/Batch.php
new file mode 100644
index 00000000000..a84cc048e71
--- /dev/null
+++ b/library/ZendAfi/Controller/Plugin/Manager/Batch.php
@@ -0,0 +1,54 @@
+<?php
+/**
+ * Copyright (c) 2012-2017, 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 ZendAfi_Controller_Plugin_Manager_Batch extends ZendAfi_Controller_Plugin_Manager_Manager {
+  public function getActions($model) {
+    return [
+            ['url' => '/admin/batch/edit/id/%s',
+             'icon' => 'edit',
+             'label' => $this->_('Modifier la tâche')],
+
+            ['url' => '/admin/batch/delete/id/%s',
+             'icon' => 'delete',
+             'label' => $this->_('Supprimer la tâche'),
+             'condition' => function($model)
+              {
+                return $model->isDeletable();
+              }],
+
+            ['url' => '/admin/batch/run/id/%s',
+             'icon' => 'test',
+             'label' => $this->_('Lancer'),
+             'condition' => function($model)
+              {
+                return $model->isManuallyRunnable() && (!$model->isAjaxRunnable());
+              }],
+
+            ['url' => '/admin/batch/run-ajax/id/%s',
+             'icon' => 'test',
+             'label' => $this->_('Lancer'),
+             'condition' => function($model)
+              {
+                return $model->isManuallyRunnable() && $model->isAjaxRunnable();
+              }]];
+  }
+}
\ No newline at end of file
diff --git a/library/ZendAfi/Controller/Plugin/ResourceDefinition/Batch.php b/library/ZendAfi/Controller/Plugin/ResourceDefinition/Batch.php
index 319f2646d50..e4e223efe84 100644
--- a/library/ZendAfi/Controller/Plugin/ResourceDefinition/Batch.php
+++ b/library/ZendAfi/Controller/Plugin/ResourceDefinition/Batch.php
@@ -28,10 +28,12 @@ class ZendAfi_Controller_Plugin_ResourceDefinition_Batch extends ZendAfi_Control
                         'order' => 'type',
                         'findAll' => 'findAllWithDefaults'],
 
-            'messages' => ['successful_add' => $this->_('Tâche ajoutée'),
+            'messages' => ['successful_save' => $this->_('Tâche sauvegardée'),
+                           'successful_add' => $this->_('Tâche ajoutée'),
                            'successful_delete' => $this->_('Tâche supprimée')],
 
             'actions' => ['add' => ['title' => $this->_('Nouvelle Tâche')],
+                          'edit' => ['title' => $this->_('Modifier la tâche')],
                           'index' => ['title' => $this->_('Tâches')]],
 
             'after_add' => function() {$this->_redirect('/admin/batch');},
diff --git a/library/ZendAfi/Form/Admin/Batch.php b/library/ZendAfi/Form/Admin/Batch.php
index 8bc12c09edb..afc90577fd0 100644
--- a/library/ZendAfi/Form/Admin/Batch.php
+++ b/library/ZendAfi/Form/Admin/Batch.php
@@ -27,10 +27,31 @@ class ZendAfi_Form_Admin_Batch extends ZendAfi_Form {
     $this
       ->setAttrib('data-disable-onchange', 'true')
 
-      ->addElement('select', 'type',
+      ->addElement('select',
+                   'type',
                    ['multiOptions' => Class_Batch::getAvailableType(),
+                    'label' => $this->_('Type de tâche'),
                     'required' => true])
 
-      ->addDisplayGroup(['type'], 'ajout_tache', []);
+      ->addElement('weekDays',
+                   'pick_day',
+                   ['label' => $this->_('Lancer tous les')])
+
+      ->addUniqDisplayGroup('ajout_tache');
+  }
+
+
+  public function populate($datas) {
+    $current_batch_label = isset($datas['type'])
+      ? Class_Batch::getBatchLibelle($datas['type'])
+      : '';
+
+    if($current_batch_label)
+      $this->getElement('type')
+           ->setMultiOptions(
+                             $this->getElement('type')->getMultiOptions()
+                             + [$datas['type'] => $current_batch_label]);
+
+    return parent::populate($datas);
   }
 }
diff --git a/library/ZendAfi/Form/Element/WeekDays.php b/library/ZendAfi/Form/Element/WeekDays.php
new file mode 100644
index 00000000000..4fbe72d00d7
--- /dev/null
+++ b/library/ZendAfi/Form/Element/WeekDays.php
@@ -0,0 +1,37 @@
+<?php
+/**
+ * Copyright (c) 2012-2017, 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 ZendAfi_Form_Element_WeekDays extends Zend_Form_Element_MultiCheckbox {
+  public function __construct($spec, $options=null) {
+    parent::__construct($spec, $options);
+    $this
+      ->setMultiOptions((new Class_Repeat_WeekDays())->allDays())
+      ->setSeparator(' ');
+  }
+
+
+  public function setValue($value) {
+    return is_string($value)
+      ? parent::setValue((new Class_Repeat_WeekDays())->unserialize($value))
+      : parent::setValue($value);
+  }
+}
diff --git a/tests/application/modules/admin/controllers/BatchControllerTest.php b/tests/application/modules/admin/controllers/BatchControllerTest.php
index bfd78004098..1c7222d1f1e 100644
--- a/tests/application/modules/admin/controllers/BatchControllerTest.php
+++ b/tests/application/modules/admin/controllers/BatchControllerTest.php
@@ -39,6 +39,7 @@ abstract class BatchControllerTestCase extends AbstractControllerTestCase {
     $this->_batch_import = $this->fixture('Class_Batch',
                                           ['id' => 3,
                                            'type' => 'IMPORT_TYPO3',
+                                           'pick_day' => '6;0',
                                            'last_run' => '2012-05-01 10:23:00']);
   }
 }
@@ -89,6 +90,12 @@ class BatchControllerWithBatchInDb extends BatchControllerTestCase {
   public function batchActionShouldRunMyTask() {
     $this->assertXPath('//a[contains(@href, "batch/run")]');
   }
+
+
+  /** @test */
+  public function batchActionsShouldContainsEdit() {
+    $this->assertXPath('//a[contains(@href, "batch/edit/id")]');
+  }
 }
 
 
@@ -376,4 +383,43 @@ class BatchControllerIndexWithCyberlibrisTest extends BatchControllerTestCase {
   public function cyberlibrisShouldNotBeAjaxRunnable() {
     $this->assertNotXpath('//a[contains(@href, "batch/run-ajax/id/1001528")]');
   }
+}
+
+
+
+
+class BatchControllerEditTest extends BatchControllerTestCase {
+  public function setUp() {
+    parent::setUp();
+    $this->dispatch('/admin/batch/edit/id/3', true);
+  }
+
+
+  /** @test */
+  public function batchTypeShouldBeImportTypo3AndDisabled() {
+    $this->assertXPath('//select/option[@value="IMPORT_TYPO3"][@selected]');
+  }
+
+
+  /** @test */
+  public function pickDaySundayShouldBeChecked() {
+    $this->assertXPath('//input[@type="checkbox"][@name="pick_day[]"][@value="0"][@checked]');
+  }
+}
+
+
+
+
+class BatchControllerPostEditTest extends BatchControllerTestCase {
+  public function setUp() {
+    parent::setUp();
+    $this->postDispatch('/admin/batch/edit/id/3', ['type' => 'IMPORT_TYPO3',
+                                                   'pick_day' => ['1', '3', '4']]);
+  }
+
+
+  /** @test */
+  public function contextShouldExpectation() {
+    $this->assertEquals('1;3;4', $this->_batch_import->getPickDay());
+  }
 }
\ No newline at end of file
diff --git a/tests/db/UpgradeDBTest.php b/tests/db/UpgradeDBTest.php
index 501402b0624..ea8805dc620 100644
--- a/tests/db/UpgradeDBTest.php
+++ b/tests/db/UpgradeDBTest.php
@@ -1658,4 +1658,21 @@ class UpgradeDB_333_Test extends UpgradeDBTestCase {
     $album = $this->query('select url_origine from album where id=' . static::$album_id)->fetch();
     $this->assertEquals(['url_origine' => 'https://export.1dtouch.com/oai'], $album);
   }
-}
\ No newline at end of file
+}
+
+
+
+
+class UpgradeDB_334_Test extends UpgradeDBTestCase {
+  public function prepare() {
+    try {
+      $this->query('alter table `batchs` drop `pick_day`');
+    } catch(Exception $e) {}
+  }
+
+
+  /** @test */
+  public function pickDayColumnShouldBeAdded() {
+    $this->assertColumn('batchs', 'pick_day');
+  }
+}
-- 
GitLab