about summary refs log tree commit diff
diff options
context:
space:
mode:
authorzsloan2016-07-27 16:41:42 +0000
committerzsloan2016-07-27 16:41:42 +0000
commit44e302f3d84b10655b6900ceab6736d24e281f9e (patch)
tree325412f601e85e3342f6b00fcbb694e8e41533a0
parent1a4a115c36370ece8bce0f3ab32a5bb4076d0ab7 (diff)
downloadgenenetwork2-44e302f3d84b10655b6900ceab6736d24e281f9e.tar.gz
Fixed problem with phenotype traits causing error
Can now remove traits from collections and add to existing collections

Fixed a few other minor collection bugs
-rw-r--r--wqflask/base/data_set.py3
-rw-r--r--wqflask/wqflask/collect.py71
-rw-r--r--wqflask/wqflask/static/new/javascript/search_results.js35
-rw-r--r--wqflask/wqflask/templates/collections/view.html4
-rw-r--r--wqflask/wqflask/user_manager.py14
5 files changed, 92 insertions, 35 deletions
diff --git a/wqflask/base/data_set.py b/wqflask/base/data_set.py
index d0ec3f3c..7aed2576 100644
--- a/wqflask/base/data_set.py
+++ b/wqflask/base/data_set.py
@@ -106,7 +106,8 @@ Publish or ProbeSet. E.g.
                             new_type = "Geno"
                         else:
                             new_type = "ProbeSet"
-                            self.datasets[short_dataset_name] = new_type
+                        self.datasets[short_dataset_name] = new_type
+        print("DATASETS:", self.datasets)
         logger.info("datasets",self.datasets)
 
     def __call__(self, name):
diff --git a/wqflask/wqflask/collect.py b/wqflask/wqflask/collect.py
index 004240b4..f1c6ddd5 100644
--- a/wqflask/wqflask/collect.py
+++ b/wqflask/wqflask/collect.py
@@ -58,12 +58,26 @@ class AnonCollection(object):
         anon_user = user_manager.AnonUser()
         self.key = anon_user.key
         self.name = collection_name
-        self.id = str(uuid.uuid4())
+        self.id = None
         self.created_timestamp = datetime.datetime.utcnow().strftime('%b %d %Y %I:%M%p')
         self.changed_timestamp = self.created_timestamp #ZS: will be updated when changes are made
 
-        if Redis.get(self.key) == "None":
+        #ZS: Find id and set it if the collection doesn't already exist
+        if Redis.get(self.key) == "None" or Redis.get(self.key) == None:
             Redis.set(self.key, None) #ZS: For some reason I get the error "Operation against a key holding the wrong kind of value" if I don't do this   
+        else:
+            collections_list = json.loads(Redis.get(self.key))
+            collection_position = 0 #ZS: Position of collection in collection_list, if it exists
+            collection_exists = False
+            for i, collection in enumerate(collections_list):
+                if collection['name'] == self.name:
+                    collection_position = i
+                    collection_exists = True
+                    self.id = collection['id']
+                    break
+        if self.id == None:
+            self.id = str(uuid.uuid4())
+        
     
     def get_members(self):
         traits = []
@@ -87,7 +101,8 @@ class AnonCollection(object):
         self.traits = list(process_traits(params['traits']))
         #len_before = len(Redis.smembers(self.key))
         existing_collections = Redis.get(self.key)
-        if existing_collections != None:
+        print("existing_collections:", existing_collections)
+        if existing_collections != None and existing_collections != "None":
             collections_list = json.loads(existing_collections)
             collection_position = 0 #ZS: Position of collection in collection_list, if it exists
             collection_exists = False
@@ -99,7 +114,7 @@ class AnonCollection(object):
             if collection_exists:
                 collections_list[collection_position]['members'].extend(self.traits)
                 collections_list[collection_position]['num_members'] = len(collections_list[collection_position]['members'])
-                collections_list[collection_position]['changed_timestamp'] = self.last_changed_timestamp
+                collections_list[collection_position]['changed_timestamp'] = datetime.datetime.utcnow().strftime('%b %d %Y %I:%M%p')
             else:
                 collection_dict = {"id" : self.id,
                                    "name" : self.name,
@@ -125,12 +140,22 @@ class AnonCollection(object):
         #report_change(len_before, len_now)
 
     def remove_traits(self, params):
-        traits_to_remove = params.getlist('traits[]')
-        print("traits_to_remove:", process_txraits(traits_to_remove))
-        len_before = len(Redis.smembers(self.key))
-        Redis.srem(self.key, traits_to_remove)
-        print("currently in redis:", Redis.smembers(self.key))
-        len_now = len(Redis.smembers(self.key))
+        traits_to_remove = [(":").join(trait.split(":")[:2]) for trait in params.getlist('traits[]')]
+        existing_collections = Redis.get(self.key)
+        collection_position = 0
+        collections_list = json.loads(existing_collections)
+        for i, collection in enumerate(collections_list):
+            if collection['id'] == self.id:
+                collection_position = i
+                collection_exists = True
+                break
+        collections_list[collection_position]['members'] = [trait for trait in collections_list[collection_position]['members'] if trait not in traits_to_remove]
+        collections_list[collection_position]['num_members'] = len(collections_list[collection_position]['members'])
+        collections_list[collection_position]['changed_timestamp'] = datetime.datetime.utcnow().strftime('%b %d %Y %I:%M%p')
+        len_now = collections_list[collection_position]['num_members']
+        #print("before in redis:", json.loads(Redis.get(self.key)))
+        Redis.set(self.key, json.dumps(collections_list))
+        #print("currently in redis:", json.loads(Redis.get(self.key)))
 
         # We need to return something so we'll return this...maybe in the future
         # we can use it to check the results
@@ -249,8 +274,9 @@ def collections_new():
         if g.user_session.logged_in:
             return UserCollection().add_traits(params, collection_name)
         else:
-            #print("PARAMS ADD TO COLLECTION:", params)
-            return AnonCollection().add_traits(params)
+            ac = AnonCollection(collection_name)
+            ac.add_traits(params)
+            return redirect(url_for('view_collection', collection_id=ac.id))
     else:
         print("ELSE")
         CauseAnError
@@ -289,6 +315,7 @@ def create_new(collection_name):
         ac = AnonCollection(collection_name)
         ac.changed_timestamp = datetime.datetime.utcnow().strftime('%b %d %Y %I:%M%p')       
         ac.add_traits(params)
+        print("Collection ID:", ac.id)
         return redirect(url_for('view_collection', collection_id=ac.id))
 
 @app.route("/collections/list")
@@ -332,7 +359,8 @@ def remove_traits():
         uc.changed_timestamp = datetime.datetime.utcnow()
         db_session.commit()
     else:
-        members_now = AnonCollection().remove_traits(params)
+        collection_name = params['collection_name']
+        members_now = AnonCollection(collection_name).remove_traits(params)
 
 
     # We need to return something so we'll return this...maybe in the future
@@ -344,12 +372,17 @@ def remove_traits():
 def delete_collection():
     params = request.form
     print("params:", params)
-    uc_id = params['uc_id']
-    uc = model.UserCollection.query.get(uc_id)
-    # Todo: For now having the id is good enough since it's so unique
-    # But might want to check ownership in the future
-    collection_name = uc.name
-    db_session.delete(uc)
+    if "uc_id" in params:
+        uc_id = params['uc_id']
+        uc = model.UserCollection.query.get(uc_id)
+        # Todo: For now having the id is good enough since it's so unique
+        # But might want to check ownership in the future
+        collection_name = uc.name
+        db_session.delete(uc)
+    else:
+        collection_name = params['collection_name']
+        user_manager.AnonUser().delete_collection(collection_name)
+        
     flash("We've deletet the collection: {}.".format(collection_name), "alert-info")
 
     return redirect(url_for('list_collections'))
diff --git a/wqflask/wqflask/static/new/javascript/search_results.js b/wqflask/wqflask/static/new/javascript/search_results.js
index 4218fdbb..746564fd 100644
--- a/wqflask/wqflask/static/new/javascript/search_results.js
+++ b/wqflask/wqflask/static/new/javascript/search_results.js
@@ -130,17 +130,30 @@ $(function() {
     }).get();
     console.log("checked length is:", traits.length);
     console.log("checked is:", traits);
-    uc_id = $("#uc_id").val();
-    console.log("uc.id is:", uc_id);
-    return $.ajax({
-      type: "POST",
-      url: "/collections/remove",
-      data: {
-        uc_id: uc_id,
-        traits: traits
-      },
-      success: removed_traits
-    });
+    if ( $("#uc_id").length ) {
+        uc_id = $("#uc_id").val();
+        return $.ajax({
+          type: "POST",
+          url: "/collections/remove",
+          data: {
+            uc_id: uc_id,
+            traits: traits
+          },
+          success: removed_traits
+        });
+    }
+    else {
+        collection_name = $("#collection_name").val();
+        return $.ajax({
+          type: "POST",
+          url: "/collections/remove",
+          data: {
+            collection_name: collection_name,
+            traits: traits
+          },
+          success: removed_traits
+        });
+    }
   };
   $("#select_all").click(select_all);
   $("#deselect_all").click(deselect_all);
diff --git a/wqflask/wqflask/templates/collections/view.html b/wqflask/wqflask/templates/collections/view.html
index 4b1752cd..68d2886f 100644
--- a/wqflask/wqflask/templates/collections/view.html
+++ b/wqflask/wqflask/templates/collections/view.html
@@ -21,16 +21,16 @@
 
     <div class="container">
         <div>
-            {% if uc %}
             <form action="/collections/delete" method="post">
                 {% if uc %}
                 <input type="hidden" name="uc_id" id="uc_id" value="{{ uc.id }}" />
+                {% else %}
+                <input type="hidden" name="collection_name" id="collection_name" value="{{ collection_name }}" />
                 {% endif %}
                 <div class="col-xs-3 controls">
                     <input type="submit" class="btn btn-danger" value="Delete this collection" />
                 </div>
             </form>
-            {% endif %}
             <form action="/corr_matrix" method="post">
                 {% if uc %}
                 <input type="hidden" name="uc_id" id="uc_id" value="{{ uc.id }}" />
diff --git a/wqflask/wqflask/user_manager.py b/wqflask/wqflask/user_manager.py
index 7cc0f415..f1a798d4 100644
--- a/wqflask/wqflask/user_manager.py
+++ b/wqflask/wqflask/user_manager.py
@@ -62,7 +62,7 @@ def timestamp():
 
 
 class AnonUser(object):
-    cookie_name = 'anon_user_v3'
+    cookie_name = 'anon_user_v7'
 
     def __init__(self):
         self.cookie = request.cookies.get(self.cookie_name)
@@ -92,9 +92,19 @@ class AnonUser(object):
         len_now = len(Redis.smembers(self.key))
         print("LENGTH NOW:", len_now)
             
+    def delete_collection(self, collection_name):
+        existing_collections = self.get_collections()
+        for i, collection in enumerate(existing_collections):
+            collection['created_timestamp'] = collection['created_timestamp'].strftime('%b %d %Y %I:%M%p')
+            collection['changed_timestamp'] = collection['changed_timestamp'].strftime('%b %d %Y %I:%M%p')
+            if collection['name'] == collection_name:
+                existing_collections.pop(i)
+        Redis.set(self.key, json.dumps(existing_collections))
+            
     def get_collections(self):
         json_collections = Redis.get(self.key)
-        if json_collections == None:
+        print("json_collections:", json_collections)
+        if json_collections == None or json_collections == "None":
             return []
         else:
             collections = json.loads(json_collections)