From 667646bdb00855cf47ae09843c274a5ef9bab49b Mon Sep 17 00:00:00 2001
From: Sebastian Castro <sebastian.castro@protonmail.com>
Date: Wed, 20 Jan 2021 12:26:54 +0100
Subject: [PATCH] Make Import name unique and maintain integrity with sourceKey

---
 src/Document/Element.php                       |  2 +-
 src/Document/Import.php                        |  2 ++
 src/EventListener/DatabaseIntegrityWatcher.php | 16 ++++++++++++++++
 src/Services/ElementImportOneService.php       |  9 +++++----
 4 files changed, 24 insertions(+), 5 deletions(-)

diff --git a/src/Document/Element.php b/src/Document/Element.php
index 1694cc2fb..c095409b5 100644
--- a/src/Document/Element.php
+++ b/src/Document/Element.php
@@ -68,7 +68,7 @@ class Element
     /**
      * Main properties available on all elements
      */
-    const CORE_FIELDS = ['id', 'name', 'categories', 'streetAddress', 'addressLocality', 'postalCode', 'addressCountry', 'latitude', 'longitude', 'images', 'files', 'owner', 'source', 'openHours', 'email', 'customFormatedAddress'];
+    const CORE_FIELDS = ['id', 'name', 'categories', 'streetAddress', 'addressLocality', 'postalCode', 'addressCountry', 'latitude', 'longitude', 'images', 'files', 'owner', 'source', 'sourceKey', 'openHours', 'email', 'customFormatedAddress'];
 
     /**
      * @var int
diff --git a/src/Document/Import.php b/src/Document/Import.php
index 0a29dd906..f4d47c304 100644
--- a/src/Document/Import.php
+++ b/src/Document/Import.php
@@ -8,6 +8,7 @@ use Symfony\Component\HttpFoundation\File\File;
 use Symfony\Component\Validator\Constraints as Assert;
 use Symfony\Component\Validator\Context\ExecutionContextInterface;
 use Vich\UploaderBundle\Mapping\Annotation as Vich;
+use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique;
 
 abstract class ImportState
 {
@@ -28,6 +29,7 @@ abstract class ImportState
  * @MongoDB\InheritanceType("SINGLE_COLLECTION")
  * @MongoDB\DiscriminatorField("type")
  * @MongoDB\DiscriminatorMap({"normal"="Import", "dynamic"="ImportDynamic"})
+ * @Unique(fields="sourceName")
  */
 class Import extends AbstractFile
 {
diff --git a/src/EventListener/DatabaseIntegrityWatcher.php b/src/EventListener/DatabaseIntegrityWatcher.php
index 9f4d3f4a2..a48b5d627 100755
--- a/src/EventListener/DatabaseIntegrityWatcher.php
+++ b/src/EventListener/DatabaseIntegrityWatcher.php
@@ -126,6 +126,22 @@ class DatabaseIntegrityWatcher
                 }
             }
         }
+        if ($document instanceof ImportDynamic) {
+            $changeset = $dm->getChangeSet($document);
+            if (array_key_exists('sourceName', $changeset)) {
+                $dm->query('Element')->updateMany()                
+                                 ->field('sourceKey')->set($changeset['sourceName'][1])
+                                 ->field('source')->references($document)
+                                 ->execute();
+                $elementIds = $dm->query('Element')
+                                 ->field('source')->references($document)
+                                 ->getIds();
+                if (count($elementIds)) {
+                    $elementIdsString = '"'.implode(',', $elementIds).'"';
+                    $this->asyncService->callCommand('app:elements:updateJson', ['ids' => $elementIdsString]);
+                }
+            }
+        }
     }
 
     public function preFlush(\Doctrine\ODM\MongoDB\Event\PreFlushEventArgs $eventArgs)
diff --git a/src/Services/ElementImportOneService.php b/src/Services/ElementImportOneService.php
index db5d0a552..1de97329a 100755
--- a/src/Services/ElementImportOneService.php
+++ b/src/Services/ElementImportOneService.php
@@ -132,8 +132,9 @@ class ElementImportOneService
         $address = new PostalAddress($row['streetAddress'], $row['addressLocality'], $row['postalCode'], $row['addressCountry'], $row['customFormatedAddress']);
         $element->setAddress($address);
 
-        $defaultSourceName = $import ? $import->getSourceName() : 'Inconnu';
-        $element->setSourceKey((strlen($row['source']) > 0 && 'Inconnu' != $row['source']) ? $row['source'] : $defaultSourceName);
+        $sourceKey = $import ? $import->getSourceName() : 'Inconnu';
+        if (!$import->isDynamicImport() && (strlen($row['source']) > 0 && 'Inconnu' != $row['source'])) $sourceKey = $row['source'];
+        $element->setSourceKey($sourceKey);
         $element->setSource($import);
 
         if (array_key_exists('owner', $row)) {
@@ -183,10 +184,10 @@ class ElementImportOneService
         } else {
             if ($updateExisting) {
                 // create edit contribution
-                $contribution = $this->interactionService->createContribution($element, null, 1, $element->getStatus());
+                $this->interactionService->createContribution($element, null, 1, $element->getStatus());
             } else {
                 // create import contribution if first time imported
-                $contribution = $this->interactionService->createContribution($element, null, 0, $element->getStatus());
+                $this->interactionService->createContribution($element, null, 0, $element->getStatus());
             }
         }
 
-- 
GitLab