def delete_table(userId, id): """ Deletes a table from the db. Only can be called via the saved_search.html """ try: savedSearch = SavedSearch.objects(id=id).first() tableName = savedSearch.name doDelete = True message = tableName + " deleted successfully!" if savedSearch.isDefaultOnDashboard: dashboards = [] for dash in Dashboard.objects(analystId=userId): dashboards.append(dash.id) if SavedSearch.objects(dashboard__in=dashboards, isDefaultOnDashboard=True, name=tableName).count() == 1: savedSearch.col = 1 savedSearch.row = 1 savedSearch.isPinned = False savedSearch.save() doDelete = False message = tableName + " is now hidden." if doDelete: dashId = savedSearch.dashboard savedSearch.delete() deleteDashboardIfEmpty(dashId) except Exception as e: print e return { 'success': False, 'message': "Search could not be found. Please refresh and try again." } return {'success': True, 'message': message, 'wasDeleted': doDelete}
def delete_table(userId, id): """ Deletes a table from the db. Only can be called via the saved_search.html """ try: savedSearch = SavedSearch.objects(id=id).first() tableName = savedSearch.name doDelete = True message = tableName+" deleted successfully!" if savedSearch.isDefaultOnDashboard: dashboards = [] for dash in Dashboard.objects(analystId=userId): dashboards.append(dash.id) if SavedSearch.objects(dashboard__in=dashboards, isDefaultOnDashboard=True, name=tableName).count() == 1: savedSearch.col = 1 savedSearch.row = 1 savedSearch.isPinned = False savedSearch.save() doDelete = False message = tableName+" is now hidden." if doDelete: dashId = savedSearch.dashboard savedSearch.delete() deleteDashboardIfEmpty(dashId) except Exception as e: print e return {'success': False, 'message': "Search could not be found. Please refresh and try again."} return {'success': True,'message': message, 'wasDeleted': doDelete}
def generate_search_for_saved_table(user, id=None, request=None): """ Called by edit_save_search in views.py. This is for editing a previously saved table or one of the default dashboard tables """ from crits.core.handlers import data_query response = {} savedSearch = None try: savedSearch = SavedSearch.objects(id=id).first() if not savedSearch: response['Result'] = "ERROR" response[ 'Message'] = "Error finding table, please try again later." return response except: savedSearch = SavedSearch() savedSearch.isDefaultOnDashboard = True savedSearch.name = id.replace("_", " ") id = None results = [] records = [] term = "" url = "" if not savedSearch.isDefaultOnDashboard: objType = get_obj_type_from_string(savedSearch.objType) resp = get_query_without_request(objType, user, savedSearch.searchTerm, "global") if resp['Result'] == "ERROR": return resp formatted_query = resp['query'] term = resp['term'] resp = data_query(objType, user, query=formatted_query, count=True) results.append({'count': resp['count'], 'name': savedSearch.objType}) else: results = { "name": savedSearch.name, "count": str(len(records)), "type": get_obj_name_from_title(savedSearch.name) } #special url to get the records of a default dashboard since their queries are different url = reverse( "crits.dashboards.views.get_dashboard_table_data", kwargs={"tableName": str(savedSearch.name.replace(" ", "_"))}) args = {'term': term, 'results': results, 'dataUrl': url, 'Result': "OK"} if savedSearch: args.update({ 'tableId': id, 'tableName': savedSearch.name, 'columns': savedSearch.tableColumns, 'sortBy': savedSearch.sortBy, 'sizex': savedSearch.sizex, 'maxRows': savedSearch.maxRows, 'isDefaultOnDashboard': savedSearch.isDefaultOnDashboard, }) if savedSearch.dashboard: args["currentDash"] = str(savedSearch.dashboard) args["dashtheme"] = Dashboard.objects( id=savedSearch.dashboard).first().theme return args
def generate_search_for_saved_table(user, id=None,request=None): """ Called by edit_save_search in views.py. This is for editing a previously saved table or one of the default dashboard tables """ from crits.core.handlers import data_query response = {} savedSearch = None try: savedSearch = SavedSearch.objects(id=id).first() if not savedSearch: response['Result'] = "ERROR" response['Message'] = "Error finding table, please try again later." return response except: savedSearch = SavedSearch() savedSearch.isDefaultOnDashboard = True savedSearch.name = id.replace("_", " ") id = None results = [] records = [] term = "" url = "" if not savedSearch.isDefaultOnDashboard: objType = get_obj_type_from_string(savedSearch.objType) resp = get_query_without_request(objType, user, savedSearch.searchTerm, "global") if resp['Result'] == "ERROR": return resp formatted_query = resp['query'] term = resp['term'] resp = data_query(objType, user, query=formatted_query, count=True) results.append({'count': resp['count'], 'name': savedSearch.objType}) else: results = {"name":savedSearch.name, "count":str(len(records)), "type":get_obj_name_from_title(savedSearch.name)} #special url to get the records of a default dashboard since their queries are different url = reverse("crits-dashboards-views-get_dashboard_table_data", kwargs={"tableName":str(savedSearch.name.replace(" ", "_"))}) args = {'term': term, 'results': results, 'dataUrl':url, 'Result': "OK" } if savedSearch: args.update({'tableId':id, 'tableName': savedSearch.name, 'columns': savedSearch.tableColumns, 'sortBy': savedSearch.sortBy, 'sizex' : savedSearch.sizex, 'maxRows': savedSearch.maxRows, 'isDefaultOnDashboard': savedSearch.isDefaultOnDashboard, }) if savedSearch.dashboard: args["currentDash"] = str(savedSearch.dashboard) args["dashtheme"] = Dashboard.objects(id=savedSearch.dashboard).first().theme return args
def get_dashboard(user, dashId=None): """ Gets a specific dashbaord for the user. If dashId is provided it looks it up. If dashId is not provided or the dashboard does not exist, it gets the user's default dashboard. If that dashboard does not exist, it first looks for a user-modified child of the public Default dashboard. Finally it will retrieve the public default dashboard if no others exist. """ dashboard = None if dashId: dashboard = Dashboard.objects(id=dashId).first() if not dashboard: return { 'success': False, 'message': "The dashboard you selected no longer exists." } elif user.defaultDashboard: try: dashboard = Dashboard.objects(id=user.defaultDashboard).first() except: user.defaultDashboard = None user.save() if not dashboard: dashboard = Dashboard.objects(name="Default", analystId__not__exists=1, isPublic=True).first() cloneOfDefault = Dashboard.objects(parent=dashboard.id, analystId=user.id).first() if cloneOfDefault: dashboard = cloneOfDefault dashId = dashboard.id tables = [] savedTables = SavedSearch.objects(dashboard=dashId, isPinned=True) for table in savedTables: tables.append(createTableObject(user, table=table)) otherDashboardIds = [] otherDashboards = {} for dash in Dashboard.objects(id__ne=dashId, analystId=user.id): otherDashboardIds.append(dash.id) otherDashboards[dash.id] = dash.name otherSearches = [] for search in SavedSearch.objects(dashboard__in=otherDashboardIds, isPinned=True): otherSearches.append({ "id": search.id, "dash": otherDashboards[search.dashboard], "name": search.name }) return { "success": True, "tables": tables, "dashboards": getDashboardsForUser(user), "currentDash": str(dashId), 'parentHasChanged': dashboard.hasParentChanged, 'parent': dashboard.parent, 'dashTheme': dashboard.theme, "otherSearches": otherSearches, "userId": dashboard.analystId }
def get_dashboard(user,dashId=None): """ Gets a specific dashbaord for the user. If dashId is provided it looks it up. If dashId is not provided or the dashboard does not exist, it gets the user's default dashboard. If that dashboard does not exist, it first looks for a user-modified child of the public Default dashboard. Finally it will retrieve the public default dashboard if no others exist. """ dashboard = None if dashId: dashboard = Dashboard.objects(id=dashId).first() if not dashboard: return {'success': False, 'message': "The dashboard you selected no longer exists."} elif user.defaultDashboard: try: dashboard = Dashboard.objects(id=user.defaultDashboard).first() except: user.defaultDashboard = None user.save() if not dashboard: dashboard = Dashboard.objects(name="Default", analystId__not__exists=1, isPublic=True).first() if dashboard: cloneOfDefault = Dashboard.objects(parent=dashboard.id, analystId=user.id).first() if cloneOfDefault: dashboard = cloneOfDefault else: return {'success': False, 'message': "No Default Dashboard. Run 'manage.py create_default_dashboard' to create."} dashId = dashboard.id tables = [] savedTables = SavedSearch.objects(dashboard=dashId, isPinned=True) for table in savedTables: tables.append(createTableObject(user, table=table)) otherDashboardIds = [] otherDashboards = {} for dash in Dashboard.objects(id__ne=dashId, analystId=user.id): otherDashboardIds.append(dash.id) otherDashboards[dash.id] = dash.name otherSearches = [] for search in SavedSearch.objects(dashboard__in=otherDashboardIds, isPinned=True) : otherSearches.append({ "id":search.id, "dash":otherDashboards[search.dashboard], "name":search.name }) return {"success": True, "tables": tables, "dashboards": getDashboardsForUser(user), "currentDash": str(dashId), 'parentHasChanged':dashboard.hasParentChanged, 'parent':dashboard.parent, 'dashTheme':dashboard.theme, "otherSearches":otherSearches, "userId": dashboard.analystId}
def clear_dashboard(dashId): """ Clears all the set positions and widths of the tables on the dashboard """ try: SavedSearch.objects(dashboard=dashId).update(unset__left=1,unset__top=1,unset__width=1) except: return {'success': False, 'message': "An unexpected error occurred while resetting dash. Please refresh and try again"} return {'success': True, 'message': "Dashboard Reset"}
def migrate_all_searches(): multiplier = 2 for search in SavedSearch.objects(): if "left" in search and search.left > 0: search.col = search.left / multiplier elif search.isDefaultOnDashboard: convert_default_searches(search, "left") if "width" in search: search.sizex = search.width / multiplier elif search.isDefaultOnDashboard: convert_default_searches(search, "width") if search.isDefaultOnDashboard: convert_default_searches(search, "top") search.save() SavedSearch.objects().update(unset__left=1, unset__top=1, unset__width=1)
def migrate_all_searches(): multiplier = 2 for search in SavedSearch.objects(): if "left" in search and search.left > 0: search.col = search.left/multiplier elif search.isDefaultOnDashboard: convert_default_searches(search, "left") if "width" in search: search.sizex = search.width/multiplier elif search.isDefaultOnDashboard: convert_default_searches(search, "width") if search.isDefaultOnDashboard: convert_default_searches(search, "top") search.save() SavedSearch.objects().update(unset__left=1, unset__top=1, unset__width=1)
def delete_table(id, tableHeight=0): """ Deletes a table from the db. Only can be called via the saved_search.html """ try: savedSearch = SavedSearch.objects(id=id).first() #if savedSearch.top > -1 and (not savedSearch.width or savedSearch.width>=97): # SavedSearch.objects(dashboard=savedSearch.dashId,top__gt=savedSearch.top).update(dec__top=tableHeight) tableName = savedSearch.name if savedSearch.isDefaultOnDashboard: savedSearch.left = -1 savedSearch.top = -1 savedSearch.width = 0 savedSearch.isPinned = False savedSearch.save() else: dashId = savedSearch.dashboard savedSearch.delete() deleteDashboardIfEmpty(dashId) except Exception as e: print e return { 'success': False, 'message': "Saved search cannot be found. Please refresh and try again." } return {'success': True, 'message': tableName + " deleted successfully!"}
def clear_dashboard(dashId): """ Clears all the set positions and widths of the tables on the dashboard """ try: SavedSearch.objects(dashboard=dashId).update(unset__left=1, unset__top=1, unset__width=1) except: return { 'success': False, 'message': "An unexpected error occurred while resetting dash. Please refresh and try again" } return {'success': True, 'message': "Dashboard Reset"}
def deleteDashboard(id): """ Deletes the dashboard with the given id and updates clones of it. Also deletes all saved searches affiliated with it """ try: dashboard = Dashboard.objects(id=id).first() name = dashboard.name if dashboard.isPublic: updateChildren(id, deletingParent=True) SavedSearch.objects(dashboard=id).delete() Dashboard.objects(id=id).delete() except Exception as e: print e return False return name
def switch_existing_search_to_dashboard(id, dashboard): if SavedSearch.objects(id=id).update(set__dashboard=dashboard) == 1: return {"success": True, "message": "Search Switched Sucessfully"} return { "success": False, "message": "Could not find search. Please refresh and try again." }
def clear_dashboard(dashId): """ Clears all the set positions and sizes of the tables on the dashboard """ default_tables = { "Counts": { "sizex": 10, "sizey": 13, "row": 1, "col": 1 }, "Top Backdoors": { "sizex": 10, "sizey": 8, "row": 1, "col": 10 }, "Top Campaigns": { "sizex": 25, "sizey": 8, "row": 1, "col": 20 }, "Recent Indicators": { "sizex": 50, "sizey": 8, "row": 15, "col": 1 }, "Recent Emails": { "sizex": 50, "sizey": 8, "row": 23, "col": 1 }, "Recent Samples": { "sizex": 50, "sizey": 8, "row": 31, "col": 1 }, } try: for search in SavedSearch.objects(dashboard=dashId): if search.isDefaultOnDashboard: tempDict = default_tables[search.name] search.sizex = tempDict["sizex"] search.sizey = tempDict["sizey"] search.row = tempDict["row"] search.col = tempDict["col"] search.save() else: search.update(unset__col=1,unset__row=1,unset__sizex=1) except Exception as e: print e return {'success': False, 'message': "An unexpected error occurred while resetting dash. Please refresh and try again"} return {'success': True, 'message': "Dashboard Reset"}
def clear_dashboard(dashId): """ Clears all the set positions and sizes of the tables on the dashboard """ default_tables = { "Counts": { "sizex": 10, "sizey": 13, "row": 1, "col": 1 }, "Top Campaigns": { "sizex": 25, "sizey": 8, "row": 1, "col": 20 }, "Recent Indicators": { "sizex": 50, "sizey": 8, "row": 15, "col": 1 }, "Recent Emails": { "sizex": 50, "sizey": 8, "row": 23, "col": 1 }, "Recent Samples": { "sizex": 50, "sizey": 8, "row": 31, "col": 1 }, } try: for search in SavedSearch.objects(dashboard=dashId): if search.isDefaultOnDashboard: tempDict = default_tables[search.name] search.sizex = tempDict["sizex"] search.sizey = tempDict["sizey"] search.row = tempDict["row"] search.col = tempDict["col"] search.save() else: search.update(unset__col=1, unset__row=1, unset__sizex=1) except Exception as e: print e return { 'success': False, 'message': "An unexpected error occurred while resetting dash. Please refresh and try again" } return {'success': True, 'message': "Dashboard Reset"}
def add_existing_search_to_dashboard(id, dashboard, user): search = SavedSearch.objects(id = id).first() if not search: return {"success":False, "message":"Could not find search. Please refresh and try again."} else: search = cloneSavedSearch(search, dashboard) return {"success":True, "message": search.name+" has been added to your dashboard.", "newSearch": createTableObject(user, table=search)}
def create_dashboard(drop=False): from crits.dashboards.dashboard import SavedSearch, Dashboard if drop: Dashboard.drop_collection() SavedSearch.drop_collection() defaultDashboard = Dashboard.objects(name="Default", analystId__not__exists=1 , isPublic=True).first() if not defaultDashboard: defaultDashboard = Dashboard() defaultDashboard.name = "Default" defaultDashboard.isPublic = True defaultDashboard.save() for title in ["Counts","Top Backdoors", "Top Campaigns","Recent Indicators", "Recent Emails", "Recent Samples"]: savedSearch = SavedSearch() savedSearch.name = title savedSearch.dashboard = defaultDashboard.id savedSearch.isDefaultOnDashboard = True savedSearch.tableColumns = getColumnsForTable(title) savedSearch.save() print "Default Dashboard Created." else: print "Default Dashboard already exists."
def toggleTableVisibility(id, isVisible): """ Changes the tables visibility to either pinned or hidden. """ table = SavedSearch.objects(id=id).first() if not table: return {'success': False, 'message': "Error finding table. Please refresh and try again"} message = table.name+ " is now " if isVisible: message += "visible" else: message += "hidden" table.isPinned = isVisible table.save() return {'success': True,'message': message}
def cloneDashboard(userId, dashboard, cloneSearches=False, skip=None): """ Clones a public dashboard to a user-modified version of if. cloneSearches will clone all affiliated searches with the dashboard. Skip will skip a specific table if cloning searches """ if Dashboard.objects(analystId=userId,name=dashboard.name): return newDash = Dashboard() newDash.name = dashboard.name newDash.theme = dashboard.theme newDash.analystId = userId newDash.parent = dashboard.id newDash.save() if cloneSearches: for search in SavedSearch.objects(dashboard = dashboard.id): if skip != str(search.id): cloneSavedSearch(search, newDash.id) return newDash
def cloneDashboard(userId, dashboard, cloneSearches=False, skip=None): """ Clones a public dashboard to a user-modified version of if. cloneSearches will clone all affiliated searches with the dashboard. Skip will skip a specific table if cloning searches """ if Dashboard.objects(analystId=userId, name=dashboard.name): return newDash = Dashboard() newDash.name = dashboard.name newDash.theme = dashboard.theme newDash.analystId = userId newDash.parent = dashboard.id newDash.save() if cloneSearches: for search in SavedSearch.objects(dashboard=dashboard.id): if skip != str(search.id): cloneSavedSearch(search, newDash.id) return newDash
def get_saved_searches_list(user): """ Returns all user dashboards and their affiliated saved searches. """ dashboards = [] for dash in Dashboard.objects(analystId=user.id): tables = [] for table in SavedSearch.objects(dashboard=dash.id): if table.isDefaultOnDashboard: table.searchTerm = "" table.objType = "" tables.append(table) tempDash = { "name": dash.name, "id": dash.id, "theme": dash.theme, 'isPublic': dash.isPublic, "tables": tables } if dash.parent: tempDash['isModified'] = True dashboards.append(tempDash) return {"dashboards": dashboards}
def delete_table(id, tableHeight=0): """ Deletes a table from the db. Only can be called via the saved_search.html """ try: savedSearch = SavedSearch.objects(id=id).first() #if savedSearch.top > -1 and (not savedSearch.width or savedSearch.width>=97): # SavedSearch.objects(dashboard=savedSearch.dashId,top__gt=savedSearch.top).update(dec__top=tableHeight) tableName = savedSearch.name if savedSearch.isDefaultOnDashboard: savedSearch.left = -1 savedSearch.top = -1 savedSearch.width = 0 savedSearch.isPinned = False savedSearch.save() else: dashId = savedSearch.dashboard savedSearch.delete() deleteDashboardIfEmpty(dashId) except Exception as e: print e return {'success': False, 'message': "Saved search cannot be found. Please refresh and try again."} return {'success': True,'message': tableName+" deleted successfully!"}
def get_saved_searches_list(user): """ Returns all user dashboards and their affiliated saved searches. """ dashboards = [] for dash in Dashboard.objects(analystId=user.id): tables = [] for table in SavedSearch.objects(dashboard=dash.id): if table.isDefaultOnDashboard: table.searchTerm = "" table.objType = "" tables.append(table) tempDash = { "name":dash.name, "id": dash.id, "theme":dash.theme, 'isPublic':dash.isPublic, "tables": tables } if dash.parent: tempDash['isModified'] = True dashboards.append(tempDash) return {"dashboards": dashboards}
def switch_existing_search_to_dashboard(id, dashboard): if SavedSearch.objects(id=id).update(set__dashboard=dashboard) == 1: return {"success":True, "message": "Search Switched Sucessfully"} return {"success":False, "message": "Could not find search. Please refresh and try again."}
def deleteDashboardIfEmpty(dashId): """ Checks if a dashboard has saved searches. Deletes it if it doesn't. """ if not SavedSearch.objects(dashboard=dashId): Dashboard.objects(id=dashId).delete()
def save_data(userId, columns, tableName, searchTerm="", objType="", sortBy=None, tableId=None, top=None, left=None, width=0, isDefaultOnDashboard=False, maxRows=0, dashboardWidth=0, dashboard=None, clone=False): """ Saves the customized table in the dashboard. Called by save_search and save_new_dashboard via ajax in views.py. width - css style used on dashboard tableWidth - width of table on edit page in order to calculate percentage width of columns """ try: if searchTerm: searchTerm = HTMLParser.HTMLParser().unescape(searchTerm) #if user is editing a table if tableId : newSavedSearch = SavedSearch.objects(id=tableId).first() if not newSavedSearch: raise Exception("Cannot find Table") elif clone: clonedSavedSearch = cloneSavedSearch(newSavedSearch, dashboard.id) else: newSavedSearch = SavedSearch() cols = [] for col in columns: if "field" not in col or "caption" not in col: continue cols.append(col) if not cols: raise("There are no columns to save") newSavedSearch.tableColumns = cols newSavedSearch.name = tableName oldDashId = None if dashboard: if newSavedSearch.dashboard != dashboard.id: newSavedSearch.left = -1 newSavedSearch.top = -1 newSavedSearch.dashboard= dashboard.id #if it is not a deault dashboard table, it must have a searchterm and objtype if searchTerm: newSavedSearch.searchTerm = searchTerm if objType: newSavedSearch.objType = objType #this is to identify the default tables on every user dashboard newSavedSearch.isDefaultOnDashboard = isDefaultOnDashboard if sortBy: newSavedSearch.sortBy = sortBy if (top or left) and dashboardWidth: newSavedSearch.top = top leftAsPercent = float(left)/float(dashboardWidth)*100 #if the new left value is within 2 of previous, dont change. #This is because rounding issues in the HTML were constantly #shifting the tables over by 1% every save if newSavedSearch.left==-1 or not (leftAsPercent >= newSavedSearch.left-2 and leftAsPercent <= newSavedSearch.left+2): newSavedSearch.left = leftAsPercent if maxRows: #if the table is growing in height, reset it's position so it doesnt #overlap with other tables if int(maxRows) > newSavedSearch.maxRows: newSavedSearch.top=-1 newSavedSearch.maxRows = maxRows; if width: width = float(width) if not dashboardWidth and newSavedSearch.width and (width > newSavedSearch.width+2 or width < newSavedSearch.width-2): newSavedSearch.top=-1 newSavedSearch.width = float(width) newSavedSearch.save() #if the old dashboard is empty, delete it if oldDashId: deleteDashboardIfEmpty(oldDashId) except Exception as e: print e return {'success': False, 'message': "An unexpected error occurred while saving table. Please refresh and try again"} return {'success': True,'message': tableName+" Saved Successfully!"}
def save_data(userId, columns, tableName, searchTerm="", objType="", sortBy=None, tableId=None, isDefaultOnDashboard=False, maxRows=0, dashboard=None, clone=False, row=0, grid_col=0, sizex=0, sizey=0): """ Saves the customized table in the dashboard. Called by save_search and save_new_dashboard via ajax in views.py. """ try: if searchTerm: searchTerm = HTMLParser.HTMLParser().unescape(searchTerm) #if user is editing a table if tableId : newSavedSearch = SavedSearch.objects(id=tableId).first() if not newSavedSearch: raise Exception("Cannot find Table") elif clone: clonedSavedSearch = cloneSavedSearch(newSavedSearch, dashboard.id) else: newSavedSearch = SavedSearch() cols = [] for col in columns: if "field" not in col or "caption" not in col: continue cols.append(col) if not cols: raise("There are no columns to save") newSavedSearch.tableColumns = cols newSavedSearch.name = tableName oldDashId = None if dashboard and newSavedSearch.dashboard != dashboard.id: newSavedSearch.dashboard= dashboard.id #if it is not a deault dashboard table, it must have a searchterm and objtype if searchTerm: newSavedSearch.searchTerm = searchTerm if objType: newSavedSearch.objType = objType #this is to identify the default tables on every user dashboard newSavedSearch.isDefaultOnDashboard = isDefaultOnDashboard if sortBy: newSavedSearch.sortBy = sortBy if sizex: newSavedSearch.sizex = sizex elif not newSavedSearch.sizex: newSavedSearch.sizex = 50 if sizey: newSavedSearch.sizey = sizey elif maxRows and maxRows != newSavedSearch.maxRows: newSavedSearch.sizey = int(maxRows)+1 elif not newSavedSearch.sizey: newSavedSearch.sizey = 7 if row: newSavedSearch.row = row elif not newSavedSearch.row: newSavedSearch.row = 1 if grid_col: newSavedSearch.col = grid_col elif not newSavedSearch.col: newSavedSearch.col = 1 if maxRows: newSavedSearch.maxRows = maxRows; newSavedSearch.save() #if the old dashboard is empty, delete it if oldDashId: deleteDashboardIfEmpty(oldDashId) except Exception as e: print "ERROR: " print e return {'success': False, 'message': "An unexpected error occurred while saving table. Please refresh and try again"} return {'success': True,'message': tableName+" Saved Successfully!"}
def save_data(userId, columns, tableName, searchTerm="", objType="", sortBy=None, tableId=None, isDefaultOnDashboard=False, maxRows=0, dashboard=None, clone=False, row=0, grid_col=0, sizex=0, sizey=0): """ Saves the customized table in the dashboard. Called by save_search and save_new_dashboard via ajax in views.py. """ try: if searchTerm: searchTerm = HTMLParser.HTMLParser().unescape(searchTerm) #if user is editing a table if tableId: newSavedSearch = SavedSearch.objects(id=tableId).first() if not newSavedSearch: raise Exception("Cannot find Table") elif clone: clonedSavedSearch = cloneSavedSearch(newSavedSearch, dashboard.id) else: newSavedSearch = SavedSearch() cols = [] for col in columns: if "field" not in col or "caption" not in col: continue cols.append(col) if not cols: raise ("There are no columns to save") newSavedSearch.tableColumns = cols newSavedSearch.name = tableName oldDashId = None if dashboard and newSavedSearch.dashboard != dashboard.id: newSavedSearch.dashboard = dashboard.id #if it is not a deault dashboard table, it must have a searchterm and objtype if searchTerm: newSavedSearch.searchTerm = searchTerm if objType: newSavedSearch.objType = objType #this is to identify the default tables on every user dashboard newSavedSearch.isDefaultOnDashboard = isDefaultOnDashboard if sortBy: newSavedSearch.sortBy = sortBy if sizex: newSavedSearch.sizex = sizex elif not newSavedSearch.sizex: newSavedSearch.sizex = 50 if sizey: newSavedSearch.sizey = sizey elif maxRows and maxRows != newSavedSearch.maxRows: newSavedSearch.sizey = int(maxRows) + 1 elif not newSavedSearch.sizey: newSavedSearch.sizey = 7 if row: newSavedSearch.row = row elif not newSavedSearch.row: newSavedSearch.row = 1 if grid_col: newSavedSearch.col = grid_col elif not newSavedSearch.col: newSavedSearch.col = 1 if maxRows: newSavedSearch.maxRows = maxRows newSavedSearch.save() #if the old dashboard is empty, delete it if oldDashId: deleteDashboardIfEmpty(oldDashId) except Exception as e: print "ERROR: " print e return { 'success': False, 'message': "An unexpected error occurred while saving table. Please refresh and try again" } return {'success': True, 'message': tableName + " Saved Successfully!"}
def save_data(userId, columns, tableName, searchTerm="", objType="", sortBy=None, tableId=None, top=None, left=None, width=0, isDefaultOnDashboard=False, maxRows=0, dashboardWidth=0, dashboard=None, clone=False): """ Saves the customized table in the dashboard. Called by save_search and save_new_dashboard via ajax in views.py. width - css style used on dashboard tableWidth - width of table on edit page in order to calculate percentage width of columns """ try: if searchTerm: searchTerm = HTMLParser.HTMLParser().unescape(searchTerm) #if user is editing a table if tableId: newSavedSearch = SavedSearch.objects(id=tableId).first() if not newSavedSearch: raise Exception("Cannot find Table") elif clone: clonedSavedSearch = cloneSavedSearch(newSavedSearch, dashboard.id) else: newSavedSearch = SavedSearch() cols = [] for col in columns: if "field" not in col or "caption" not in col: continue cols.append(col) if not cols: raise ("There are no columns to save") newSavedSearch.tableColumns = cols newSavedSearch.name = tableName oldDashId = None if dashboard: if newSavedSearch.dashboard != dashboard.id: newSavedSearch.left = -1 newSavedSearch.top = -1 newSavedSearch.dashboard = dashboard.id #if it is not a deault dashboard table, it must have a searchterm and objtype if searchTerm: newSavedSearch.searchTerm = searchTerm if objType: newSavedSearch.objType = objType #this is to identify the default tables on every user dashboard newSavedSearch.isDefaultOnDashboard = isDefaultOnDashboard if sortBy: newSavedSearch.sortBy = sortBy if (top or left) and dashboardWidth: newSavedSearch.top = top leftAsPercent = float(left) / float(dashboardWidth) * 100 #if the new left value is within 2 of previous, dont change. #This is because rounding issues in the HTML were constantly #shifting the tables over by 1% every save if newSavedSearch.left == -1 or not ( leftAsPercent >= newSavedSearch.left - 2 and leftAsPercent <= newSavedSearch.left + 2): newSavedSearch.left = leftAsPercent if maxRows: #if the table is growing in height, reset it's position so it doesnt #overlap with other tables if int(maxRows) > newSavedSearch.maxRows: newSavedSearch.top = -1 newSavedSearch.maxRows = maxRows if width: width = float(width) if not dashboardWidth and newSavedSearch.width and ( width > newSavedSearch.width + 2 or width < newSavedSearch.width - 2): newSavedSearch.top = -1 newSavedSearch.width = float(width) newSavedSearch.save() #if the old dashboard is empty, delete it if oldDashId: deleteDashboardIfEmpty(oldDashId) except Exception as e: print e return { 'success': False, 'message': "An unexpected error occurred while saving table. Please refresh and try again" } return {'success': True, 'message': tableName + " Saved Successfully!"}