From ab5b8be7c88d2d97155ce8c58f2ef4acfc3fd831 Mon Sep 17 00:00:00 2001
From: Frederick Muriuki Muriithi
Date: Tue, 24 Oct 2023 05:08:42 +0300
Subject: case-attribute: approve/reject diff

Make calls to the API server to approve or reject a diff, depending on
the user's actions.

Clean up the UI elements to remove debug artifacts.
---
 .../templates/list_case_attribute_diffs.html       |  6 ---
 .../templates/view_case_attribute_diff.html        | 31 +++++++-------
 wqflask/wqflask/views.py                           | 47 +++++++++++++++++++---
 3 files changed, 58 insertions(+), 26 deletions(-)

diff --git a/wqflask/wqflask/templates/list_case_attribute_diffs.html b/wqflask/wqflask/templates/list_case_attribute_diffs.html
index a0f946d5..f5c7482f 100644
--- a/wqflask/wqflask/templates/list_case_attribute_diffs.html
+++ b/wqflask/wqflask/templates/list_case_attribute_diffs.html
@@ -20,12 +20,6 @@
 
   {{flash_me()}}
 
-  <p class="text-danger">
-    <span class="glyphicon glyphicon-exclamation-sign">
-    </span>
-    <strong>WORK IN PROGRESS!!!</strong>
-  </p>
-
   <table class="table-hover table-striped cell-border dataTable no-footer">
     <thead>
       <tr>
diff --git a/wqflask/wqflask/templates/view_case_attribute_diff.html b/wqflask/wqflask/templates/view_case_attribute_diff.html
index 7ff4e20e..0b5c95f1 100644
--- a/wqflask/wqflask/templates/view_case_attribute_diff.html
+++ b/wqflask/wqflask/templates/view_case_attribute_diff.html
@@ -35,6 +35,9 @@
   }
   .diff-addition {color: green; font-weight: bold;}
   .diff-deletion {color: red; font-weight: bold;}
+  form input[type="submit"] {
+      text-transform: capitalize;
+  }
 </style>
 {%endblock%}
 
@@ -88,22 +91,22 @@
   
 
   <form method="POST" action="{{url_for('approve_reject_diff')}}">
-    <input type="hidden"
-	   name="inbredset_id"
-	   value="{{diff.json_diff_data.inbredset_id}}" />
     <input type="hidden"
 	   name="diff_id"
-	   value="{{diff.id}}">
-    <button type="submit"
-	    title="Approve the changes"
-	    class="btn btn-warning">
-      Approve
-    </button>
-    <button type="submit"
-	    title="Reject the changes"
-	    class="btn btn-danger">
-      Reject
-    </button>
+	   value="{{diff.id}}" />
+    <input type="hidden"
+	   name="diff_data"
+	   value='{{diff.json_diff_data | tojson}}' />
+    <input type="submit"
+	   name="action"
+	   title="Approve the changes"
+	   class="btn btn-warning"
+	   value="approve" />
+    <input type="submit"
+	   name="action"
+	   title="Reject the changes"
+	   class="btn btn-danger"
+	   value="reject" />
   </form>
 {%endblock%}
 
diff --git a/wqflask/wqflask/views.py b/wqflask/wqflask/views.py
index 81597e95..32b7627f 100644
--- a/wqflask/wqflask/views.py
+++ b/wqflask/wqflask/views.py
@@ -1261,9 +1261,44 @@ def view_diff(inbredset_id:int, diff_id: int) -> Response:
                     "view_case_attribute_diff.html", diff=diff))
 
 @app.route("/case-attribute/diff/approve-reject", methods=["POST"])
-def approve_reject_diff(diff_filename: str) -> Response:
-    """Reject the diff."""
-    return jsonify({
-        "error": "Not Implemented.",
-        "error_description": "Would reject the diff."
-    }), 500
+def approve_reject_diff() -> Response:
+    """Approve/Reject the diff."""
+    try:
+        form = request.form
+        action = form["action"]
+        assert action in ("approve", "reject")
+        diff_data = json.loads(form["diff_data"])
+        diff_data = {
+            **diff_data,
+            "created": datetime.datetime.fromisoformat(diff_data["created"])}
+        inbredset_id = diff_data["inbredset_id"]
+        filename = (
+            f"{inbredset_id}:::{diff_data['user_id']}:::"
+            f"{diff_data['created'].isoformat()}.json")
+
+        list_diffs_page = url_for("list_case_attribute_diffs",
+                                  inbredset_id=inbredset_id)
+        token = session_info()["user"]["token"].either(
+            lambda err: err, lambda tok: tok["access_token"])
+        def __error__(resp):
+            error = resp.json()
+            flash((f"{resp.status_code} {error['error']}: "
+                   f"{error['error_description']}"),
+                  "alert-danger")
+            return redirect(list_diffs_page)
+        def __success__(results):
+            flash(results["message"], "alert-success")
+            return redirect(list_diffs_page)
+        return monad_requests.post(
+            urljoin(current_app.config["GN_SERVER_URL"],
+                    f"/api/case-attribute/{action}/{filename}"),
+            headers={"Authorization": f"Bearer {token}"}).then(
+                lambda resp: resp.json()
+            ).either(
+                __error__, __success__)
+    except AssertionError as _ae:
+        flash("Invalid action! Expected either 'approve' or 'reject'.",
+              "alert-danger")
+        return redirect(url_for("view_diff",
+                                inbredset_id=inbredset_id,
+                                diff_id=form["diff_id"]))
-- 
cgit v1.2.3