From f0ed226492d8fb73efa924809bc2bc2efe5139a3 Mon Sep 17 00:00:00 2001
From: lecluse <lecluse@d57fa8bc-6af1-4de9-8b7d-78e900e231e7>
Date: Fri, 20 Mar 2015 15:54:45 +0000
Subject: [PATCH] =?UTF-8?q?Gestion=20affin=C3=A9e=20des=20historiques=20(e?=
 =?UTF-8?q?n=20cours)=20Refactoring=20massif=20(n=C3=A9toyage=20d'ancienne?=
 =?UTF-8?q?s=20portions=20de=20code=20mort)=20Optimisation=20du=20chargeme?=
 =?UTF-8?q?nt=20des=20privil=C3=A8ges?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 data/Sql/Mise en paiement.sql                 |   3 +-
 data/Sql/Services.sql                         |  44 +++++++
 module/Application/Module.php                 |   4 -
 module/Application/config/demo.config.php     |  81 ------------
 module/Application/config/module.config.php   |   1 -
 .../Application/Controller/DemoController.php | 115 ------------------
 .../Controller/EtablissementController.php    |   5 +
 .../Controller/IntervenantController.php      |  73 +----------
 .../ModificationServiceDuController.php       |  88 ++------------
 .../Controller/OffreFormationController.php   |  31 ++++-
 .../Controller/PaiementController.php         |  13 +-
 .../Application/Controller/Plugin/Context.php |  34 ++----
 .../src/Application/Controller/Plugin/Em.php  |  33 +----
 .../Controller/Plugin/Intervenant.php         |  28 -----
 .../Controller/Plugin/IntervenantFactory.php  |  28 -----
 .../Controller/Plugin/ServiceReferentiel.php  |  28 -----
 .../Plugin/ServiceReferentielFactory.php      |  28 -----
 .../Controller/RechercheController.php        |   5 +
 .../Controller/ServiceController.php          |  15 +--
 .../ServiceReferentielController.php          |  10 +-
 .../Controller/StructureController.php        |   4 +-
 .../Controller/VolumeHoraireController.php    |  13 ++
 .../VolumeHoraireReferentielController.php    |  12 ++
 .../Provider/Role/RoleProvider.php            |  69 +++++++----
 .../Provider/Role/RoleProviderFactory.php     |   1 +
 .../Application/Service/ContextProvider.php   |   7 +-
 .../Application/Service/MotifNonPaiement.php  |   2 +-
 .../src/Application/Service/Service.php       |   7 ++
 .../src/Application/Service/ServiceAPayer.php |   1 -
 .../view/application/demo/index.phtml         |   6 -
 .../view/application/demo/intervenant.phtml   |  39 ------
 .../application/intervenant/importer.phtml    |   7 --
 .../application/intervenant/modifier.phtml    |  29 -----
 .../Event/Listeners/HistoriqueListener.php    |  42 +------
 .../Common/ORM/Filter/HistoriqueFilter.php    |  83 ++++++++++---
 35 files changed, 289 insertions(+), 700 deletions(-)
 create mode 100644 data/Sql/Services.sql
 delete mode 100644 module/Application/config/demo.config.php
 delete mode 100755 module/Application/src/Application/Controller/DemoController.php
 delete mode 100644 module/Application/src/Application/Controller/Plugin/Intervenant.php
 delete mode 100644 module/Application/src/Application/Controller/Plugin/IntervenantFactory.php
 delete mode 100644 module/Application/src/Application/Controller/Plugin/ServiceReferentiel.php
 delete mode 100644 module/Application/src/Application/Controller/Plugin/ServiceReferentielFactory.php
 delete mode 100755 module/Application/view/application/demo/index.phtml
 delete mode 100644 module/Application/view/application/demo/intervenant.phtml
 delete mode 100644 module/Application/view/application/intervenant/importer.phtml
 delete mode 100644 module/Application/view/application/intervenant/modifier.phtml

diff --git a/data/Sql/Mise en paiement.sql b/data/Sql/Mise en paiement.sql
index 20f15e177f..53865ac7c2 100644
--- a/data/Sql/Mise en paiement.sql	
+++ b/data/Sql/Mise en paiement.sql	
@@ -19,8 +19,7 @@ FROM
   LEFT JOIN service s ON s.id = frs.service_id
   LEFT JOIN element_pedagogique ep ON ep.id = s.element_pedagogique_id
 WHERE
-  mep.histo_destruction IS NULL
-  AND i.nom_usuel = 'Chaillot'
+  mep.histo_destruction IS NOT NULL
 ;
 
 
diff --git a/data/Sql/Services.sql b/data/Sql/Services.sql
new file mode 100644
index 0000000000..13793ce431
--- /dev/null
+++ b/data/Sql/Services.sql
@@ -0,0 +1,44 @@
+SELECT
+  s.id,
+  i.id,
+  s.structure_aff_id,
+  i.structure_id,
+  s.structure_ens_id,
+  ep.structure_id
+FROM
+  service s
+  JOIN intervenant i ON i.id = s.intervenant_id
+  JOIN element_pedagogique ep ON ep.id = s.element_pedagogique_id
+WHERE
+  s.structure_aff_id <> i.structure_id
+  OR s.structure_ens_id <> ep.structure_id;
+  
+  
+UPDATE service SET
+  structure_aff_id = (SELECT structure_id FROM intervenant WHERE intervenant.id = service.intervenant_id),
+  structure_ens_id = (SELECT structure_id FROM element_pedagogique ep WHERE ep.id = service.element_pedagogique_id)
+WHERE
+  service.id IN (
+SELECT
+  s.id
+FROM
+  service s
+  JOIN intervenant i ON i.id = s.intervenant_id
+  JOIN element_pedagogique ep ON ep.id = s.element_pedagogique_id
+WHERE
+  s.structure_aff_id <> i.structure_id
+  OR s.structure_ens_id <> ep.structure_id );
+  
+/
+
+alter trigger "OSE"."SERVICE_HISTO_CK" disable;
+alter trigger "OSE"."SERVICE_CK" disable;
+
+/
+
+alter trigger "OSE"."SERVICE_HISTO_CK" enable;
+alter trigger "OSE"."SERVICE_CK" enable;
+
+/
+
+select * from intervenant where nom_usuel like '%Martin%';
\ No newline at end of file
diff --git a/module/Application/Module.php b/module/Application/Module.php
index bfea86cbbf..66b129b150 100755
--- a/module/Application/Module.php
+++ b/module/Application/Module.php
@@ -162,10 +162,6 @@ class Module implements ControllerPluginProviderInterface, ViewHelperProviderInt
                 'em'      => 'Application\Controller\Plugin\Em',
                 'context' => 'Application\Controller\Plugin\Context',
             ),
-            'factories' => array(
-                'intervenant'        => 'Application\Controller\Plugin\IntervenantFactory',
-                'serviceReferentiel' => 'Application\Controller\Plugin\ServiceReferentielFactory',
-            ),
         );
     }
 
diff --git a/module/Application/config/demo.config.php b/module/Application/config/demo.config.php
deleted file mode 100644
index 492bc74ed7..0000000000
--- a/module/Application/config/demo.config.php
+++ /dev/null
@@ -1,81 +0,0 @@
-<?php
-
-namespace Application;
-
-return array(
-    'router' => array(
-        'routes' => array(
-            'demo' => array(
-                'type'    => 'Segment',
-                'options' => array(
-                    'route'    => '/demo[/:action]',
-                    'constraints' => array(
-                        'action'     => '[a-zA-Z][a-zA-Z0-9_-]*',
-                    ),
-                    'defaults' => array(
-                        'controller' => 'Application\Controller\Demo',
-                        'action'     => 'index',
-                    ),
-                ),
-            ),
-        ),
-    ),
-    'navigation' => array(
-        'default' => array(
-            'home' => array(
-                'pages' => array(
-//                    'demo' => array(
-//                        'label'    => 'Démo',
-//                        'route'    => 'demo',
-//                        'params' => array(
-//                            'action' => 'index',
-//                        ),
-//                        'pages' => array(
-////                            'of' => array(
-////                                'label'  => "Offre de formation",
-////                                'route'  => 'demo',
-////                                'params' => array(
-////                                    'action' => 'of',
-////                                ),
-////                                'visible' => true,
-////                                'pages' => array(),
-////                            ),
-//                            'intervenant' => array(
-//                                'label'  => "Intervenants",
-//                                'route'  => 'demo',
-//                                'params' => array(
-//                                    'action' => 'intervenant',
-//                                ),
-//                                'visible' => true,
-//                                'pages' => array(),
-//                            ),
-//                            'service-ref' => array(
-//                                'label'  => "Service référentiel",
-//                                'route'  => 'demo',
-//                                'params' => array(
-//                                    'action' => 'saisir-service-referentiel-intervenant',
-//                                ),
-//                                'visible' => true,
-//                                'pages' => array(),
-//                            ),
-//                        ),
-//                    ),
-                ),
-            ),
-        ),
-    ),
-    'bjyauthorize' => array(
-        'guards' => array(
-            'BjyAuthorize\Guard\Controller' => array(
-                array(
-                    'controller' => 'Application\Controller\Demo',
-                    'roles' => array('user')),
-            ),
-        ),
-    ),
-    'controllers' => array(
-        'invokables' => array(
-            'Application\Controller\Demo'        => 'Application\Controller\DemoController',
-        ),
-    ),
-);
diff --git a/module/Application/config/module.config.php b/module/Application/config/module.config.php
index 8da92d4f63..f347b5b352 100755
--- a/module/Application/config/module.config.php
+++ b/module/Application/config/module.config.php
@@ -257,7 +257,6 @@ return array_merge_recursive(
     include 'piece-jointe.config.php',
     include 'structure.config.php',
     include 'etablissement.config.php',
-    include 'demo.config.php',
     include 'recherche.config.php',
     include 'service.config.php',
     include 'volume-horaire.config.php',
diff --git a/module/Application/src/Application/Controller/DemoController.php b/module/Application/src/Application/Controller/DemoController.php
deleted file mode 100755
index be0417a17d..0000000000
--- a/module/Application/src/Application/Controller/DemoController.php
+++ /dev/null
@@ -1,115 +0,0 @@
-<?php
-
-namespace Application\Controller;
-
-use Zend\Mvc\Controller\AbstractActionController;
-
-/**
- * 
- * @method \Doctrine\ORM\EntityManager                em()
- * @method \Application\Controller\Plugin\Context     context()
- * @method \Application\Controller\Plugin\Intervenant intervenant()
- * @method \Application\Controller\Plugin\Structure   structure()
- * @method \UnicaenApp\Controller\Plugin\ModalInnerViewModel modalInnerViewModel()
- */
-class DemoController extends AbstractActionController
-{
-    /**
-     * @return \Application\Service\ServiceReferentiel
-     */
-    public function getServiceReferentielService()
-    {
-        return $this->getServiceLocator()->get('ApplicationServiceReferentiel');
-    }
-    
-    /**
-     * 
-     * @return type
-     */
-    public function indexAction()
-    {
-        $repo = $this->em()->getRepository('Application\Entity\Db\ElementPedagogique');
-        $structures = $repo->finderDistinctStructures()->getQuery()->execute();
-                
-        $sl = $this->getServiceLocator();
-        $fs = $sl->get('FormElementManager')->get('FormElementPedagogiqueRechercheFieldset');
-        
-        $fs
-                ->setStructures(array($s = $structures[0]))
-                ->setEtapes($repo->finderDistinctEtapes(array('structure' => $s))->getQuery()->execute())
-                ->setStructuresSourceUrl(null)
-                ->setEtapesSourceUrl(null)
-                ;
-        $fs->get('structure')->setValue($s->getId());
-        
-        return array('fs' => $fs);
-    }
-    
-    /**
-     * 
-     * @return \Zend\View\Model\ViewModel
-     */
-    public function intervenantAction()
-    {
-        $url    = $this->url()->fromRoute('recherche', array('action' => 'intervenantFind'));
-        $interv = new \UnicaenApp\Form\Element\SearchAndSelect('interv');
-        $interv->setAutocompleteSource($url)
-                ->setLabel("Rechercher un intervenant :")
-                ->setAttributes(array('title' => "Saisissez le nom suivi éventuellement du prénom (2 lettres au moins)"));
-        $form   = new \Zend\Form\Form('search');
-        $form->setAttributes(array('class' => 'intervenant-rech'));
-        $form->add($interv);
-
-        $view = new \Zend\View\Model\ViewModel();
-        $view->setVariables(array('form' => $form, 'title' => "Intervenant..."));
-        
-        return $view;
-    }
-
-    /**
-     * 
-     * @return \Zend\View\Model\ViewModel
-     * @see IntervenantController
-     */
-    public function voirIntervenantAction()
-    {
-        if (!($sourceCode = $this->params()->fromQuery('sourceCode', $this->params()->fromPost('sourceCode')))) {
-            if ($this->getRequest()->isXmlHttpRequest()) {
-                exit;
-            }
-            return $this->redirect()->toRoute('home');
-        }
-
-        $controller = 'Application\Controller\Intervenant';
-        $params     = $this->getEvent()->getRouteMatch()->getParams();
-
-        // import si besoin
-        if (!($intervenant = $this->intervenant()->getRepo()->findOneBy(array('sourceCode' => $sourceCode)))) {
-            $params['action'] = 'importer';
-            $params['id']     = $sourceCode;
-            $viewModel        = $this->forward()->dispatch($controller, $params); /* @var $viewModel \Zend\View\Model\ViewModel */
-            $intervenant      = $viewModel->getVariable('intervenant');
-        }
-
-        $params['action'] = 'voir';
-        $params['id']     = $intervenant->getId();
-        $viewModel        = $this->forward()->dispatch($controller, $params);
-
-        return $viewModel;
-    }
-
-    /**
-     * 
-     * @return \Zend\View\Model\ViewModel
-     */
-    public function saisirServiceReferentielIntervenantAction()
-    {
-        $controller = 'Application\Controller\Intervenant';
-        $params     = $this->getEvent()->getRouteMatch()->getParams();
-
-        $params['action'] = 'saisirServiceReferentiel';
-        $viewModel        = $this->forward()->dispatch($controller, $params);
-
-        return $viewModel;
-    }
-}
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/EtablissementController.php b/module/Application/src/Application/Controller/EtablissementController.php
index b4b371028b..882c6815f1 100644
--- a/module/Application/src/Application/Controller/EtablissementController.php
+++ b/module/Application/src/Application/Controller/EtablissementController.php
@@ -60,6 +60,11 @@ class EtablissementController extends AbstractActionController
 
     public function rechercheAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            'Application\Entity\Db\Etablissement',
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         if (!($term = $this->params()->fromQuery('term'))) {
             return new JsonModel(array());
         }
diff --git a/module/Application/src/Application/Controller/IntervenantController.php b/module/Application/src/Application/Controller/IntervenantController.php
index 5624a84c38..526753c208 100644
--- a/module/Application/src/Application/Controller/IntervenantController.php
+++ b/module/Application/src/Application/Controller/IntervenantController.php
@@ -133,6 +133,7 @@ class IntervenantController extends AbstractActionController implements ContextP
 
     public function voirAction()
     {
+         //       \Test\Util::sqlLog($this->em());
         $role = $this->getContextProvider()->getSelectedIdentityRole();
         
         $this->em()->getFilters()->enable('historique');
@@ -143,37 +144,7 @@ class IntervenantController extends AbstractActionController implements ContextP
         else {
             $intervenant = $this->context()->mandatory()->intervenantFromRoute();
         }
-        
-        // fetch avec jointures
-        $entityClass = $intervenant instanceof IntervenantExterieur ? 
-                'Application\Entity\Db\IntervenantExterieur' : 
-                'Application\Entity\Db\IntervenantPermanent';
-        $qb = $this->em()->getRepository($entityClass)->createQueryBuilder("i")
-                ->addSelect("ti, si, c, src, a, aff, affr, d")
-                ->join("i.type", "ti")
-                ->join("i.statut", "si")
-                ->join("i.civilite", "c")
-                ->join("i.source", "src")
-                ->leftJoin("i.utilisateur", "u")
-                ->leftJoin("i.adresse", "a")
-                ->leftJoin("i.structure", "aff")
-                ->leftJoin("i.affectation", "affr")
-                ->leftJoin("i.discipline", "d")
-                ->where("i = :intervenant")->setParameter('intervenant', $intervenant);
-        if ($intervenant instanceof IntervenantExterieur) {
-            $qb
-                    ->addSelect("sf, rs, tp")
-                    ->leftJoin("i.situationFamiliale", "sf")
-                    ->leftJoin("i.regimeSecu", "rs")
-                    ->leftJoin("i.typePoste", "tp");
-        }
-        else {
-            $qb
-                    ->addSelect("co")
-                    ->leftJoin("i.corps", "co");
-        }
-        $intervenant = $qb->getQuery()->getSingleResult();
-        
+
         $import = $this->getServiceLocator()->get('ImportProcessusImport');
         $changements = $import->intervenantGetDifferentiel($intervenant);
         $short = $this->params()->fromQuery('short', false);
@@ -202,10 +173,6 @@ class IntervenantController extends AbstractActionController implements ContextP
 
     public function voirHeuresCompAction()
     {
-        $this->em()->getFilters()->enable('historique')
-                ->disableForEntity('Application\Entity\Db\ElementPedagogique')
-                ->disableForEntity('Application\Entity\Db\Etablissement');
-
         $intervenant = $this->context()->mandatory()->intervenantFromRoute();
         /* @var $intervenant \Application\Entity\Db\Intervenant */
         $form = $this->getFormHeuresComp();
@@ -363,8 +330,6 @@ class IntervenantController extends AbstractActionController implements ContextP
     {
         $role = $this->getContextProvider()->getSelectedIdentityRole();
 
-        $this->em()->getFilters()->enable('historique');
-
         if ($role instanceof \Application\Acl\IntervenantRole) {
             $intervenant = $role->getIntervenant();
         }
@@ -391,40 +356,6 @@ class IntervenantController extends AbstractActionController implements ContextP
         return $view;
     }
     
-    public function modifierAction()
-    {
-        if (!($id = $this->params()->fromRoute('id'))) {
-            throw new LogicException("Aucun identifiant d'intervenant spécifié.");
-        }
-        if (!($intervenant = $this->intervenant()->getRepo()->find($id))) {
-            throw new RuntimeException("Intervenant '$id' spécifié introuvable.");
-        }
-
-        $form = $this->getFormModifier();
-        $form->bind($intervenant);
-
-        if (($data = $this->params()->fromPost())) {
-            $form->setData($data);
-            if ($form->isValid()) {
-                $em = $this->intervenant()->getEntityManager();
-                $em->flush($form->getObject());
-            }
-        }
-        
-        $view = new \Zend\View\Model\ViewModel();
-        $view->setVariables(array('form' => $form, 'intervenant' => $intervenant));
-        return $view;
-    }
-    
-    protected function getFormModifier()
-    {
-        $builder = new AnnotationBuilder();
-        $form    = $builder->createForm('Application\Entity\Db\Intervenant');
-        $form->getHydrator()->setUnderscoreSeparatedKeys(false);
-        
-        return $form;
-    }
-    
     /**
      * @return \Application\Service\Intervenant
      */
diff --git a/module/Application/src/Application/Controller/ModificationServiceDuController.php b/module/Application/src/Application/Controller/ModificationServiceDuController.php
index d23bee76a0..1690a15dc8 100644
--- a/module/Application/src/Application/Controller/ModificationServiceDuController.php
+++ b/module/Application/src/Application/Controller/ModificationServiceDuController.php
@@ -27,25 +27,28 @@ class ModificationServiceDuController extends AbstractActionController implement
      */
     public function saisirAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            'Application\Entity\Db\ModificationServiceDu',
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         $context     = $this->getContextProvider()->getGlobalContext();
         $isAjax      = $this->getRequest()->isXmlHttpRequest();
         $intervenant = $this->context()->mandatory()->intervenantFromRoute(); /* @var $intervenant IntervenantPermanent */
         $role        = $this->getContextProvider()->getSelectedIdentityRole();
-        
+
         $rule = $this->getServiceLocator()->get('PeutSaisirModificationServiceDuRule')
                 ->setIntervenant($intervenant)
                 ->setStructure($role instanceof ComposanteRole ? $role->getStructure() : null);
         if (!$rule->execute()) {
             throw new MessageException("La modification de service dû n'est pas possible. ", null, new \Exception($rule->getMessage()));
         }
-        
-        $this->em()->getFilters()->enable("historique");
-        
+
         // fetch intervenant avec jointure sur les modifs de service dû
         $qb = $this->getServiceIntervenant()->getFinderIntervenantPermanentWithModificationServiceDu();
         $qb->setIntervenant($intervenant);
         $intervenant = $qb->getQuery()->getOneOrNullResult(); /* @var $intervenant IntervenantPermanent */
-        
+
         $annee = $context->getAnnee();
         
         // NB: patch pour permettre de vider toutes les modifs de service dû
@@ -60,13 +63,13 @@ class ModificationServiceDuController extends AbstractActionController implement
                 $this->em()->refresh($intervenant);
             }
         }
-        
+
         $form = $this->getServiceLocator()->get('form_element_manager')->get('IntervenantModificationServiceDuForm');
         /* @var $form \Application\Form\Intervenant\ModificationServiceDuForm */
         $form->setAttribute('action', $this->getRequest()->getRequestUri());
         $form->getBaseFieldset()->getHydrator()->setAnnee($annee);
         $form->bind($intervenant);
-        
+
         $variables = array(
             'form' => $form, 
             'intervenant' => $intervenant,
@@ -97,7 +100,7 @@ class ModificationServiceDuController extends AbstractActionController implement
                 }
             }
         }
-        
+
         $viewModel = new \Zend\View\Model\ViewModel();
         $viewModel->setVariables($variables);
 
@@ -105,76 +108,9 @@ class ModificationServiceDuController extends AbstractActionController implement
                 
         $viewModel = new \Zend\View\Model\ViewModel();
         $viewModel->setVariables($variables);
-        
+
         return $viewModel;
     }
-
-    /**
-     * 
-     * @param bool $import Importer l'intervenant si besoin ?
-     * @return \Application\Entity\Db\Intervenant
-     * @throws RuntimeException Intervenant spécifié par son code source introuvable
-     */
-//    protected function getIntervenant($import = true)
-//    {
-//        $sourceCode  = $this->params()->fromQuery('sourceCode', $this->params('id'));
-//        $intervenant = null;
-//        
-//        if ($sourceCode) {
-//            // test d'existence de l'intervenant et import éventuel
-//            $intervenant = $this->em()->getRepository('Application\Entity\Db\Intervenant')->findOneBySourceCode($sourceCode);
-//            if (!$intervenant) {
-//                if (!$import) {
-//                    throw new RuntimeException("Intervenant spécifié introuvable (sourceCode = $sourceCode).");
-//                }
-//                // import de l'intervenant
-//                $intervenant = $this->getServiceLocator()->get('ApplicationIntervenant')->importer($sourceCode);
-//            }
-//            
-//            return $intervenant;
-//        }
-//        
-//        $context = $this->getContextProvider()->getLocalContext();
-//        $role    = $this->getContextProvider()->getSelectedIdentityRole();
-//        
-//        if ($role instanceof \Application\Acl\IntervenantRole) {
-//            $intervenant = $role->getIntervenant();
-//        }
-//        
-//        if ($role instanceof \Application\Acl\DbRole) {
-//            // récupère l'éventuel intervenant du contexte local
-//            $intervenant = $context->getIntervenant();
-//        }
-//        
-//        return $intervenant;
-//    }
-//    
-//    /**
-//     * Redirection vers le choix d'un intervenant (action qui redirigera vers l'action 
-//     * courante une fois l'intervenant choisi).
-//     * 
-//     * @param \Application\Entity\Db\Intervenant $intervenant Intervenant pré-choisi
-//     * @return \Zend\Http\Response
-//     * @see IntervenantController
-//     */
-//    protected function redirectToChoisirIntervenant(\Application\Entity\Db\Intervenant $intervenant = null)
-//    {
-//        $modal    = $this->params()->fromQuery('modal');
-//        $redirect = $this->url()->fromRoute(
-//                null, 
-//                array(), 
-//                array('query' => array('sourceCode' => '__sourceCode__', 'modal' => $modal)), 
-//                true);
-//        
-//        if ($intervenant) {
-//           $intervenant = $intervenant->getSourceCode();
-//        }
-//        
-//        return $this->redirect()->toRoute(
-//                'intervenant/default', 
-//                array('action' => 'choisir'), 
-//                array('query' => array('intervenant' => $intervenant, 'redirect' => $redirect, 'modal' => $modal)));
-//    }
     
     /**
      * @return \Application\Service\Intervenant
diff --git a/module/Application/src/Application/Controller/OffreFormationController.php b/module/Application/src/Application/Controller/OffreFormationController.php
index 7e457683da..e1a35b010f 100644
--- a/module/Application/src/Application/Controller/OffreFormationController.php
+++ b/module/Application/src/Application/Controller/OffreFormationController.php
@@ -32,7 +32,13 @@ class OffreFormationController extends AbstractActionController implements Conte
      */
     public function indexAction()
     {
-        $this->em()->getFilters()->enable('historique');
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\ElementPedagogique',
+                'Application\Entity\Db\Etape'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
         
         $serviceEp    = $this->getServiceLocator()->get('applicationElementPedagogique'); /* @var $serviceEp ElementPedagogiqueService */
         $serviceEtape = $this->getServiceLocator()->get('applicationEtape'); /* @var $serviceEtape EtapeService */
@@ -131,7 +137,13 @@ class OffreFormationController extends AbstractActionController implements Conte
         $serviceEp    = $this->getServiceLocator()->get('applicationElementPedagogique'); /* @var $serviceEp ElementPedagogiqueService */
         $role         = $this->getContextProvider()->getSelectedIdentityRole();
 
-        $em->getFilters()->enable('historique');
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\ElementPedagogique',
+                'Application\Entity\Db\Etape'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
 
         // extraction des filtres spécifiés dans la requête
         $structure = $this->context()->structureFromQuery();
@@ -188,6 +200,11 @@ class OffreFormationController extends AbstractActionController implements Conte
      */
     public function searchStructuresAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            'Application\Entity\Db\Structure',
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         $serviceStructure = $this->getServiceLocator()->get('applicationStructure'); /* @var $serviceStructure \Application\Service\Structure */
         $result = $serviceStructure->getList( $serviceStructure->finderByEnseignement() );
         
@@ -202,8 +219,16 @@ class OffreFormationController extends AbstractActionController implements Conte
      */
     public function searchNiveauxAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\Etape',
+                'Application\Entity\Db\CheminPedagogique',
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         $structure = $this->context()->structureFromQuery();
-        
+
         $params = array();
         $params['structure'] = $structure instanceof \Application\Entity\Db\Structure ? $structure : null;
         
diff --git a/module/Application/src/Application/Controller/PaiementController.php b/module/Application/src/Application/Controller/PaiementController.php
index 2b9546a7e8..000bf8d5da 100644
--- a/module/Application/src/Application/Controller/PaiementController.php
+++ b/module/Application/src/Application/Controller/PaiementController.php
@@ -25,11 +25,10 @@ class PaiementController extends AbstractActionController implements ContextProv
      */
     protected function initFilters()
     {
-        $this->em()->getFilters()->enable('historique')
-                ->disableForEntity('Application\Entity\Db\ElementPedagogique')
-                ->disableForEntity('Application\Entity\Db\Etape')
-                ->disableForEntity('Application\Entity\Db\Etablissement')
-                ->disableForEntity('Application\Entity\Db\FonctionReferentiel');
+        $this->em()->getFilters()->enable('historique')->init(
+            'Application\Entity\Db\MiseEnPaiement',
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
     }
 
     public function indexAction()
@@ -46,7 +45,6 @@ class PaiementController extends AbstractActionController implements ContextProv
         if ($this->getRequest()->isPost()) {
             $changements = $this->params()->fromPost('changements', '{}');
             $changements = Json::decode($changements, Json::TYPE_ARRAY);
-            //var_dump($changements);
             $this->getServiceMiseEnPaiement()->saveChangements($changements);
             $saved = true;
         }
@@ -124,6 +122,7 @@ class PaiementController extends AbstractActionController implements ContextProv
 
     public function misesEnPaiementCsvAction()
     {
+        $this->initFilters();
         $role = $this->getContextProvider()->getSelectedIdentityRole();
 
         $recherche = new MiseEnPaiementRecherche;
@@ -221,6 +220,7 @@ class PaiementController extends AbstractActionController implements ContextProv
 
     public function extractionWinpaieAction()
     {
+        $this->initFilters();
         $periode = $this->params()->fromRoute('periode');
         $periode = $this->getServicePeriode()->getRepo()->findOneBy(['code' => $periode]);
 
@@ -256,6 +256,7 @@ class PaiementController extends AbstractActionController implements ContextProv
 
     public function miseEnPaiementAction()
     {
+        $this->initFilters();
         $title = 'Mise en paiement';
         $structure    = $this->context()->mandatory()->structureFromRoute();
         $intervenants = $this->params('intervenants');
diff --git a/module/Application/src/Application/Controller/Plugin/Context.php b/module/Application/src/Application/Controller/Plugin/Context.php
index 46bff98257..6f5a6d3d51 100644
--- a/module/Application/src/Application/Controller/Plugin/Context.php
+++ b/module/Application/src/Application/Controller/Plugin/Context.php
@@ -4,7 +4,7 @@ namespace Application\Controller\Plugin;
 
 use Zend\Mvc\Controller\Plugin\Params;
 use Zend\ServiceManager\ServiceLocatorAwareInterface;
-use Zend\ServiceManager\ServiceLocatorInterface;
+use Zend\ServiceManager\ServiceLocatorAwareTrait;
 use Zend\Session\Container;
 use Application\Service\LocalContext;
 use Application\Service\GlobalContext;
@@ -27,6 +27,8 @@ use Common\Exception\RuntimeException;
  */
 class Context extends Params implements ServiceLocatorAwareInterface
 {
+    use ServiceLocatorAwareTrait;
+
     /**
      * @var ServiceLocatorInterface
      */
@@ -135,13 +137,13 @@ class Context extends Params implements ServiceLocatorAwareInterface
             }
         }
 
-        $em = $this->getServiceLocator()->get('doctrine.entitymanager.orm_default');
+        $em = $this->getServiceLocator()->getServiceLocator()->get('doctrine.entitymanager.orm_default');
 
         /* Cas particulier pour les intervenants : import implicite */
         if ('intervenant' === $target && (int)$value){
             $sourceCode = (string)(int)$value;
             if (!($intervenant = $em->getRepository('Application\Entity\Db\Intervenant')->findOneBySourceCode($sourceCode))) {
-                $this->getServiceLocator()->get('importProcessusImport')->intervenant($sourceCode); // Import
+                $this->getServiceLocator()->getServiceLocator()->get('importProcessusImport')->intervenant($sourceCode); // Import
                 if (!($intervenant = $em->getRepository('Application\Entity\Db\Intervenant')->findOneBySourceCode($sourceCode))) {
                     throw new RuntimeException("L'intervenant suivant est introuvable après import : sourceCode = $sourceCode.");
                 }
@@ -258,7 +260,7 @@ class Context extends Params implements ServiceLocatorAwareInterface
     public function getGlobalContext()
     {
         if (null === $this->globalContext) {
-            $this->globalContext = $this->sl->get('ApplicationContextProvider')->getGlobalContext();
+            $this->globalContext = $this->getServiceLocator()->getServiceLocator()->get('ApplicationContextProvider')->getGlobalContext();
         }
         return $this->globalContext;
     }
@@ -269,7 +271,7 @@ class Context extends Params implements ServiceLocatorAwareInterface
     public function getLocalContext()
     {
         if (null === $this->localContext) {
-            $this->localContext = $this->sl->get('ApplicationContextProvider')->getLocalContext();
+            $this->localContext = $this->getServiceLocator()->getServiceLocator()->get('ApplicationContextProvider')->getLocalContext();
         }
         return $this->localContext;
     }
@@ -284,26 +286,4 @@ class Context extends Params implements ServiceLocatorAwareInterface
         }
         return $this->sessionContainer;
     }
-    
-    /**
-     * Set service locator
-     *
-     * @param ServiceLocatorInterface $serviceLocator
-     */
-    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
-    {
-        $this->sl = $serviceLocator->getServiceLocator();
-        
-        return $this;
-    }
-
-    /**
-     * Get service locator
-     *
-     * @return ServiceLocatorInterface
-     */
-    public function getServiceLocator()
-    {
-        return $this->sl;
-    }
 }
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/Plugin/Em.php b/module/Application/src/Application/Controller/Plugin/Em.php
index 9544139eb8..bb9f7af5ed 100644
--- a/module/Application/src/Application/Controller/Plugin/Em.php
+++ b/module/Application/src/Application/Controller/Plugin/Em.php
@@ -4,7 +4,7 @@ namespace Application\Controller\Plugin;
 
 use Zend\Mvc\Controller\Plugin\AbstractPlugin;
 use Zend\ServiceManager\ServiceLocatorAwareInterface;
-use Zend\ServiceManager\ServiceLocatorInterface;
+use Zend\ServiceManager\ServiceLocatorAwareTrait;
 use Doctrine\ORM\EntityManager;
 
 /**
@@ -14,10 +14,7 @@ use Doctrine\ORM\EntityManager;
  */
 class Em extends AbstractPlugin implements ServiceLocatorAwareInterface
 {
-    /**
-     * @var ServiceLocatorInterface
-     */
-    protected $sl;
+    use ServiceLocatorAwareTrait;
     
     /**
      * @var EntityManager
@@ -34,7 +31,7 @@ class Em extends AbstractPlugin implements ServiceLocatorAwareInterface
     {
         return $this->getEntityManager($name);
     }
-    
+
     /**
      * Retourne le gestionnaire d'entités.
      * 
@@ -44,31 +41,9 @@ class Em extends AbstractPlugin implements ServiceLocatorAwareInterface
     protected function getEntityManager($name)
     {
         if (null === $this->em) {
-            $this->em = $this->sl->get("doctrine.entitymanager.$name");
+            $this->em = $this->getServiceLocator()->getServiceLocator()->get("doctrine.entitymanager.$name");
         }
         
         return $this->em;
     }
-    
-    /**
-     * Set service locator
-     *
-     * @param ServiceLocatorInterface $serviceLocator
-     */
-    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
-    {
-        $this->sl = $serviceLocator->getServiceLocator();
-        
-        return $this;
-    }
-
-    /**
-     * Get service locator
-     *
-     * @return ServiceLocatorInterface
-     */
-    public function getServiceLocator()
-    {
-        return $this->sl;
-    }
 }
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/Plugin/Intervenant.php b/module/Application/src/Application/Controller/Plugin/Intervenant.php
deleted file mode 100644
index 699979b922..0000000000
--- a/module/Application/src/Application/Controller/Plugin/Intervenant.php
+++ /dev/null
@@ -1,28 +0,0 @@
-<?php
-
-namespace Application\Controller\Plugin;
-
-use Common\Controller\Plugin\BasePlugin;
-
-/**
- * Description of Intervenant
- *
- * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
- */
-class Intervenant extends BasePlugin
-{
-    public function __invoke()
-    {
-        return $this;
-    }
-    
-    /**
-     * Retourne le repository.
-     * 
-     * @return \Application\Entity\Db\Repository\IntervenantRepository
-     */
-    public function getRepo()
-    {
-        return $this->getEntityManager()->getRepository('Application\Entity\Db\Intervenant');
-    }
-}
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/Plugin/IntervenantFactory.php b/module/Application/src/Application/Controller/Plugin/IntervenantFactory.php
deleted file mode 100644
index 9e70429278..0000000000
--- a/module/Application/src/Application/Controller/Plugin/IntervenantFactory.php
+++ /dev/null
@@ -1,28 +0,0 @@
-<?php
-
-namespace Application\Controller\Plugin;
-
-use Zend\ServiceManager\FactoryInterface;
-use Zend\ServiceManager\ServiceLocatorInterface;
-
-/**
- * Description of IntervenantFactory
- *
- * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
- */
-class IntervenantFactory implements FactoryInterface
-{
-
-    /**
-     * Create service
-     *
-     * @param ServiceLocatorInterface $serviceLocator
-     * @return mixed
-     */
-    public function createService(ServiceLocatorInterface $serviceLocator) /* @var $serviceLocator \Zend\Mvc\Controller\PluginManager */
-    {
-        $em = $serviceLocator->getServiceLocator()->get('doctrine.entitymanager.orm_default');
-        
-        return new Intervenant($em);
-    }
-}
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/Plugin/ServiceReferentiel.php b/module/Application/src/Application/Controller/Plugin/ServiceReferentiel.php
deleted file mode 100644
index 84f9ece25f..0000000000
--- a/module/Application/src/Application/Controller/Plugin/ServiceReferentiel.php
+++ /dev/null
@@ -1,28 +0,0 @@
-<?php
-
-namespace Application\Controller\Plugin;
-
-use Common\Controller\Plugin\BasePlugin;
-
-/**
- * Description of ServiceReferentiel
- *
- * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
- */
-class ServiceReferentiel extends BasePlugin
-{
-    public function __invoke()
-    {
-        return $this;
-    }
-    
-    /**
-     * Retourne le repository.
-     * 
-     * @return \Application\Entity\Db\Repository\IntervenantRepository
-     */
-    public function getRepo()
-    {
-        return $this->getEntityManager()->getRepository('Application\Entity\Db\ServiceReferentiel');
-    }
-}
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/Plugin/ServiceReferentielFactory.php b/module/Application/src/Application/Controller/Plugin/ServiceReferentielFactory.php
deleted file mode 100644
index 6e7e3c57b5..0000000000
--- a/module/Application/src/Application/Controller/Plugin/ServiceReferentielFactory.php
+++ /dev/null
@@ -1,28 +0,0 @@
-<?php
-
-namespace Application\Controller\Plugin;
-
-use Zend\ServiceManager\FactoryInterface;
-use Zend\ServiceManager\ServiceLocatorInterface;
-
-/**
- * Description of IntervenantFactory
- *
- * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
- */
-class ServiceReferentielFactoryFactory implements FactoryInterface
-{
-
-    /**
-     * Create service
-     *
-     * @param ServiceLocatorInterface $serviceLocator
-     * @return mixed
-     */
-    public function createService(ServiceLocatorInterface $serviceLocator) /* @var $serviceLocator \Zend\Mvc\Controller\PluginManager */
-    {
-        $em = $serviceLocator->getServiceLocator()->get('doctrine.entitymanager.orm_default');
-        
-        return new ServiceReferentiel($em);
-    }
-}
\ No newline at end of file
diff --git a/module/Application/src/Application/Controller/RechercheController.php b/module/Application/src/Application/Controller/RechercheController.php
index 8504f147b3..9d571501b9 100644
--- a/module/Application/src/Application/Controller/RechercheController.php
+++ b/module/Application/src/Application/Controller/RechercheController.php
@@ -37,6 +37,11 @@ class RechercheController extends AbstractActionController
     
     public function intervenantFindAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            'Application\Entity\Db\Intervenant',
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         if (!($term = $this->params()->fromQuery('term'))) {
             return new JsonModel(array());
         }
diff --git a/module/Application/src/Application/Controller/ServiceController.php b/module/Application/src/Application/Controller/ServiceController.php
index df6a75dac7..95cbc886da 100644
--- a/module/Application/src/Application/Controller/ServiceController.php
+++ b/module/Application/src/Application/Controller/ServiceController.php
@@ -27,10 +27,13 @@ class ServiceController extends AbstractActionController
      */
     protected function initFilters()
     {
-        $this->em()->getFilters()->enable('historique')
-                ->disableForEntity('Application\Entity\Db\ElementPedagogique')
-                ->disableForEntity('Application\Entity\Db\Etape')
-                ->disableForEntity('Application\Entity\Db\Etablissement');
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\Service',
+                'Application\Entity\Db\VolumeHoraire'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
     }
 
     /**
@@ -214,7 +217,6 @@ class ServiceController extends AbstractActionController
             throw new \BjyAuthorize\Exception\UnAuthorizedException();
         }
 
-        $this->initFilters();
         if ($intervenant){
             $this->getContextProvider()->getLocalContext()->setIntervenant($intervenant);
         }
@@ -256,8 +258,6 @@ class ServiceController extends AbstractActionController
 
     public function resumeRefreshAction()
     {
-        $this->initFilters();
-
         $filter = $this->getFormRecherche()->hydrateFromSession();
 
         return compact('filter');
@@ -345,6 +345,7 @@ class ServiceController extends AbstractActionController
 
     public function constatationAction()
     {
+        $this->initFilters();
         $errors = [];
         $typeVolumeHoraire = $this->getServiceTypeVolumehoraire()->getRealise();
         $services = $this->params()->fromQuery('services');
diff --git a/module/Application/src/Application/Controller/ServiceReferentielController.php b/module/Application/src/Application/Controller/ServiceReferentielController.php
index 8e757dd270..313e306145 100644
--- a/module/Application/src/Application/Controller/ServiceReferentielController.php
+++ b/module/Application/src/Application/Controller/ServiceReferentielController.php
@@ -30,8 +30,13 @@ class ServiceReferentielController extends AbstractActionController implements C
 
     protected function initFilters()
     {
-        $this->em()->getFilters()->enable('historique')
-                ->disableForEntity('Application\Entity\Db\FonctionReferentiel');
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\ServiceReferentiel',
+                'Application\Entity\Db\VolumeHoraireReferentiel'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
     }
 
     /**
@@ -206,6 +211,7 @@ class ServiceReferentielController extends AbstractActionController implements C
 
     public function constatationAction()
     {
+        $this->initFilters();
         $services = $this->params()->fromQuery('services');
         if ($services){
             $services = explode( ',', $services );
diff --git a/module/Application/src/Application/Controller/StructureController.php b/module/Application/src/Application/Controller/StructureController.php
index 4a9d251126..460b5bb523 100644
--- a/module/Application/src/Application/Controller/StructureController.php
+++ b/module/Application/src/Application/Controller/StructureController.php
@@ -63,8 +63,8 @@ class StructureController extends AbstractActionController
         if (!($term = $this->params()->fromQuery('term'))) {
             return new JsonModel(array());
         }
-
-        $entities  = $this->getServiceStructure()->finderByNom($term)->getQuery()->execute();
+        $qb = $this->getServiceStructure()->finderByHistorique();
+        $entities  = $this->getServiceStructure()->finderByNom($term, $qb)->getQuery()->execute();
         $result = array();
 
         foreach ($entities as $item) { /* @var $item \Application\Entity\Db\Structure */
diff --git a/module/Application/src/Application/Controller/VolumeHoraireController.php b/module/Application/src/Application/Controller/VolumeHoraireController.php
index e041673026..d7323aeb21 100644
--- a/module/Application/src/Application/Controller/VolumeHoraireController.php
+++ b/module/Application/src/Application/Controller/VolumeHoraireController.php
@@ -38,6 +38,12 @@ class VolumeHoraireController extends AbstractActionController
 
     public function listeAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\VolumeHoraire'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
         $service = $this->context()->serviceFromRoute('id');
         if (! $service) throw new RuntimeException("Service non spécifié ou introuvable.");
 
@@ -50,6 +56,13 @@ class VolumeHoraireController extends AbstractActionController
 
     public function saisieAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\VolumeHoraire'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         $service            = $this->context()->serviceFromRoute();
         $typeVolumehoraire  = $this->context()->typeVolumeHoraireFromQueryPost('type-volume-horaire');
         $periode            = $this->context()->periodeFromQueryPost();
diff --git a/module/Application/src/Application/Controller/VolumeHoraireReferentielController.php b/module/Application/src/Application/Controller/VolumeHoraireReferentielController.php
index 985d115ed7..6b3db8dffb 100644
--- a/module/Application/src/Application/Controller/VolumeHoraireReferentielController.php
+++ b/module/Application/src/Application/Controller/VolumeHoraireReferentielController.php
@@ -38,6 +38,12 @@ class VolumeHoraireReferentielController extends AbstractActionController
 
     public function listeAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\VolumeHoraireReferentiel'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
         $service = $this->context()->serviceReferentielFromRoute('id');
         if (! $service) throw new RuntimeException("Service non spécifié ou introuvable.");
 
@@ -50,6 +56,12 @@ class VolumeHoraireReferentielController extends AbstractActionController
 
     public function saisieAction()
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\VolumeHoraireReferentiel'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
         $service           = $this->context()->serviceReferentielFromRoute(); /* @var $service \Application\Entity\Db\ServiceReferentiel */
         $typeVolumehoraire = $this->context()->typeVolumeHoraireFromQueryPost('type-volume-horaire');
         $errors = array();
diff --git a/module/Application/src/Application/Provider/Role/RoleProvider.php b/module/Application/src/Application/Provider/Role/RoleProvider.php
index 1ffdfe8e29..38ed45e90e 100644
--- a/module/Application/src/Application/Provider/Role/RoleProvider.php
+++ b/module/Application/src/Application/Provider/Role/RoleProvider.php
@@ -22,6 +22,7 @@ use Zend\Permissions\Acl\Role\RoleInterface;
 class RoleProvider implements ProviderInterface, EntityManagerAwareInterface
 {
     use EntityManagerAwareTrait;
+    use \Zend\ServiceManager\ServiceLocatorAwareTrait;
 
     /**
      * @var array
@@ -33,6 +34,7 @@ class RoleProvider implements ProviderInterface, EntityManagerAwareInterface
      */
     protected $roles;
 
+
     /**
      * Constructeur.
      * @param array $config
@@ -53,45 +55,68 @@ class RoleProvider implements ProviderInterface, EntityManagerAwareInterface
     public function getRoles()
     {
         if (null === $this->roles) {
-            $this->roles = array();
+            $this->roles = $this->makeRoles();
+        }
+        return $this->roles;
+    }
 
-            // Chargement des rôles de base
-            foreach( $this->config as $classname ){
-                if (class_exists( $classname )){
-                    $role = new $classname; /* @var $role RoleInterface */
-                    $this->roles[$role->getRoleId()] = $role;
-                }else{
-                    throw new LogicException('La classe "'.$classname.'" déclarée dans la configuration du fournisseur de rôles n\'a pas été trouvée.');
-                }
-            }
+    protected function makeRoles()
+    {
+        $roles = [];
 
+        // Chargement des rôles de base
+        foreach( $this->config as $classname ){
+            if (class_exists( $classname )){
+                $role = new $classname; /* @var $role RoleInterface */
+                $roles[$role->getRoleId()] = $role;
+            }else{
+                throw new LogicException('La classe "'.$classname.'" déclarée dans la configuration du fournisseur de rôles n\'a pas été trouvée.');
+            }
+        }
+        if (($utilisateur = $this->getUtilisateur()) && ($personnel = $utilisateur->getPersonnel())){
             // chargement des rôles métiers
             $qb = $this->getEntityManager()->createQueryBuilder()
                 ->from("Application\Entity\Db\Role", "r")
                 ->select("r, tr, s")
                 ->distinct()
                 ->join("r.type", "tr")
-                ->leftJoin("r.structure", "s");
+                ->leftJoin("r.structure", "s")
+                ->andWhere('1=compriseEntre(r.histoCreation,r.histoDestruction)')
+                ->andWhere('1=compriseEntre(tr.histoCreation,tr.histoDestruction)')
+                ->andWhere("r.personnel = :personnel")->setParameter(':personnel', $personnel);
             foreach ($qb->getQuery()->getResult() as $role) { /* @var $role Role */
                 $roleId = $role->getType()->getCode();
-                if (! isset($this->roles[$roleId])){
+                if (! isset($roles[$roleId])){
                     throw new Exception('Le rôle "'.$roleId.'" est inconnu.');
                 }
-                $classname = get_class($this->roles[$roleId]);
-                if ($this->roles[$roleId] instanceof StructureAwareInterface && $role->getStructure()){
+                $classname = get_class($roles[$roleId]);
+                if ($roles[$roleId] instanceof StructureAwareInterface && $role->getStructure()){
                     $roleId .= '-'.$role->getStructure()->getSourceCode();
-                    $this->roles[$roleId] = new $classname($roleId);
-                    $this->roles[$roleId]->setStructure( $role->getStructure() );
+                    $roles[$roleId] = new $classname($roleId);
+                    $roles[$roleId]->setStructure( $role->getStructure() );
                 }else{
-                    $this->roles[$roleId] = new $classname($roleId);
+                    $roles[$roleId] = new $classname($roleId);
                 }
-                $this->roles[$roleId]->setTypeRole( $role->getType() );
-                
-                $this->injectSelectedStructureInRole($this->roles[$roleId]);
+                $roles[$roleId]->setTypeRole( $role->getType() );
+
+                $this->injectSelectedStructureInRole($roles[$roleId]);
             }
         }
-        
-        return $this->roles;
+        return $roles;
+    }
+
+    /**
+     *
+     * @return \Application\Entity\Db\Utilisateur
+     */
+    public function getUtilisateur()
+    {
+        $identity = $this->getServiceLocator()->get('AuthUserContext')->getIdentity();
+        if (isset($identity['db'])){
+            return $identity['db'];
+        }else{
+            return null;
+        }
     }
 
     /**
diff --git a/module/Application/src/Application/Provider/Role/RoleProviderFactory.php b/module/Application/src/Application/Provider/Role/RoleProviderFactory.php
index 103b9263f6..9ae7bc4166 100644
--- a/module/Application/src/Application/Provider/Role/RoleProviderFactory.php
+++ b/module/Application/src/Application/Provider/Role/RoleProviderFactory.php
@@ -36,6 +36,7 @@ class RoleProviderFactory implements FactoryInterface
         $roleProvider = new RoleProvider( $providerConfig );
         $roleProvider
                 ->setEntityManager($em)
+                ->setServiceLocator($serviceLocator)
                 ->setStructureSelectionnee($contextProvider->getGlobalContext()->getStructure())
                 ->init();
         
diff --git a/module/Application/src/Application/Service/ContextProvider.php b/module/Application/src/Application/Service/ContextProvider.php
index 13579c403e..0b4c0d2c2e 100644
--- a/module/Application/src/Application/Service/ContextProvider.php
+++ b/module/Application/src/Application/Service/ContextProvider.php
@@ -62,9 +62,10 @@ class ContextProvider extends AbstractService
             
             if ($authUserContext->getIdentity()) {
                 $utilisateur = $authUserContext->getDbUser();
-                $intervenant = $utilisateur->getIntervenant();
-                $personnel   = $utilisateur->getPersonnel();
-                
+                if ($utilisateur){
+                    $intervenant = $utilisateur->getIntervenant();
+                    $personnel   = $utilisateur->getPersonnel();
+                }
                 if (null === $intervenant) {
                     $ldapUser = $authUserContext->getLdapUser();
                     $intervenant = $this->getServiceLocator()->get('ApplicationIntervenant')->importer((int) $ldapUser->getSupannEmpId());
diff --git a/module/Application/src/Application/Service/MotifNonPaiement.php b/module/Application/src/Application/Service/MotifNonPaiement.php
index 80f847a59e..83521d7029 100644
--- a/module/Application/src/Application/Service/MotifNonPaiement.php
+++ b/module/Application/src/Application/Service/MotifNonPaiement.php
@@ -62,7 +62,7 @@ class MotifNonPaiement extends AbstractEntityService
     public function getMotifsNonPaiement()
     {
         if (! $this->motifsNonPaiement){
-            $this->motifsNonPaiement = $this->getList();
+            $this->motifsNonPaiement = $this->getList( $this->finderByHistorique() );
         }
         return $this->motifsNonPaiement;
     }
diff --git a/module/Application/src/Application/Service/Service.php b/module/Application/src/Application/Service/Service.php
index 1c35c65f44..34efdb66f1 100644
--- a/module/Application/src/Application/Service/Service.php
+++ b/module/Application/src/Application/Service/Service.php
@@ -570,6 +570,13 @@ class Service extends AbstractEntityService
 
     public function setRealisesFromPrevus( ServiceEntity $service )
     {
+        $this->em()->getFilters()->enable('historique')->init(
+            [
+                'Application\Entity\Db\VolumeHoraire'
+            ],
+            $this->context()->getGlobalContext()->getDateObservation()
+        );
+
         $prevus = $service
                     ->getVolumeHoraireListe()->getChild()
                     ->setTypeVolumeHoraire( $this->getServiceTypeVolumeHoraire()->getPrevu() )
diff --git a/module/Application/src/Application/Service/ServiceAPayer.php b/module/Application/src/Application/Service/ServiceAPayer.php
index 2a04138990..94c7b52792 100644
--- a/module/Application/src/Application/Service/ServiceAPayer.php
+++ b/module/Application/src/Application/Service/ServiceAPayer.php
@@ -5,7 +5,6 @@ namespace Application\Service;
 use Application\Entity\Db\Intervenant as IntervenantEntity;
 use Application\Entity\Db\Annee as AnneeEntity;
 use Application\Entity\Db\ServiceAPayerInterface;
-use Doctrine\ORM\QueryBuilder;
 
 
 /**
diff --git a/module/Application/view/application/demo/index.phtml b/module/Application/view/application/demo/index.phtml
deleted file mode 100755
index 6fb493df28..0000000000
--- a/module/Application/view/application/demo/index.phtml
+++ /dev/null
@@ -1,6 +0,0 @@
-<div class="jumbotron">
-    <h1>Pages de démo</h1>
-    <h2>Organisation des Services d'Enseignement</h2>
-</div>
-
-<?php echo $this->fieldsetElementPedagogiqueRecherche($fs); ?>
diff --git a/module/Application/view/application/demo/intervenant.phtml b/module/Application/view/application/demo/intervenant.phtml
deleted file mode 100644
index 8aa70c8fef..0000000000
--- a/module/Application/view/application/demo/intervenant.phtml
+++ /dev/null
@@ -1,39 +0,0 @@
-<div class="jumbotron">
-    <h1>Intervenants</h1>
-</div>
-
-<style>
-    span.sas-highlight { font-weight: bold; }
-    .dl-horizontal dd .dl-horizontal { display: block; }
-</style>
-
-<?php $form->prepare(); ?>
-
-<div class="row">
-    <div class="col-md-3">
-        <?php echo $this->form()->openTag($form) ?> 
-        <?php echo $this->formControlGroup($form->get('interv')); ?>
-        <input class="btn btn-primary" type="submit" value="Importer / consulter" name="submit">
-        <?php echo $this->form()->closeTag() ?> 
-    </div>
-    <div class="col-md-9 intervenant-voir">
-    </div>
-</div>
-
-<script>
-    var url = '<?php echo $this->url('demo', array('action' => 'voirIntervenant')) ?>';
-    $("body").on("submit", "form.intervenant-rech", function(event) {
-        var div = $("div.intervenant-voir").addClass('fade');
-        var form = $(event.target);
-        var id = $("input.sas", form).val();
-        $.post(url, { 'sourceCode': id }, function(data) {
-            div.removeClass('fade').html(data);
-        });
-        event.preventDefault();
-    });
-
-    $(function() {
-//        $(".ui-autocomplete-input").on("autocompleteselect", function(event, ui) { console.log($(this).val()); });
-        $(":input").tooltip({ placement: 'left' });
-    });
-</script>
\ No newline at end of file
diff --git a/module/Application/view/application/intervenant/importer.phtml b/module/Application/view/application/intervenant/importer.phtml
deleted file mode 100644
index 5d168f91d6..0000000000
--- a/module/Application/view/application/intervenant/importer.phtml
+++ /dev/null
@@ -1,7 +0,0 @@
-<div class="jumbotron">
-    <h1>Intervenant importé : <?php echo $intervenant ?></h1>
-</div>
-
-<?php echo $this->intervenantDl($intervenant, true) ?>
-
-<?php //echo $this->navigation('navigation')->menuContextuel()->withTarget($intervenant->getId()) ?>
\ No newline at end of file
diff --git a/module/Application/view/application/intervenant/modifier.phtml b/module/Application/view/application/intervenant/modifier.phtml
deleted file mode 100644
index 463229ac80..0000000000
--- a/module/Application/view/application/intervenant/modifier.phtml
+++ /dev/null
@@ -1,29 +0,0 @@
-<div class="jumbotron">
-    <h1>Modification d'un intervenant</h1>
-</div>
-
-<?php $form->prepare(); ?>
-
-<?php echo $this->form()->openTag($form) ?> 
-<div class="row">
-    <div class="col-md-3">
-        <?php echo $this->formControlGroup($form->get('nomUsuel')); ?>
-        <?php echo $this->formControlGroup($form->get('nomPatronymique')); ?>
-        <?php echo $this->formControlGroup($form->get('prenom')); ?>
-        <?php echo $this->formControlGroup($form->get('civilite')); ?>
-        <?php echo $this->formControlGroup($form->get('email')); ?>
-    </div>
-    <div class="col-md-4">
-        <?php echo $this->formControlGroup($form->get('dateNaissance')->setDateSupActivated(false)); ?>
-        <?php echo $this->formControlGroup($form->get('depNaissanceCodeInsee')); ?>
-        <?php echo $this->formControlGroup($form->get('paysNaissanceCodeInsee')); ?>
-    </div>
-</div>
-<input class="btn btn-primary" type="submit" value="Enregistrer" name="submit">
-<?php echo $this->form()->closeTag() ?> 
-
-<script>
-    $(function() {
-        $(":input").tooltip();
-    });
-</script>
\ No newline at end of file
diff --git a/module/Common/src/Common/ORM/Event/Listeners/HistoriqueListener.php b/module/Common/src/Common/ORM/Event/Listeners/HistoriqueListener.php
index 1c237f220d..9dfeaf2388 100644
--- a/module/Common/src/Common/ORM/Event/Listeners/HistoriqueListener.php
+++ b/module/Common/src/Common/ORM/Event/Listeners/HistoriqueListener.php
@@ -2,7 +2,7 @@
 namespace Common\ORM\Event\Listeners;
 
 use Zend\ServiceManager\ServiceLocatorAwareInterface;
-use Zend\ServiceManager\ServiceLocatorInterface;
+use Zend\ServiceManager\ServiceLocatorAwareTrait;
 use Doctrine\ORM\Event\LifecycleEventArgs;
 use Doctrine\ORM\Event\PreUpdateEventArgs;
 use Doctrine\ORM\Events;
@@ -19,10 +19,7 @@ use Application\Entity\Db\ValiditeAwareInterface;
  */
 class HistoriqueListener implements EventSubscriber, ServiceLocatorAwareInterface
 {
-    /**
-     * @var ServiceLocatorInterface
-     */
-    protected $sl;
+    use ServiceLocatorAwareTrait;
     
     /**
      * @var mixed
@@ -60,17 +57,6 @@ class HistoriqueListener implements EventSubscriber, ServiceLocatorAwareInterfac
         
         $now = new \DateTime();
         
-        /**
-         * Validité
-         */
-        
-        // l'entité doit implémenter l'interface requise
-        if ($entity instanceof ValiditeAwareInterface) {
-            if (null === $entity->getValiditeDebut()) {
-                $entity->setValiditeDebut($now);
-            }
-        }
-        
         /**
          * Historique
          */
@@ -131,7 +117,7 @@ class HistoriqueListener implements EventSubscriber, ServiceLocatorAwareInterfac
     public function getIdentity()
     {
         if (null === $this->identity) {
-            $authenticationService = $this->sl->get('Zend\Authentication\AuthenticationService');
+            $authenticationService = $this->getServiceLocator()->get('Zend\Authentication\AuthenticationService');
             if ($authenticationService->hasIdentity()) {
                 $this->identity = $authenticationService->getIdentity();
             }
@@ -147,26 +133,4 @@ class HistoriqueListener implements EventSubscriber, ServiceLocatorAwareInterfac
     {
         return array(Events::prePersist, Events::preUpdate);
     }   
-    
-    /**
-     * Set service locator
-     *
-     * @param ServiceLocatorInterface $serviceLocator
-     */
-    public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
-    {
-        $this->sl = $serviceLocator;
-        
-        return $this;
-    }
-
-    /**
-     * Get service locator
-     *
-     * @return ServiceLocatorInterface
-     */
-    public function getServiceLocator()
-    {
-        return $this->sl;
-    }
 }
\ No newline at end of file
diff --git a/module/Common/src/Common/ORM/Filter/HistoriqueFilter.php b/module/Common/src/Common/ORM/Filter/HistoriqueFilter.php
index 10ba1537a4..ad3da746f7 100644
--- a/module/Common/src/Common/ORM/Filter/HistoriqueFilter.php
+++ b/module/Common/src/Common/ORM/Filter/HistoriqueFilter.php
@@ -8,11 +8,18 @@ use Doctrine\ORM\Query\Filter\SQLFilter;
 /**
  * Description of HistoriqueFilter
  *
- * @author Bertrand GAUTHIER <bertrand.gauthier at unicaen.fr>
+ * @author Laurent LÉCLUSE <laurent.lecluse at unicaen.fr>
  */
 class HistoriqueFilter extends SQLFilter
 {
-    protected $disabledEntities = [];
+    protected $enabledEntities = [];
+
+    /**
+     *
+     * @var \DateTime
+     */
+    protected $dateObservation = null;
+
 
     public function addFilterConstraint(ClassMetaData $targetEntity, $targetTableAlias)
     {
@@ -21,45 +28,91 @@ class HistoriqueFilter extends SQLFilter
             return "";
         }
 
-        if (isset($this->disabledEntities[$targetEntity->name])){
-            return "";
+        if (isset($this->enabledEntities[$targetEntity->name])){
+            if ($this->dateObservation){
+                $this->setParameter('date_observation', $this->dateObservation, \Doctrine\DBAL\Types\Type::DATETIME);
+                return '1 = OSE_DIVERS.COMPRISE_ENTRE('.$targetTableAlias.'.HISTO_CREATION,'.$targetTableAlias.'.HISTO_DESTRUCTION, '.$this->getParameter('date_observation').')';
+            }else{
+                return '1 = OSE_DIVERS.COMPRISE_ENTRE('.$targetTableAlias.'.HISTO_CREATION,'.$targetTableAlias.'.HISTO_DESTRUCTION)';
+            }
+        }else{
+            return '';
         }
+    }
+
+    /**
+     * 
+     * @return \DateTime
+     */
+    function getDateObservation()
+    {
+        return $this->dateObservation;
+    }
 
-        return "$targetTableAlias.HISTO_DESTRUCTION IS NULL AND $targetTableAlias.HISTO_DESTRUCTEUR_ID IS NULL";
+    /**
+     *
+     * @param \DateTime $dateObservation
+     * @return \Common\ORM\Filter\HistoriqueFilter
+     */
+    function setDateObservation(\DateTime $dateObservation=null)
+    {
+        $this->dateObservation = $dateObservation;
+        return $this;
     }
 
     /**
-     * Désactive le filtre pour une entité donnée
+     * Désactive le filtre pour une ou des entités données
      *
-     * @param string $entity
+     * @param string|string[] $entity
      * @return self
      */
     public function disableForEntity( $entity )
     {
-        $this->disabledEntities[$entity] = true;
+        if (is_array($entity)){
+            foreach($entity as $e){
+                unset($this->enabledEntities[$e]);
+            }
+        }else{
+            unset($this->enabledEntities[$entity]);
+        }
         return $this;
     }
 
     /**
-     * Réactive le filtre pour une entité donnée
+     * Active le filtre pour une ou des entités données
      *
-     * @param string $entity
+     * @param string|string[] $entity
      * @return self
      */
     public function enableForEntity($entity)
     {
-        unset($this->disabledEntities[$entity]);
+        if (is_array($entity)){
+            foreach($entity as $e){
+                $this->enabledEntities[$e] = true;
+            }
+        }else{
+            $this->enabledEntities[$entity] = true;
+        }
         return $this;
     }
 
     /**
-     * Réactive les filtres pour toutes les entités
-     *
+     * Initialisation rapide du filtre!!
+     * 
+     * @param string|string[] $entity
+     * @param \DateTime|null $dateObservation
      * @return self
      */
-    public function enableForAll()
+    public function init($entity, $dateObservation=null)
     {
-        $this->disabledEntities = [];
+        if ($entity){
+            $this->enableForEntity($entity);
+        }
+        if ($dateObservation){
+            $this->setDateObservation($dateObservation);
+        }else{
+            $this->setDateObservation();
+        }
         return $this;
     }
 }
\ No newline at end of file
-- 
GitLab