From 5aa124bc56539377058bc3017cdc59bd51adc3fd Mon Sep 17 00:00:00 2001
From: Sebastian Castro <sebastian.castro@protonmail.com>
Date: Wed, 25 Sep 2019 12:51:07 +0200
Subject: [PATCH] Fix handling the case where no categories exists bis

---
 .../Controller/Admin/ImportAdminController.php   |  9 +++++----
 .../EventListener/TaxonomyJsonGenerator.php      |  2 +-
 .../Resources/config/services.yml                |  4 +++-
 .../custom-fields/mapping-taxonomy.html.twig     | 11 +++++++++--
 .../Services/ElementImportMappingService.php     | 16 +++++++++++++---
 .../Services/ElementImportService.php            |  5 ++++-
 6 files changed, 35 insertions(+), 12 deletions(-)

diff --git a/src/Biopen/GeoDirectoryBundle/Controller/Admin/ImportAdminController.php b/src/Biopen/GeoDirectoryBundle/Controller/Admin/ImportAdminController.php
index a0ec7e895..f4c079ac6 100755
--- a/src/Biopen/GeoDirectoryBundle/Controller/Admin/ImportAdminController.php
+++ b/src/Biopen/GeoDirectoryBundle/Controller/Admin/ImportAdminController.php
@@ -39,7 +39,7 @@ class ImportAdminController extends Controller
     ]);
   }
 
-  public function refreshAction()
+  public function refreshAction(Request $request)
   {
     $object = $this->admin->getSubject();
 
@@ -55,9 +55,10 @@ class ImportAdminController extends Controller
     $em->persist($object);
     $em->flush();
 
-    $this->get('biopen.async')->callCommand('app:elements:importSource', [$object->getId()]);
-
-    // $result = $this->get('biopen.element_import')->startImport($object);
+    if ($request->get('direct'))
+      $result = $this->get('biopen.element_import')->startImport($object);
+    else
+      $this->get('biopen.async')->callCommand('app:elements:importSource', [$object->getId()]);
 
     $redirectionUrl = $this->admin->generateUrl('edit', ['id' => $object->getId()]);
     $stateUrl = $this->generateUrl('biopen_import_state', ['id' => $object->getId()]);
diff --git a/src/Biopen/GeoDirectoryBundle/EventListener/TaxonomyJsonGenerator.php b/src/Biopen/GeoDirectoryBundle/EventListener/TaxonomyJsonGenerator.php
index 229865d3d..8d35efc55 100755
--- a/src/Biopen/GeoDirectoryBundle/EventListener/TaxonomyJsonGenerator.php
+++ b/src/Biopen/GeoDirectoryBundle/EventListener/TaxonomyJsonGenerator.php
@@ -80,7 +80,7 @@ class TaxonomyJsonGenerator
     }
   }
 
-	private function updateTaxonomy($dm)
+	public function updateTaxonomy($dm)
 	{
     $taxonomy = $dm->getRepository('BiopenGeoDirectoryBundle:Taxonomy')->findTaxonomy();
 		if (!$taxonomy || $taxonomy->preventUpdate) return false;
diff --git a/src/Biopen/GeoDirectoryBundle/Resources/config/services.yml b/src/Biopen/GeoDirectoryBundle/Resources/config/services.yml
index 48348249d..25e63eb1b 100755
--- a/src/Biopen/GeoDirectoryBundle/Resources/config/services.yml
+++ b/src/Biopen/GeoDirectoryBundle/Resources/config/services.yml
@@ -65,6 +65,7 @@ services:
           - "@doctrine.odm.mongoDB.document_manager"
           - '@biopen.element_import_one'
           - "@biopen.element_import_mapping"
+          - "@biopen.taxonomy_json_generator"
 
     biopen.element_import_one:
        class: Biopen\GeoDirectoryBundle\Services\ElementImportOneService
@@ -75,7 +76,8 @@ services:
 
     biopen.element_import_mapping:
        class: Biopen\GeoDirectoryBundle\Services\ElementImportMappingService
-       arguments: ["@doctrine.odm.mongoDB.document_manager"]
+       arguments:
+          - "@doctrine.odm.mongoDB.document_manager"
 
     biopen.gogocartojs_service:
        class: Biopen\GeoDirectoryBundle\Services\GoGoCartoJsService
diff --git a/src/Biopen/GeoDirectoryBundle/Resources/views/admin/core_custom/custom-fields/mapping-taxonomy.html.twig b/src/Biopen/GeoDirectoryBundle/Resources/views/admin/core_custom/custom-fields/mapping-taxonomy.html.twig
index bba23727c..c16cc0fb4 100644
--- a/src/Biopen/GeoDirectoryBundle/Resources/views/admin/core_custom/custom-fields/mapping-taxonomy.html.twig
+++ b/src/Biopen/GeoDirectoryBundle/Resources/views/admin/core_custom/custom-fields/mapping-taxonomy.html.twig
@@ -17,7 +17,9 @@
         <tr>
           <td class="original">{{originName}}</td>
           <td>></td>
-          <td class="mapped"><input type="text" name="taxonomy[{{originName}}][]" class="form-control category-selector" value="{{mappedName|join(',')}}"/></td>
+          <td class="mapped">
+            <input type="text" name="taxonomy[{{originName}}][]" class="form-control category-selector" value="{{mappedName|join(',')}}"/>
+          </td>
           <td><i class="clear-icon fa fa-ban" title="Ne pas utiliser cette catégorie"></i></td>
         </tr>
       {% endfor %}
@@ -39,6 +41,7 @@
 
     function recursivelyAddOption(category, parentOption)
     {
+      if (!category.options) return;
       for(var i = 0; i < category.options.length; i++)
       {
         var option = category.options[i];
@@ -54,7 +57,6 @@
         }
       }
     }
-
     for(var k = 0; k < taxonomy.length; k++) recursivelyAddOption(taxonomy[k], null);
 
     $(".category-selector").select2({
@@ -62,6 +64,11 @@
         multiple: true
     });
 
+    // on init, if the category selector is empty that mean that the old mapped category does not exist anymore
+    $(".category-selector").each(function() {
+      if (!$(this).val()) $(this).siblings('input').val('/');
+    });
+
     $('.clear-icon').click(function() {
       $(this).parent().parent().find('.category-selector:not(.select2-container)').val("").trigger('change');
     });
diff --git a/src/Biopen/GeoDirectoryBundle/Services/ElementImportMappingService.php b/src/Biopen/GeoDirectoryBundle/Services/ElementImportMappingService.php
index e26ac9c0f..b42cb391d 100644
--- a/src/Biopen/GeoDirectoryBundle/Services/ElementImportMappingService.php
+++ b/src/Biopen/GeoDirectoryBundle/Services/ElementImportMappingService.php
@@ -127,6 +127,7 @@ class ElementImportMappingService
 
     $this->em->persist($import);
     $this->em->flush();
+
     return $data;
   }
 
@@ -189,9 +190,19 @@ class ElementImportMappingService
   public function collectTaxonomy($data, $import)
   {
     $taxonomyMapping = $import->getTaxonomyMapping();
+    // delete obsolte mapping (if an option have been deleted, but is still in the mapping)
+    $allOptionsIds = array_keys($this->em->createQueryBuilder('BiopenGeoDirectoryBundle:Option')->select('id')
+                                ->hydrate(false)->getQuery()->execute()->toArray());
+    foreach ($taxonomyMapping as $key => $value) {
+      $taxonomyMapping[$key] = array_filter($value, function($el) use ($allOptionsIds) {
+        return in_array($el, $allOptionsIds);
+      });
+      if (count($taxonomyMapping[$key]) == 0) unset($taxonomyMapping[$key]);
+    }
+    $import->setTaxonomyMapping($taxonomyMapping);
+
     $allNewCategories = [];
     $this->createOptionsMappingTable();
-
     foreach($data as $row)
     {
       if (isset($row['categories'])) {
@@ -215,7 +226,7 @@ class ElementImportMappingService
           }
           // create options for previously imported non mapped options
           if (array_key_exists($category, $taxonomyMapping)
-              && (!$taxonomyMapping[$category] || $taxonomyMapping[$category] == '/')
+              && (!$taxonomyMapping[$category] || $taxonomyMapping[$category] == '/' || $taxonomyMapping[$category] == '')
               && $this->createMissingOptions) {
             $taxonomyMapping[$category] = [$this->createOption($category)];
           }
@@ -359,7 +370,6 @@ class ElementImportMappingService
       $mainCategory->setName('Catégories Principales');
       $mainCategory->setPickingOptionText('Une catégorie principale');
       $this->em->persist($mainCategory);
-      $this->em->flush();
       $this->parentCategoryIdToCreateMissingOptions = $mainCategory->getId();
       $parent = $mainCategory;
     }
diff --git a/src/Biopen/GeoDirectoryBundle/Services/ElementImportService.php b/src/Biopen/GeoDirectoryBundle/Services/ElementImportService.php
index 696f79474..6ec245861 100755
--- a/src/Biopen/GeoDirectoryBundle/Services/ElementImportService.php
+++ b/src/Biopen/GeoDirectoryBundle/Services/ElementImportService.php
@@ -26,11 +26,12 @@ class ElementImportService
 	/**
     * Constructor
     */
-  public function __construct(DocumentManager $documentManager, $importOneService, $mappingService)
+  public function __construct(DocumentManager $documentManager, $importOneService, $mappingService, $taxonomyJsonGenerator)
   {
 		$this->em = $documentManager;
 		$this->importOneService = $importOneService;
 		$this->mappingService = $mappingService;
+    $this->taxonomyJsonGenerator = $taxonomyJsonGenerator;
   }
 
   public function startImport($import)
@@ -176,6 +177,8 @@ class ElementImportService
 
 		$this->em->flush();
 		$this->em->clear();
+
+    $this->taxonomyJsonGenerator->updateTaxonomy($this->em);
 		$import = $this->em->getRepository('BiopenGeoDirectoryBundle:Import')->find($import->getId());
 		$this->em->persist($import);
 
-- 
GitLab