Repository: OpenEnergyPlatform/oeplatform

Issue:
After a table has been published, the peer review still refers to the unpublished table
## Description of the issue

We have recently introduced the function to publish a table via the profile page. 
Publishing basically means that a table must have been reviewed in model_draft and can then be moved to a target topic.
Once it has been moved, the peer review data of the updated topic to which the table has been moved will not be updated in the open peer review model.

## Steps to Reproduce
1. Create table
2. Review table
3. Publish table via profile page
4. Attempt to open the peer review again

## Ideas of solution

Solution 1: update the topic in the peer review table.
Solution 2: Store the table object in the peer review. In this case the topich (aka schema) will update once it was moved.


## Workflow checklist
- [ ] I am aware of the workflow in [CONTRIBUTING.md](https://github.com/OpenEnergyPlatform/oeplatform/blob/develop/CONTRIBUTING.md)



Discussion:

Resolving patch:
diff --git a/api/actions.py b/api/actions.py
--- a/api/actions.py
+++ b/api/actions.py
@@ -32,7 +32,7 @@
     load_cursor_from_context,
     load_session_from_context,
 )
-from dataedit.models import Schema as DBSchema
+from dataedit.models import Schema as DBSchema, PeerReview
 from dataedit.models import Table as DBTable
 from dataedit.structures import TableTags as OEDBTableTags
 from dataedit.structures import Tag as OEDBTag
@@ -490,9 +490,11 @@ def get_response_dict(
     """
     dict = {
         "success": success,
-        "error": str(reason).replace("\n", " ").replace("\r", " ")
-        if reason is not None
-        else None,
+        "error": (
+            str(reason).replace("\n", " ").replace("\r", " ")
+            if reason is not None
+            else None
+        ),
         "http_status": http_status_code,
         "exception": exception,
         "result": result,
@@ -1270,9 +1272,11 @@ def data_insert_check(schema, table, values, context):
                             {
                                 "operands": [
                                     {"type": "column", "column": c},
-                                    {"type": "value", "value": row[c]}
-                                    if c in row
-                                    else {"type": "value"},
+                                    (
+                                        {"type": "value", "value": row[c]}
+                                        if c in row
+                                        else {"type": "value"}
+                                    ),
                                 ],
                                 "operator": "=",
                                 "type": "operator",
@@ -1523,6 +1527,14 @@ def move(from_schema, table, to_schema):
         session.query(OEDBTableTags).filter(
             OEDBTableTags.schema_name == from_schema, OEDBTableTags.table_name == table
         ).update({OEDBTableTags.schema_name: to_schema})
+
+        all_peer_reviews = PeerReview.objects.filter(table=table, schema=from_schema)
+
+        for peer_review in all_peer_reviews:
+            peer_review.update_all_table_peer_reviews_after_table_moved(
+                to_schema=to_schema
+            )
+
         t.set_is_published()
         session.commit()
         # t.save()
@@ -1533,10 +1545,6 @@ def move(from_schema, table, to_schema):
         session.close()
 
 
-
-
-
-
 def create_meta(schema, table):
     # meta_schema = get_meta_schema_name(schema)
 
@@ -1745,9 +1753,11 @@ def get_columns(request, context=None):
 
     enums = dict(
         (
-            "%s.%s" % (rec["schema"], rec["name"])
-            if not rec["visible"]
-            else rec["name"],
+            (
+                "%s.%s" % (rec["schema"], rec["name"])
+                if not rec["visible"]
+                else rec["name"]
+            ),
             rec,
         )
         for rec in engine.dialect._load_enums(connection, schema="*")
diff --git a/dataedit/models.py b/dataedit/models.py
--- a/dataedit/models.py
+++ b/dataedit/models.py
@@ -1,4 +1,5 @@
 from enum import Enum
+import json
 
 from django.contrib.postgres.search import SearchVectorField
 from django.core.exceptions import ValidationError
@@ -195,8 +196,8 @@ def load(cls, schema, table):
         )
         return opr
 
-    # TODO: CAUTION unifinished work ... fix: includes all id´s and not just the
-    # related ones (reviews on same table) .. procudes false results
+    # TODO: CAUTION unfinished work ... fix: includes all id´s and not just the
+    # related ones (reviews on same table) .. procedures false results
     def get_prev_and_next_reviews(self, schema, table):
         """
         Sets the prev_review and next_review fields based on the date_started field of
@@ -227,10 +228,10 @@ def get_prev_and_next_reviews(self, schema, table):
 
     def save(self, *args, **kwargs):
         review_type = kwargs.pop("review_type", None)
+        pm_new = None
+
         if not self.contributor == self.reviewer:
-            # Call the parent class's save method to save the PeerReview instance
             super().save(*args, **kwargs)
-
             # TODO: This causes errors if review list ist empty
             # prev_review, next_review = self.get_prev_and_next_reviews(
             #   self.schema, self.table
@@ -242,35 +243,27 @@ def save(self, *args, **kwargs):
             # pm_new = PeerReviewManager(opr=self, prev_review=prev_review)
 
             if review_type == "save":
-                # Handle save status
                 pm_new = PeerReviewManager(
                     opr=self, status=ReviewDataStatus.SAVED.value
                 )
 
             elif review_type == "submit":
-                # Handle submit status
                 pm_new = PeerReviewManager(
                     opr=self, status=ReviewDataStatus.SUBMITTED.value
                 )
                 pm_new.set_next_reviewer()
 
             elif review_type == "finished":
-                # TODO: fails if the review is completed without submitting
-                # (finish in one run)
                 pm_new = PeerReviewManager(
                     opr=self, status=ReviewDataStatus.FINISHED.value
                 )
                 self.is_finished = True
                 self.date_finished = timezone.now()
-                # Call the parent class's save method to save the PeerReview instance
                 super().save(*args, **kwargs)
 
-            pm_new.save()
+            if pm_new:
+                pm_new.save()
 
-            # if prev_review is not None:
-            #     pm_prev = PeerReviewManager.objects.get(opr=prev_review)
-            #     pm_prev.next_review = next_review
-            #     pm_prev.save()
         else:
             raise ValidationError("Contributor and reviewer cannot be the same.")
 
@@ -300,6 +293,23 @@ def update(self, *args, **kwargs):
         else:
             raise ValidationError("Contributor and reviewer cannot be the same.")
 
+    def update_all_table_peer_reviews_after_table_moved(
+        self, *args, to_schema, **kwargs
+    ):
+        # all_peer_reviews = self.objects.filter(table=table, schema=from_schema)
+        # for peer_review in all_peer_reviews:
+        if isinstance(self.review, str):
+            review_data = json.loads(self.review)
+        else:
+            review_data = self.review
+
+        review_data["topic"] = to_schema
+
+        self.review = review_data
+        self.schema = to_schema
+
+        super().save(*args, **kwargs)
+
     @property
     def days_open(self):
         if self.date_started is None:
diff --git a/dataedit/views.py b/dataedit/views.py
--- a/dataedit/views.py
+++ b/dataedit/views.py
@@ -2151,6 +2151,7 @@ def get(self, request, schema, table, review_id=None):
             # need this here as json.dumps breaks the template syntax access
             # like {{ config.table }} now you can use {{ table }}
             "table": table,
+            "topic": schema,
             "config": json.dumps(config_data),
             "meta": metadata,
             "json_schema": json_schema,
@@ -2328,9 +2329,11 @@ def get(self, request, schema, table, review_id):
                     ),
                     "topic": schema,
                     "table": table,
+
                 }
             ),
             "table": table,
+            "topic": schema,
             "meta": metadata,
             "json_schema": json_schema,
             "field_descriptions_json": json.dumps(field_descriptions),


Test patch: