def generate_matches(): """ Compares Offers and Requests and saves matches (by product and area) to Matches database. Current version matches by Town. TODO: Match by actual distance, as for some addresses the other side of the road is a different Town! """ requests = app_tables.requests.search(tables.order_by("product_category")) offers = app_tables.offers.search(tables.order_by("product_key")) matches = 0 # print("Generating Matches...") statuses = anvil.server.call("STATUSES") for request in (x for x in requests if x['status'] not in statuses): for offer in (x for x in offers if x['status'] not in statuses): if request['product_category'] in offer['product_key']: if request['user']['display_name'] != offer['user'][ 'display_name']: # check if new or existing match new_match = app_tables.matches.get( request=request, offer=offer) or app_tables.matches.add_row( available_runners=[], request=request, offer=offer, status="New") new_match['route_url'] = generate_route_url(new_match) # 'or []' added to address possible database corruption i.e. value = None rather than value = [] if new_match not in (offer['matches'] or []): offer['matches'] = (offer['matches'] or []) + [new_match] if new_match not in (request['matches'] or []): request['matches'] = (request['matches'] or []) + [new_match]
def get_tickets(sort, filters={}, date_filter={}): ascending = True if sort == 'title' or sort == 'priority' else False if date_filter: date_filter['end'] += timedelta(days=1) return app_tables.tickets.search(tables.order_by(sort, ascending=ascending), date=q.between(date_filter['start'], date_filter['end'], max_inclusive=True), **filters) return app_tables.tickets.search( tables.order_by(sort, ascending=ascending), **filters)
def record_score(name, source_word, record_time, given_words): """ When a player successfully completes the game, their game details are passed in: - Name - Source word given by program - Their recorded time - Their input The current scores are pulled in, and their position in the front-end leaderboard is found. The score is recorded and their position is returned to the client before navigating to the leaderboard with that position passed as a parameter. This way, the position doesn't need to be stored but the user knows *their* position via an ascending order by time search. """ curr_scores = app_tables.high_scores.search( tables.order_by("time", ascending=True)) pos = 1 for entry in curr_scores: if entry["time"] > record_time: break pos += 1 app_tables.high_scores.add_row(name=name, source_word=source_word, time=record_time, matches=given_words) return pos
def get_my_deliveries(): """ Returns rows from the Matches database where runner = user """ user = anvil.users.get_user() if user is not None: return [ x for x in app_tables.matches.search(tables.order_by("status")) if x['approved_runner'] != None ]
def get_all_orders_time_sorted(user): user_management.verify_user_permission(user) orders=app_tables.pending_orders.search( tables.order_by("created", ascending=False), user=user ) if len(orders) is not 0: return orders
def my_measurements(): user = anvil.users.get_user() if not user: return [] measurements = app_tables.measurements.search(tables.order_by( "RecordDate", ascending=True), User=user) return measurements
def _generate_route_url_for_all_matches(): """This is a developer function to create OSM route urls for all Matches""" matches = app_tables.matches.search(tables.order_by("request")) count = 0 for match in matches: # if match['route_url'] == None: match['route_url'] = generate_route_url(match) count += 1 print(f"Populated {count} Matches with a route_url") return
def get_all_pending_teams_by_creator(creator): user_management.verify_user_permission(creator) teams=app_tables.pending_teams.search( tables.order_by("created", ascending=False), creator=creator, defunct=None ) if len(teams) is not 0: return teams
def get_all_completed_orders_time_sorted(user): user_management.verify_user_permission(user) orders=app_tables.pending_orders.search( tables.order_by("created", ascending=False), user=user, status=app_tables.order_statuses.get(status='Completado'), canceled=None, returned=None ) if len(orders) is not 0: return orders
def get_item_details(item_name, user): ''' Called when an item is selected from the search. This code prioritizes readability over number of lines. Returns a dict that looks like: { "style": "cool", "all_colors": [item_row, item_row], "matches": [ {'villager': villager_row, 'items': [item_row, item_row], 'purchased_on': 'date'}, ...] } ''' # non-lazily, find all item rows that have this name items = list(app_tables.items.search(name=item_name)) # item style is parsed out for the browser, and all items of the same name share the same style item_style = items[0]['style'] # build a list of associated villager rows, or an empty list (None is not helpful here) villagers = user['villagers'] or [] # build a list of villagers and which items they like, ignoring villagers that don't match matches = [] for villager in villagers: # CHECK FOR MATCHES matching_items = [] for item in items: if item_matches_villager(item, villager): matching_items.append(item) if len(matching_items) == 0: continue # LOOK FOR PREVIOUS GIFTS existing_gifts = app_tables.gifts.search(tables.order_by('updated_on'), villager=villager, item=q.any_of(*items)) if len(existing_gifts) > 0: # this villager has already received this gift purchase_date = '{dt.month}/{dt.day}'.format( dt=existing_gifts[0]['updated_on']) else: purchase_date = '' # SAVE THE DATA matches.append({ 'villager': dict(villager), 'items': matching_items, 'purchased_on': purchase_date }) return {'style': item_style, 'all_colors': items, 'matches': matches}
def text_box_3_change(self, **event_args): if len(self.text_box_3.text)>2: self.drop_down_3.enabled=True self.drop_down_3.items=[(r['title'],r['movieId']) for r in app_tables.movies.search(tables.order_by('title'),title=q.ilike("%"+self.text_box_3.text+"%"))] pass
def products(product_id, **param): client_jwt = anvil.server.request.headers['Authorization'] if not client_jwt: return anvil.server.HttpResponse( 400, "You must submit a Authorization header with an appropriate value." ) if not check_client(client_jwt): return anvil.server.HttpResponse( 403, "You are not authorized to access this end-point.") if "data" not in param.keys( ) or param['data'] != "product" or param['data'] != "picture": return anvil.server.HttpResponse( 400, '"data" query with the value of "product" or "picture" is expected.' ) # Get product information. if param['data'] == "product": if product_id != "all": return anvil.server.HttpResponse( 400, "You can only request all products by passing /all.") return [{ 'sku': product['sku'], 'name': product['name'], 'description': product['description'], 'price_single': product['price_single'], 'price_team': product['price_team'], 'created': product['created'].isoformat(), 'thumbnail': str(product['thumbnail']['order'] - 1), 'picture': str(len(product['picture'])), 'category': [{ 'category_name': product_category['category_name'] } for product_category in product['category']], 'brand': { 'code_name': product['brand']['code_name'] } } for product in app_tables.products.search()] # Get product pictures and thumbnail. elif param['data'] == "picture": global __product_pictures if product_id.isdigit(): sku = int(product_id) else: return anvil.server.HttpResponse(400, "SKU must be an integer.") if app_tables.products.get(sku=sku): if "id" in param.keys() and param['id'].isdigit(): index = int(param['id']) # If the product pictures aren't stored locally or it's not the right product, get the product pictures. if __product_pictures is None or sku is not __product_pictures[ 0]['product']['sku']: __product_pictures = app_tables.product_pictures.search( tables.order_by('order'), product=app_tables.products.get(sku=sku)) # Check if out of range. if index < len(__product_pictures): return __product_pictures[index]['picture'] else: return anvil.server.HttpResponse(400, "Index is out of range.") else: return anvil.server.HttpResponse(400, "Invalid data request.") else: return anvil.server.HttpResponse( 404, "Cannot find a product with the given SKU.")
def get_all_brands_time_sorted(): return app_tables.brands.search(tables.order_by("created", ascending=False))
def get_customers(filters={}): return app_tables.customers.search(tables.order_by('name', ascending=True), **filters)
def get_my_requests(): """ Returns rows from the Requests database for a given user """ user = anvil.users.get_user() if user is not None: return app_tables.requests.search(tables.order_by("product_category"), user=user)
def get_my_offers(): """ Returns rows from the Offers database for a given user """ user = anvil.users.get_user() if user is not None: return app_tables.offers.search(tables.order_by("product_key"), user=user)
def get_my_matches(): """ Returns rows from the Matches database """ user = anvil.users.get_user() if user is not None: return app_tables.matches.search(tables.order_by("status"), approved_runner=None)
def get_messages(ticket): return app_tables.messages.search(tables.order_by("date", ascending=False), ticket=ticket)
def get_scores(): return app_tables.scores.search(tables.order_by('score'))
def get_recent_documents(): return list( app_tables.documents.search( tables.order_by("created", ascending=False), )[:3])
def return_leaderboard(): high_scores = app_tables.high_scores.search( tables.order_by("time", ascending=True)) return high_scores
def return_log(): log = app_tables.user_log.search( tables.order_by("date_time", ascending=False)) return log
def get_all_products_time_sorted(): return app_tables.products.search( tables.order_by("created", ascending=False))
def IsValidUser(self, x): for y in app_tables.users.search(tables.order_by("email")): if x == y: return y return "User doesn't exist."