From f7b4fbfa14c08e0f42768ef73a769e19bf1bc72e Mon Sep 17 00:00:00 2001
From: starek21 <starek21@vt.edu>
Date: Mon, 29 Apr 2024 22:00:14 -0400
Subject: [PATCH] implemented deleting collections

---
 .../__pycache__/sqlite_api.cpython-312.pyc    | Bin 11279 -> 11949 bytes
 database_implementation/sqlite_api.py         |  14 ++++++++++
 flask_backend.py                              |  22 +++++++++++++++
 .../src/App.js                                |   7 ++++-
 .../src/collection_list.js                    |  16 +++++++++--
 .../src/database_util.js                      |  25 ++++++++++++++++++
 6 files changed, 81 insertions(+), 3 deletions(-)

diff --git a/database_implementation/__pycache__/sqlite_api.cpython-312.pyc b/database_implementation/__pycache__/sqlite_api.cpython-312.pyc
index a7790301ef527d8df1011e480fe45ef6a185d826..c0e9c6d8dfc4c6426ca79c99e16a7aebd115cb60 100644
GIT binary patch
delta 1081
zcmZXTU1$_n6vyZ8$7D_JeoS^YyW5#`cVl2PE3py8G-i`DHi;r}jT%3)BI{=EByPLS
zrgtZlrmc}S6eOT6_o0DMh;NE0>L~c2PrekYuu3E`>YIH_F>QS)et`E3B?<Jx{P^GV
zKj)q^U+0fqIpO==>#Y{}O82*n_#3YK?mN&;_SCU^YFfx*f(;Mx8lDjs@lCt3Uf7Q~
zh@Wd82^dveOI-Vj+t#&Q2S|`tO5hUNt_<;LEve(tAPIBIL?w}Flns%necA`yulrij
z>X)TMUlt3d(UUjx!`7U0x|%5gT<zx5Ir;U^E4D2#h+OPKD5y9-?-2yrU{=BGu!!?p
zG$#<(uTG}m1beCaLhcQ&XuDPGF7{}fGLx-6z5Ts|y-ba0?Cpo1DeB-yP0Bq+(J&1X
z*Gt8sp__%$SUmX}B?l+*ryC-ZHOcr`$&8PbCdNpg=B7SgOt*3@duZt^org{O5yXNV
znv2$eP605Wg`@1^i1S6gT!_mO;jP(zZz2rBG;-@Bq#^w~_Lo$z@2d>tD*N*bp5awd
z!2a{;v+3EyqZ;KImMU`7#aN}O?Y2~@ZC}9YB^+49>O-u~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zOu%r$i?QUffkQl$`w1fidK!6>P$A3^Y6OvRflwzj2@PCHhT$>3NFGK=-G(CGP37Hr
zZgtG;?*~m+8<H&H=hShBOvcVxSyCirn$_ew7Sa)ucG=9Iam}<JT6iPf=RRV9U3bjy
S{Mk4D>^B`nUxsiiz4;r>A*>Jp

diff --git a/database_implementation/sqlite_api.py b/database_implementation/sqlite_api.py
index 5ab59fb..aa31049 100644
--- a/database_implementation/sqlite_api.py
+++ b/database_implementation/sqlite_api.py
@@ -57,6 +57,20 @@ class SqliteDatabaseAPI(database_api.CrisisEventsDatabase):
         self._disconnect(connection, cur)
         return collection_id
     
+    def delete_collection(self, collection_name):
+        connection, cur = self._connect()
+        cur.execute("DELETE FROM event_collections WHERE collection_name = ?", (collection_name,))
+
+        # Check if any row was affected
+        if cur.rowcount > 0:
+            print(f"Deleted collection '{collection_name}'")
+            self._disconnect(connection, cur)
+            return True
+        else:
+            print(f"Collection '{collection_name}' not found")
+            self._disconnect(connection, cur)
+            return False
+    
     def create_raw_text_file(self,collection_id,path):
         connection, cur = self._connect()
         cur.execute("INSERT INTO raw_text_files VALUES (NULL, ?, ?)", (collection_id,path,))
diff --git a/flask_backend.py b/flask_backend.py
index 457bfcf..5e8c2ae 100644
--- a/flask_backend.py
+++ b/flask_backend.py
@@ -186,6 +186,28 @@ def v1_create_collection():
         "collection_id":id
         }, 200
 
+@app.route('/api/v1/delete_collection', methods=['DELETE'])
+def v1_delete_collection():
+    data = request.json
+
+    if "collection_info" not in data:
+        abort(400)
+
+    collection_info = data["collection_info"]
+
+    if "collection_name" not in collection_info:
+        abort(400)
+
+    collection_name = collection_info["collection_name"]
+
+    # Call the database function to delete the collection
+    success = database.delete_collection(collection_name)
+
+    if success:
+        return jsonify({"status": "success", "message": f"Collection '{collection_name}' deleted"}), 200
+    else:
+        abort(404, f"Collection '{collection_name}' not found")
+
 @app.route('/api/v1/update_collection_glob', methods=['POST'])
 def v1_update_collection_glob():
 
diff --git a/frontend/crisis-events-text-summarization-frontend/src/App.js b/frontend/crisis-events-text-summarization-frontend/src/App.js
index 1c4c102..9fb57f9 100644
--- a/frontend/crisis-events-text-summarization-frontend/src/App.js
+++ b/frontend/crisis-events-text-summarization-frontend/src/App.js
@@ -127,6 +127,11 @@ function App() {
   updateFileLists();
   }
 
+  const handleDeletedCollection = () => {
+    setSelectedCollection(null);
+    showEditor();
+  }
+
   const logoutFunction = () => {
     setAuthenticated(false);
     sessionStorage.setItem('authenticated', 'false');
@@ -192,7 +197,7 @@ function App() {
         {/* <Box sx={{border: '1px dashed grey', padding:1}}> */}
           <Grid container spacing={2}>
             <Grid item xs={2}>
-              <CollectionList collections={loadedCollections} onSelectCollection={setSelectedCollection} onListUpdate={updateCollectionList} onFileSelect={onFileSelect} collectionFileCache={collectionFileCache}/>
+              <CollectionList collections={loadedCollections} onSelectCollection={setSelectedCollection} onListUpdate={updateCollectionList} onFileSelect={onFileSelect} collectionFileCache={collectionFileCache} onDeletedCollection={handleDeletedCollection}/>
             </Grid>
             <Grid item xs={10}>
               {
diff --git a/frontend/crisis-events-text-summarization-frontend/src/collection_list.js b/frontend/crisis-events-text-summarization-frontend/src/collection_list.js
index 727ccea..79198b6 100644
--- a/frontend/crisis-events-text-summarization-frontend/src/collection_list.js
+++ b/frontend/crisis-events-text-summarization-frontend/src/collection_list.js
@@ -1,6 +1,6 @@
 import * as React from 'react'
 import './Sidebar.css'
-import {dbCreateCollection, dbGetCollection, dbUploadRawTextFiles, dbUploadUrlFile, dbUploadRawHTMLFiles} from './database_util'
+import {dbCreateCollection, dbGetCollection, dbUploadRawTextFiles, dbUploadUrlFile, dbUploadRawHTMLFiles, dbDeleteCollection} from './database_util'
 
 
 //General MUI imports
@@ -85,6 +85,18 @@ const CollectionList = (props) => {
         props.onSelectCollection(detailCollection);
     }
 
+    const handleDelete = async (collectionName) => {
+        const isDeleted = await dbDeleteCollection(collectionName);
+        if (isDeleted) {
+          console.log(`Collection "${collectionName}" deleted successfully`);
+          props.onDeletedCollection(true);
+          props.onListUpdate();
+        } else {
+          console.error(`Failed to delete collection "${collectionName}"`);
+        }
+        handleDeleteClose();
+    }
+
     return (
         <div className="sidebar-container">
             <aside id="aside" className="sidebar">
@@ -184,7 +196,7 @@ const CollectionList = (props) => {
                 </DialogContent>
                 <DialogActions>
                     <Button onClick={handleDeleteClose}>Cancel</Button>
-                    <Button >Delete</Button>
+                    <Button onClick={() => handleDelete(displayedCollection)}>Delete</Button>
                 </DialogActions>
             </Dialog>
         </div>
diff --git a/frontend/crisis-events-text-summarization-frontend/src/database_util.js b/frontend/crisis-events-text-summarization-frontend/src/database_util.js
index bb01c3f..a77d277 100644
--- a/frontend/crisis-events-text-summarization-frontend/src/database_util.js
+++ b/frontend/crisis-events-text-summarization-frontend/src/database_util.js
@@ -29,6 +29,31 @@ export const  dbCreateCollection = async (newCollectionName, newCollectionType)
   return result
 };
 
+export const dbDeleteCollection = async (collectionName) => {
+  console.log("dbDeleteCollection");
+  const response = await fetch(
+    "http://127.0.0.1:5000/api/v1/delete_collection",
+    {
+      method: "DELETE",
+      headers: {
+        "Content-Type": "application/json",
+      },
+      body: JSON.stringify({
+        "collection_info": { "collection_name": collectionName }
+      }),
+    }
+  );
+
+  const responseData = await response.json();
+  if (responseData.status === "success") {
+    console.log("dbDeleteCollection Success");
+    return true;
+  } else {
+    console.error("dbDeleteCollection Failed");
+    return false;
+  }
+};
+
 export const dbGetCollection = async (collection_id) => {
   console.log("dbGetCollection");
   let result = await fetch("http://127.0.0.1:5000//api/v1/get_collection?collection=" + collection_id,)
-- 
GitLab