From 876d651e42e82e22b68a4c270a024b975d77f024 Mon Sep 17 00:00:00 2001
From: dcz <dcz@ipipan.waw.pl>
Date: Tue, 5 Sep 2023 11:16:05 +0200
Subject: [PATCH] attach free lu to unified_frame

---
 entries/urls.py                               |  4 +-
 entries/views.py                              | 16 +++++
 .../Unification/LexicalUnitEdit.vue           | 67 ++++++++++++++-----
 shellvalier/settings.py                       |  2 +
 unifier/urls.py                               |  2 +
 unifier/views.py                              | 47 +++++++++++++
 6 files changed, 120 insertions(+), 18 deletions(-)

diff --git a/entries/urls.py b/entries/urls.py
index d440adb..445b935 100644
--- a/entries/urls.py
+++ b/entries/urls.py
@@ -2,7 +2,7 @@ from django.urls import path
 
 from . import autocompletes, views
 from .views import ajax_plWN_context_lookup, ajax_predefined_preferences, ajax_relations, ajax_synsets, ajax_roles, \
-    ajax_role_attributes, ajax_role_sub_attributes
+    ajax_role_attributes, ajax_role_sub_attributes, ajax_free_slowal_frame_lookup
 
 app_name = 'entries'
 
@@ -29,6 +29,8 @@ urlpatterns = [
     path('relations/', ajax_relations, name='relations'),
     path('synsets/', ajax_synsets, name='synsets'),
 
+    path('free_slowal_frame_lookup/', ajax_free_slowal_frame_lookup, name='free_slowal_frame_lookup'),
+
     # TODO remove!
     #path('test/', views.test, name='test'),
     path('', views.entries, name='entries'),
diff --git a/entries/views.py b/entries/views.py
index de61bf4..cef9e17 100644
--- a/entries/views.py
+++ b/entries/views.py
@@ -1095,3 +1095,19 @@ def ajax_synsets(request, base, pos):
 
     return context
 
+
+@ajax(method='get', encode_result=True)
+def ajax_free_slowal_frame_lookup(request, term):
+    results = []
+    if len(term) > 0:
+        obj_results = LexicalUnit.objects.filter(base__startswith=term).filter(frames__assignments=None)
+        results = get_ordered_lexical_units_synsets(obj_results)
+    return {'result': results}
+
+
+def get_ordered_lexical_units_synsets(lexical_units_query):
+    lexical_unit_bases = []
+    ordered_lexical_units = lexical_units_query.order_by('base', 'sense')
+    for lexical_unit in ordered_lexical_units:
+        lexical_unit_bases.append(str(lexical_unit))
+    return lexical_unit_bases
diff --git a/frontend/src/components/unification/Unification/LexicalUnitEdit.vue b/frontend/src/components/unification/Unification/LexicalUnitEdit.vue
index f67c273..d68e686 100644
--- a/frontend/src/components/unification/Unification/LexicalUnitEdit.vue
+++ b/frontend/src/components/unification/Unification/LexicalUnitEdit.vue
@@ -687,23 +687,6 @@ Object.assign(LexicalUnitEdit, {
                   show_error(errorType + ' (' + errorMessage + ')');
                   alert(gettext("Status ramy niew został zmieniony. Błąd: "+errorType + ' (' + errorMessage + ')'));
                 })
-        // $.ajax({
-        //   type: 'post',
-        //   url: '/' + lang + '/unifier/change_slowal_frame_status/',
-        //   dataType: 'json',
-        //   data: data,
-        //   timeout: 60000,
-        //   success: function (response) {
-        //     show_info('Status ramy został zmieniony');
-        //     alert(gettext("Status ramy został zmieniony."));
-        //     this.$emit('refreshEntriesList');
-        //     this.loadFrame();
-        //   }.bind(this),
-        //   error: function (request, errorType, errorMessage) {
-        //     show_error(errorType + ' (' + errorMessage + ')');
-        //     alert(gettext("Status ramy niew został zmieniony. Błąd: "+errorType + ' (' + errorMessage + ')'));
-        //   }
-        // });
       });
     },
     slowal_frame_ready_rollback(status) {
@@ -963,6 +946,55 @@ Object.assign(LexicalUnitEdit, {
     },
     showSelectionalPreferencies() {
       this.selectionalPreferenciesVisible = true;
+    },
+    attachSlowalFrame() {
+      const attach_slowal_frame_popup = {
+        state0: {
+          title: 'Podpinanie dodatkowej ramy',
+          html: "<input id='slowal_frame_selection' type='text' name='context'>",
+          buttons: {Anuluj: 0, Zapisz: 1},
+          focus: -1,
+          submit: function (e, v, m, f) {
+            if (v == 0) {
+              $.prompt.close();
+            }
+            if (v === 1) {
+              e.preventDefault();
+              const lu_base = f.context;
+
+              send_post_request('/unifier/attach_lu_to_unified_frame/',
+                      {'lu_base': lu_base,
+                            'unified_frame_id': this.unified_frame.id},
+                      (reponse) => {
+                        show_info('Rama została podpięta.');
+                        alert(gettext("Rama została podpięta."));
+                        this.$emit('refreshEntriesList');
+                        this.loadFrame();
+                        $.prompt.close();
+                      },
+                      (request, errorType, errorMessage) => {
+                        show_error(errorType + ' (' + errorMessage + ')');
+                        alert(gettext("Status ramy niew został zmieniony. Błąd: "+errorType + ' (' + errorMessage + ')'));
+                        $.prompt.close();
+                      })
+            }
+          }.bind(this)
+        }
+      }
+      $.prompt(attach_slowal_frame_popup);
+      $('#slowal_frame_selection').autocomplete({
+        select: function (event, ui) {
+        },
+        source: function (req, add) {
+          fetch(`/${lang}/entries/free_slowal_frame_lookup/?` + new URLSearchParams(req))
+                  .then(function (response) {
+                    return response.json();
+                  })
+                  .then(function (data) {
+                    add(data['result']);
+                  });
+        },
+      });
     }
   },
   mounted() {
@@ -1142,6 +1174,7 @@ export default LexicalUnitEdit;
             <td id="wrong-frame" style="padding: 10px 15px 10px 15px; color: #000000;" @click="change_slowal_frame_status('B')">Błędna</td>
             <td id="hide-slowal-frame" style="padding: 10px 15px 10px 15px; color: #000000;"  @click="changeShowVerifiedFrames(false)">Ukryj gotowe {{showVerifiedFrames ? '' : getSlowalReadyFrameCnt() > 0 ? '(ukrytych: ' + getSlowalReadyFrameCnt() + ')' : ''}}</td>
             <td id="ready-slowal-frame" style="padding: 10px 15px 10px 15px; color: #000000;" @click="slowal_frame_ready_rollback">{{ statusButtonTitle }}</td>
+            <td id="attach-slowal-frame" style="padding: 10px 15px 10px 15px; color: #000000;" @click="attachSlowalFrame">Podepnij</td>
           </tr>
           <tr style="background-color: white;">
             <td id="inccorect-slowal-frame" style="padding: 10px 15px 10px 15px; color: #000000;" @click="change_slowal_frame_status('C')">
diff --git a/shellvalier/settings.py b/shellvalier/settings.py
index 54bb686..8ea5d4c 100644
--- a/shellvalier/settings.py
+++ b/shellvalier/settings.py
@@ -194,3 +194,5 @@ UNIFIED_FRAME_SERVICE_URL = get_environment('UNIFIED_FRAME_SERVICE_URL',
                                             default='http://127.0.0.1:8000/en/unifier/build_unified_frame_xml/?frame_id=')
 SLOWAL_FRAME_REMOVE_SERVICE_URL = get_environment('SLOWAL_FRAME_REMOVE_SERVICE_URL',
                                                   default='http://walentygroupies.ipipan.waw.pl/ajax/frame_statuses_free/?unifier_frame_ids=')
+SLOWAL_FRAME_TAKE_SERVICE_URL = get_environment('SLOWAL_FRAME_TAKE_SERVICE_URL',
+                                                  default='http://walentygroupies.ipipan.waw.pl/ajax/frame_statuses_take/?unifier_frame_ids=')
diff --git a/unifier/urls.py b/unifier/urls.py
index d0c7885..a04cda7 100644
--- a/unifier/urls.py
+++ b/unifier/urls.py
@@ -32,4 +32,6 @@ urlpatterns = [
     path('get_hierarchy_hyperonyms/<int:unified_frame_id>/', views.get_hierarchy_hyperonyms, name='get_hierarchy_hyperonyms'),
 
     path('check_unified_frame_title_uniq/', views.check_unified_frame_title_uniq, name='check_unified_frame_title_uniq'),
+
+    path('attach_lu_to_unified_frame/', views.attach_lu_to_unified_frame, name='attach_lu_to_unified_frame'),
 ]
diff --git a/unifier/views.py b/unifier/views.py
index 417afec..7598753 100644
--- a/unifier/views.py
+++ b/unifier/views.py
@@ -829,3 +829,50 @@ def get_hierarchy_hyperonyms(request, unified_frame_id):
     }
 
     return JsonResponse(res)
+
+
+@ajax_required
+@transaction.atomic
+def attach_lu_to_unified_frame(request):
+    if request.method == 'POST':
+        unified_frame_id = request.POST['unified_frame_id']
+        lu_base_sense = request.POST['lu_base']
+        lu_base_sense_split = lu_base_sense.split('-')
+        lu_base = lu_base_sense_split[0]
+        lu_sense = lu_base_sense_split[1]
+
+        unified_frame = UnifiedFrame.objects.get(pk=unified_frame_id)
+        lu = LexicalUnit.objects.get(base=lu_base, sense=lu_sense)
+        frames = list(lu.frames.all())
+        for frame in frames:
+
+            frame.status = FrameStatus.PROCESSING
+            Assignment.assign(user=request.user, subject=frame)
+            frame.save()
+
+            mapping = UnifiedFrame2SlowalFrameMapping(unified_frame=unified_frame, slowal_frame=frame)
+            UnifiedFrame2SlowalFrameMapping.save(mapping)
+
+            slowal_frame_arguments = list(frame.arguments.all())
+            unified_frame_arguments = list(unified_frame.unified_arguments.all())
+            slowal_frame_argument_cnt = len(slowal_frame_arguments)
+            for ind in range(slowal_frame_argument_cnt):
+                if ind >= len(unified_frame_arguments):
+                    # create additional argument in unified frame
+                    unified_frame_argument = UnifiedFrameArgument(unified_frame=unified_frame)
+                    UnifiedFrameArgument.save(unified_frame_argument)
+                else:
+                    unified_frame_argument = unified_frame_arguments[ind]
+
+                unified_frame_argument_slowal_frame_mapping = \
+                    UnifiedFrameArgumentSlowalFrameMapping(unified_frame_mapping=mapping,
+                                                           unified_agrument=unified_frame_argument,
+                                                           slowal_agrument=slowal_frame_arguments[ind])
+                UnifiedFrameArgumentSlowalFrameMapping.save(unified_frame_argument_slowal_frame_mapping)
+
+        for frame in frames:
+            http = urllib3.PoolManager()
+            r = http.request('GET', settings.SLOWAL_FRAME_TAKE_SERVICE_URL + str(frame.id))
+
+        return JsonResponse({})
+    return JsonResponse({})
-- 
GitLab