From 0d514882b10859587eb6fd61cfc5bb48a09d22e0 Mon Sep 17 00:00:00 2001
From: dcz <dcz@ipipan.waw.pl>
Date: Fri, 3 Nov 2023 12:58:33 +0100
Subject: [PATCH] Remove argument. Example connection bugfix.

---
 entries/views.py                              |  5 +-
 freelus/urls.py                               |  1 +
 freelus/views.py                              | 66 +++++++++++++------
 .../unification/free_lu/FreeLuEdit.vue        | 46 ++++++++++---
 .../SemanticsSchemataComponent.vue            |  4 +-
 5 files changed, 91 insertions(+), 31 deletions(-)

diff --git a/entries/views.py b/entries/views.py
index 2f0a797..f81b03f 100644
--- a/entries/views.py
+++ b/entries/views.py
@@ -763,10 +763,13 @@ def get_examples(entry):
             if connection.lexical_unit:
                 lu_ids.add(connection.lexical_unit.id)
             for hook in connection.schema_connections.all():
-                schema_ids.add(hook.schema.id);
+                schema_ids.add(hook.schema.id)
                 phrases.add('{}-{}-{}-{}'.format(hook.schema.id, hook.position.id, hook.phrase_type.id, hook.alternation - 1))
                 phrases_syntax.add('{}-{}-{}'.format(hook.schema.id, hook.position.id, hook.phrase_type.id))
                 positions.add('{}-{}'.format(hook.schema.id, hook.position.id))
+                for argument_connection in hook.argument_connections.all():
+                    frame_ids.add(argument_connection.argument.frame.id)
+                    argument_ids.add('{}-{}'.format(argument_connection.argument.frame.id, argument_connection.argument.id))
         examples.append({
             'id'             : str(example.id),
             'sentence'       : example.sentence,
diff --git a/freelus/urls.py b/freelus/urls.py
index d7de51e..81308e4 100644
--- a/freelus/urls.py
+++ b/freelus/urls.py
@@ -13,5 +13,6 @@ urlpatterns = [
     path('delete_schema_to_argument_connection/', views.delete_schema_to_argument_connection,
          name='delete_schema_to_argument_connection'),
     path('finish_frame_processing/', views.finish_frame_processing, name='finish_frame_processing'),
+    path('remove_argument_from_frame/', views.remove_argument_from_frame, name='remove_argument_from_frame'),
 
 ]
diff --git a/freelus/views.py b/freelus/views.py
index c47b6f4..509bc14 100644
--- a/freelus/views.py
+++ b/freelus/views.py
@@ -4,6 +4,7 @@ from django.http import JsonResponse
 
 from common.decorators import ajax_required
 from connections.models import Entry, Status, ExampleConnection, SchemaHook, ArgumentConnection, RealisationDescription
+from examples.models import Example
 from meanings.models import LexicalUnit
 from semantics.models import Frame, FrameOpinion, Argument, ArgumentRole, SemanticRole, \
     RoleAttribute, RoleSubAttribute, RoleType
@@ -83,6 +84,28 @@ def add_argument_to_frame(request):
     return JsonResponse({})
 
 
+@ajax_required
+@transaction.atomic
+def remove_argument_from_frame(request):
+    """
+    Removing argument from the specified slowal frame in building process.
+    The request has to contain 'argument_id'.
+    :param request: http request
+    :return: Empty json response
+    """
+    if request.method == 'POST':
+        # frame_id = request.POST['frame_id']
+        argument_id = request.POST['argument_id']
+        # frame = Frame.objects.get(id=frame_id)
+
+        ArgumentConnection.objects.filter(argument_id=argument_id).delete()
+        Argument.objects.get(id=argument_id).delete()
+
+        return JsonResponse({})
+
+    return JsonResponse({})
+
+
 @ajax_required
 @transaction.atomic
 def change_role(request):
@@ -124,28 +147,24 @@ def change_role_base(frame_argument, request):
 @transaction.atomic
 def attach_examples_to_frame(request):
     """
-    Attaching selected examples to the slowal frame in building process.
-    The request has to contain 'frame_id' and 'argument_id' that represents slowal frame in building process.
+    Attaching selected examples to the lus.
+    The request has to contain 'selected_lus' that represents lu ids.
     List of example ids ('example_ids') is also required.
     :param request: http request
     :return: Empty json response
     """
     if request.method == 'POST':
-        frame_id = request.POST['frame_id']
-        argument_id = request.POST['argument_id']
         example_ids = json.loads(request.POST['example_ids'])
+        selected_lus = json.loads(request.POST['selected_lus'])
 
-        argument = Argument.objects.get(id=argument_id)
-        frame = Frame.objects.get(id=frame_id)
-
-        lexical_units = frame.lexical_units.all()
+        lexical_units = LexicalUnit.objects.filter(id__in=selected_lus).all()
+        for lexical_unit in lexical_units:
+            ExampleConnection.objects.filter(lexical_unit=lexical_unit).delete()
 
         for example_id in example_ids:
             for lexical_unit in lexical_units:
                 example_conn = ExampleConnection(example_id=example_id, lexical_unit=lexical_unit)
                 example_conn.save()
-                example_conn.arguments.add(argument)
-                example_conn.save()
 
     return JsonResponse({})
 
@@ -175,17 +194,20 @@ def attach_schema_to_argument(request):
                 schema_hooks = SchemaHook.objects.filter(subentry_id=subentry_id, schema_id=schema_id,
                                                              position_id=schema_position_id, phrase_type=phrase_type,
                                                              alternation=schema_alternation_id)
-                if schema_hooks.count() > 0:
-                    schema_hook = schema_hooks[0]
-                else:
-                    schema_hook = SchemaHook.objects.create(subentry_id=subentry_id, schema_id=schema_id,
+                if not schema_hooks.exists():
+                    schema_hooks = [SchemaHook.objects.create(subentry_id=subentry_id, schema_id=schema_id,
                                                              position_id=schema_position_id, phrase_type=phrase_type,
-                                                             alternation=schema_alternation_id)
+                                                             alternation=schema_alternation_id)]
+
+                # examples = Example.objects.filter(example_connections__schema_connections__in=schema_hooks)
+                # for example in examples:
+                #     ExampleConnection.objects.get_or_create(example=example, argument=argument, schema_hook)
 
                 argument_connection, _ = ArgumentConnection.objects.get_or_create(argument=argument,
                                                                                     defaults={'argument': argument})
                 argument_connection.save()
-                argument_connection.schema_connections.add(schema_hook)
+                for schema_hook in schema_hooks:
+                    argument_connection.schema_connections.add(schema_hook)
                 argument_connection.save()
 
                 RealisationDescription.objects.get_or_create(frame_id=frame_id,
@@ -211,14 +233,18 @@ def delete_schema_to_argument_connection(request):
     if request.method == 'POST':
         argument_id = request.POST['argument_id']
         schema_id = request.POST['schema_id']
+        subentry_id = request.POST['subentry_id']
         schema_position_id = request.POST['schema_position_id']
+        schema_alternation_id = request.POST['schema_alternation_id']
 
         argument = Argument.objects.get(id=argument_id)
-
-        schema_hooks = SchemaHook.objects.filter(schema_id=schema_id, position=schema_position_id)
-
         argument_connection = ArgumentConnection.objects.get(argument=argument)
-        argument_connection.schema_connections.remove(schema_hooks[0])
+
+        schema_hooks = SchemaHook.objects.filter(subentry_id=subentry_id, schema_id=schema_id,
+                                                 position_id=schema_position_id,
+                                                 alternation=schema_alternation_id)
+        for schema_hook in schema_hooks.all():
+            argument_connection.schema_connections.remove(schema_hook)
         argument_connection.save()
 
     return JsonResponse({})
diff --git a/frontend/src/components/unification/free_lu/FreeLuEdit.vue b/frontend/src/components/unification/free_lu/FreeLuEdit.vue
index e47ee85..11370d4 100644
--- a/frontend/src/components/unification/free_lu/FreeLuEdit.vue
+++ b/frontend/src/components/unification/free_lu/FreeLuEdit.vue
@@ -132,7 +132,7 @@
             selectSchemaPositionSelected(selected_schemata_position_id, subentry, alternation_id) {
                 this.selected_schemata_position_id = selected_schemata_position_id;
                 this.selected_schemata_position_alternation_id = alternation_id;
-                this.selected_schemata_subentry_id = subentry.id;
+                this.selected_schemata_subentry_id = subentry ? subentry.id : null;
             },
             exampleSelected(selectedExamples) {
                 this.selectedExamples = selectedExamples;
@@ -200,16 +200,16 @@
             },
             attach_examples() {
                 if (this.frame_in_progress) {
-                    if (this.selected_frame_argument_id) {
+                    if (this.selectedLus) {
                         const examplesSelect = function () {
                             return '<div class="attach-examples-table-wrapper-scroll-y attach-examples-custom-scrollbar"><table id="attach-examples" class="table table-bordered table-striped mb-0"><thead><tr class="font-weight-bold"><th></th><th>Zdanie</th><th>Źródło</th><th>Opinia</th></tr></thead>' + this.examples.map(example => {
-                                return `<tr><td><input type="checkbox" name="lus" value="${example.id}" /></td><td>${example.sentence}</td><td>${example.source}</td><td>${example.opinion}</td></tr>`;
+                                return `<tr><td><input type="checkbox" ${this.selectedLus && example.lu_ids.includes(this.selectedLus[0].id)  ? 'checked' : ''} name="lus" value="${example.id}" /></td><td>${example.sentence}</td><td>${example.source}</td><td>${example.opinion}</td></tr>`;
                             }).join("") + '</table></div>';
                         }.bind(this);
 
                         const attach_examples_popup = {
                             state0: {
-                                title: 'Wybierz przykłady',
+                                title: 'Wybierz przykłady dla: ' + this.selectedLus.map(e => e.str).join(', '),
                                 html: examplesSelect,
                                 buttons: {Anuluj: 0, Wybierz: 1},
                                 focus: -1,
@@ -223,8 +223,7 @@
                                         let example_ids = normalizeFormData(f.lus);
                                         const data = {
                                             'example_ids': JSON.stringify(example_ids),
-                                            'frame_id': this.frame_in_progress.id,
-                                            'argument_id': this.selected_frame_argument_id.split('-')[1]
+                                            'selected_lus': JSON.stringify(this.selectedLus.map(e => e.id)),
                                         };
                                         $.ajax({
                                             type: 'post',
@@ -248,7 +247,7 @@
                         }
                         $.prompt(attach_examples_popup);
                     } else {
-                        alert(gettext("Wybierz argument, do którego chcesz podłączyć przykłady."));
+                        alert(gettext("Zaznacz jednostkę leksykalną, do którego chcesz podłączyć przykłady."));
                     }
                 } else {
                     alert(gettext("Stwórz nową ramę."));
@@ -283,6 +282,32 @@
                     return roleName;
                 }
             },
+            remove_argument() {
+                if (this.selected_frame_argument_id === null) {
+                    alert(gettext("Zaznacz argument, który chcesz usunąć."));
+                } else {
+                    const data = {
+                        'argument_id': parseInt(this.selected_frame_argument_id.split('-')[1]),
+                    };
+                    $.ajax({
+                        type: 'post',
+                        url: '/' + lang + '/freelus/remove_argument_from_frame/',
+                        dataType: 'json',
+                        data: data,
+                        timeout: 60000,
+                        success: function (response) {
+                            alert(gettext("Argument został usunięty."));
+                            show_info('Argument został usunięty.');
+                            this.loadEntry();
+                            $.prompt.close();
+                        }.bind(this),
+                        error: function (request, errorType, errorMessage) {
+                            show_error(errorType + ' (' + errorMessage + ')');
+                            $.prompt.close();
+                        }
+                    });
+                }
+            },
             change_role(selected_frame_argument_id, api_path) {
                 if (selected_frame_argument_id === null) {
                     alert(gettext("Zaznacz argument, dla którego chcesz wybrać rolę."));
@@ -414,9 +439,11 @@
                 if (this.frame_in_progress && this.selected_schemata_position_id && this.selected_frame_argument_id) {
                     const data = {
                         'frame_id': this.frame_in_progress.id,
+                        'subentry_id': parseInt(this.selected_schemata_subentry_id),
                         'argument_id': this.selected_frame_argument_id.split('-')[1],
                         'schema_id': this.selectedSchemas[0].id,
-                        'schema_position_id': this.selected_schemata_position_id.split('-')[1]
+                        'schema_position_id': this.selected_schemata_position_id.split('-')[1],
+                        'schema_alternation_id': (parseInt(this.selected_schemata_position_alternation_id)+1)
                     };
                     $.ajax({
                         type: 'post',
@@ -513,6 +540,9 @@
                     <td id="assign-schema" class="table-button-menu-td" @click="assign_schema()"
                         style="padding: 10px 15px 10px 15px; color: #000000;">Podłącz schemat
                     </td>
+                    <td id="remove-argument" class="table-button-menu-td" @click="remove_argument()"
+                        style="padding: 10px 15px 10px 15px; color: #000000;">Usuń argument
+                    </td>
                     <td id="delete-schema" class="table-button-menu-td" @click="delete_schema_connections()"
                         style="padding: 10px 15px 10px 15px; color: #000000;">Rozłącz schemat
                     </td>
diff --git a/frontend/src/components/unification/shared/frame-components/SemanticsSchemataComponent.vue b/frontend/src/components/unification/shared/frame-components/SemanticsSchemataComponent.vue
index 92ce2d5..90401c2 100644
--- a/frontend/src/components/unification/shared/frame-components/SemanticsSchemataComponent.vue
+++ b/frontend/src/components/unification/shared/frame-components/SemanticsSchemataComponent.vue
@@ -115,8 +115,8 @@
                     this.$emit('schemataSelected', [schema]);
                 } else {
                     this.selected_schemata_position_id = null;
-                    this.$emit('schemaPositionSelected', null);
-                    this.$emit('schemataSelected', []);
+                    this.$emit('schemaPositionSelected', null, null, null);
+                    this.$emit('schemataSelected', null);
                 }
             },
             computePositionCSS(position) {
-- 
GitLab