From 77b0c72054df14679b3422611e45a7aa69af9dfe Mon Sep 17 00:00:00 2001
From: pfleu <fleutotp@gmail.com>
Date: Mon, 12 Jun 2023 11:07:28 +0200
Subject: [PATCH] =?UTF-8?q?Page=20Lexique:=20proposition=20d'ajout=20d'un?=
 =?UTF-8?q?=20mot=20recherch=C3=A9=20si=20non=20pr=C3=A9sent?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 public/assets/js/app.js                   |  1 +
 src/Controller/HeadwordController.php     |  7 ++-
 src/Controller/LexiconController.php      | 45 +++++++++++++++++++
 src/Entity/Lexicon.php                    | 15 +++++++
 src/EventListener/SecuritySubscriber.php  |  2 +-
 templates/closeModalAndRedirect.html.twig |  9 ++++
 templates/lexicon/show.html.twig          | 54 +++++++++++++++--------
 templates/nav.html.twig                   |  4 +-
 8 files changed, 114 insertions(+), 23 deletions(-)
 create mode 100644 templates/closeModalAndRedirect.html.twig

diff --git a/public/assets/js/app.js b/public/assets/js/app.js
index d11aea0..b10fb9d 100644
--- a/public/assets/js/app.js
+++ b/public/assets/js/app.js
@@ -391,6 +391,7 @@ function initializeAjaxLinks() {
     })
 }
 
+// Barre de recherche : on cherche le mot en ajax. Si on le trouve dans le wiko, on l'importe et on redirige vers lexique zéro, sinon on ouvre la modale de confirmation d'ajout
 function initializeSearchHeadwords() {
     $form = $('#searchHeadwordsForm');
     $form.on('submit', function (e) {
diff --git a/src/Controller/HeadwordController.php b/src/Controller/HeadwordController.php
index 1ce53ab..639e037 100644
--- a/src/Controller/HeadwordController.php
+++ b/src/Controller/HeadwordController.php
@@ -39,6 +39,8 @@ class HeadwordController extends AppBaseController
 
     /**
      * @Route("/search", name="app_headword_search")
+     *
+     * Barre de recherche : on cherche le mot en ajax. Si on le trouve dans le wiko, on l'importe et on redirige vers lexique zéro, sinon on ouvre la modale de confirmation d'ajout
      */
     public function search(Request $request, WiktionaryManager $wiktionaryManager): Response
     {
@@ -61,8 +63,8 @@ class HeadwordController extends AppBaseController
             return new JsonResponse($this->generateUrl('app_entry_show', ['id' => $entry->getId()]), 211);
 
         } else {
-            return  $this->render("headword/confirmAddNewWord.html.twig", ['word' => $search]);
-        }
+        return  $this->render("headword/confirmAddNewWord.html.twig", ['word' => $search]);
+    }
     }
 
     /**
@@ -73,6 +75,7 @@ class HeadwordController extends AppBaseController
         $word = $request->get('word');
         $headword = $this->newHeadword($word, $this->getLanguage());
         $this->createEntryInNewWordsLexicon($headword);
+        $this->em->flush();
 
         $this->addFlash('success', sprintf("Le mot « %s » a été ajouté à l'Agora Des Néologismes.", $word));
 
diff --git a/src/Controller/LexiconController.php b/src/Controller/LexiconController.php
index 5b308df..8ed7287 100644
--- a/src/Controller/LexiconController.php
+++ b/src/Controller/LexiconController.php
@@ -3,17 +3,20 @@
 namespace App\Controller;
 
 use App\Entity\Entry;
+use App\Entity\Headword;
 use App\Entity\Label;
 use App\Entity\Lexicon;
 use App\Entity\Log;
 use App\Form\CopyEntriesType;
 use App\Form\SearchStringType;
 use App\Manager\LabelManager;
+use App\Manager\WiktionaryManager;
 use App\Repository\EntryRepository;
 use App\Repository\LexiconRepository;
 use Doctrine\Persistence\ManagerRegistry;
 use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
 use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
+use Symfony\Component\HttpFoundation\JsonResponse;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 use Symfony\Component\Routing\Annotation\Route;
@@ -70,12 +73,22 @@ class LexiconController extends AppBaseController
 //        $entriesWithAddingOrderIndex = $entriesOrdered;
 //        usort($entriesWithAddingOrderIndex, function ($a, $b) { return $b->getCreatedAt()->getTimestamp() - $a->getCreatedAt()->getTimestamp(); });
 
+        // Si recherche de mot et aucun résultat, on propose l'ajout du mot au lexique
+        if ($form->get('searchString')->getData() && count($entries) === 0) {
+            $wordToAdd = $form->get('searchString')->getData();
+            if ($this->getNewWordsLexicon($lexicon->getLanguage())->getEntryForWord($wordToAdd)) {
+                $this->addFlash('warning', "Ce mot est présent dans l'Agora des Néologisme et ne peut pas être ajouté au lexique pour l'instant");
+                $wordToAdd = null;
+            }
+        }
+
         return $this->render('lexicon/show.html.twig', [
             'entries'           => $entriesIndexedById,
             'lexicon'           => $lexicon,
             'form'              => $form->createView(),
             'sortingColumn'     => $sortingColumn,
             'sortingOrder'      => $sortingOrder,
+            'wordToAdd'         => $wordToAdd ?? null,
         ]);
     }
     /**
@@ -215,4 +228,36 @@ class LexiconController extends AppBaseController
         ]);
     }
 
+    /**
+     * @Route("/{id}/add-word", name="app_lexicon_add_word")
+     *
+     * Barre de recherche : on cherche le mot en ajax. Si on le trouve dans le wiko, on l'importe et on recharge la page, sinon on ouvre la modale de confirmation d'ajout
+     */
+    public function addWord(Request $request, Lexicon $lexicon, WiktionaryManager $wiktionaryManager): Response
+    {
+        $search = trim($request->get('wordToAdd'));
+
+        $headword = $this->em->getRepository(Headword::class)->getFirstByGraphyValueAndLanguage($search, $lexicon->getLanguage());
+
+        // Si pas trouvé, on ajout le mot depuis le wiko si possible
+        if (!$headword && $wiktionaryManager->search($search, $lexicon->getLanguage())) {
+            $headword = $this->newHeadword($search, $lexicon->getLanguage());
+            $this->addFlash('success', "« " . $search . " » a été ajouté à Balex depuis le wiktionnaire");
+
+        }
+
+        // On ajoute le mot au lexique s'il existe
+        if ($headword) {
+            $this->createEntryInLexicon($headword, $lexicon);
+            $this->em->flush();
+            $this->addFlash('success', "Le mot a été ajouté au lexique");
+
+            return $this->render('closeModalAndReload.html.twig');
+            
+        // Sinon on propose de l'ajouter à l'Agora
+        } else {
+            return  $this->render("headword/confirmAddNewWord.html.twig", ['word' => $search]);
+        }
+    }
+
 }
diff --git a/src/Entity/Lexicon.php b/src/Entity/Lexicon.php
index 204bb4b..50435c5 100644
--- a/src/Entity/Lexicon.php
+++ b/src/Entity/Lexicon.php
@@ -221,6 +221,21 @@ class Lexicon
         return null;
     }
 
+    /**
+     * @param $string string
+     * @return Entry|mixed|null
+     */
+    public function getEntryForWord($string)
+    {
+        $word = strtolower(trim($string));
+        foreach ($this->getEntries() as $entry) {
+            if ($entry->getHeadword()->getValue() == $word) {
+                return $entry;
+            }
+        }
+        return null;
+    }
+
     public function getId(): ?int
     {
         return $this->id;
diff --git a/src/EventListener/SecuritySubscriber.php b/src/EventListener/SecuritySubscriber.php
index d8f20c1..c043cd0 100644
--- a/src/EventListener/SecuritySubscriber.php
+++ b/src/EventListener/SecuritySubscriber.php
@@ -40,7 +40,7 @@ class SecuritySubscriber implements EventSubscriberInterface
     {
         $user = $event->getAuthenticationToken()->getUser();
         if ($user instanceof User) {
-            $user->setLoginDate(new \DateTime());
+            $user->setLoggedAt(new \DateTimeImmutable());
 
             $this->em->persist($user);
             $this->em->flush();
diff --git a/templates/closeModalAndRedirect.html.twig b/templates/closeModalAndRedirect.html.twig
new file mode 100644
index 0000000..3751110
--- /dev/null
+++ b/templates/closeModalAndRedirect.html.twig
@@ -0,0 +1,9 @@
+<script type="text/javascript">
+    {% if url|default(null) %}
+    window.location.replace("{{ url|raw }}");
+    {% else %}
+    location.reload();
+    {% endif %}
+    $('#bootstrap-modal').modal('hide');
+</script>
+
diff --git a/templates/lexicon/show.html.twig b/templates/lexicon/show.html.twig
index cb3e325..bf6d777 100644
--- a/templates/lexicon/show.html.twig
+++ b/templates/lexicon/show.html.twig
@@ -8,25 +8,41 @@
 
     <div class="row justify-content-center m-lg-5 m-sm-3">
         <div class="col-md-12">
-{#            <h1 class="">#}
-{#                {{ lexicon|badgeXl }} {{ "Lexique"|trans }} {{ lexicon|capitalize }}#}
-{#            </h1>#}
-
-{#            <div class="row mt-4">#}
-{#                <div class="col-sm-3">#}
-{#                    {{ form_start(form) }}#}
-{#                    <div class="d-flex justify-content-between">#}
-{#                        {{ form_widget(form.searchString) }}#}
-{#                        <button type="submit" title="{{ "Filtrer"|trans }}" class="btn btn-block btn-dark" style="margin-left: 10px">#}
-{#                            <i class="fa fa-search"></i>#}
-{#                        </button>#}
-{#                        <a href="{{ path('app_lexicon_show', {id: lexicon.id}) }}" title="{{ "Réinitialiser"|trans }}" class="btn btn-block btn-light" style="margin-left: 10px">#}
-{#                            <i class="fa fa-times"></i>#}
-{#                        </a>#}
-{#                    </div>#}
-{#                    {{ form_end(form) }}#}
-{#                </div>#}
-{#            </div>#}
+            <h1 class="">
+                {{ lexicon|badgeXl }} {{ "Lexique"|trans }} {{ lexicon|capitalize }}
+            </h1>
+
+            <div class="row mt-4">
+                <div class="col-sm-3">
+                    {{ form_start(form) }}
+                    <div class="d-flex justify-content-between">
+                        {{ form_widget(form.searchString) }}
+                        <button type="submit" title="{{ "Filtrer"|trans }}" class="btn btn-block btn-dark" style="margin-left: 10px">
+                            <i class="fa fa-search"></i>
+                        </button>
+                        <a href="{{ path('app_lexicon_show', {id: lexicon.id}) }}" title="{{ "Réinitialiser"|trans }}" class="btn btn-block btn-light" style="margin-left: 10px">
+                            <i class="fa fa-times"></i>
+                        </a>
+                    </div>
+                    {{ form_end(form) }}
+                </div>
+            </div>
+
+            <div class="row mt-2">
+                <div class="col-md-12">
+                    {% if wordToAdd %}
+                        <div class="alert alert-warning alert-dismissible text-center">
+                            {{ "Ce mot n'est pas présent dans le lexique, voulez-vous l'ajouter ?"|trans }}
+                            <br>
+                            <a title="Ajouter ce mot au lexique" href="#" data-url="{{ path('app_lexicon_add_word', {id: lexicon.id, wordToAdd: wordToAdd}) }}" class="modal-show btn btn-dark btn-xs"><i class="fa fa-plus"></i> Ajouter</a>
+                            <button type="button" class="btn btn-light btn-xs" data-bs-dismiss="alert" aria-label="Close">
+                                <i class="fa fa-times"></i> {{ "Fermer"|trans }}
+                            </button>
+                        </div>
+                    {% endif %}
+                </div>
+            </div>
+
 
             <div class="row mt-4">
 
diff --git a/templates/nav.html.twig b/templates/nav.html.twig
index ad64727..dd15320 100644
--- a/templates/nav.html.twig
+++ b/templates/nav.html.twig
@@ -96,7 +96,9 @@
 
         </div>
 
-        {% include "notifications.html.twig" %}
+        {% if app.user %}
+            {% include "notifications.html.twig" %}
+        {% endif %}
 
     </div>
 </nav>
\ No newline at end of file
-- 
GitLab