def route_edit_meta_division(meta_division_id): meta_division_data = json.loads(request.data) db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) # FIXME : need to load machines as part of init meta_division = fetch_entity(tables.MetaDivision, int(meta_division_id)) if 'divisions' in meta_division_data: for division in meta_division_data['divisions']: division_table = fetch_entity(tables.Division, int(division)) meta_division.divisions.append(division_table) for division in meta_division.divisions: if str(division.division_id ) not in meta_division_data['divisions']: meta_division.divisions.remove(division) if 'meta_division_name' in meta_division_data: meta_division.meta_division_name = meta_division_data[ 'meta_division_name'] if 'discount_ticket_count' in meta_division_data: meta_division.discount_ticket_count = meta_division_data[ 'discount_ticket_count'] if 'discount_ticket_price' in meta_division_data: meta_division.discount_ticket_price = meta_division_data[ 'discount_ticket_price'] if 'discount_stripe_sku' in meta_division_data and meta_division_data[ 'discount_stripe_sku']: meta_division.discount_stripe_sku = meta_division_data[ 'discount_stripe_sku'] tables.db_handle.session.commit() return jsonify({'data': meta_division.to_dict_simple()})
def get_sku_prices(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) dict_sku_prices = {} dict_div_to_sku = {} stripe.api_key = current_app.td_config['STRIPE_API_KEY'] divisions = tables.Division.query.all() use_stripe = False for division in divisions: if division.use_stripe is False: use_stripe = True dict_div_to_sku[division.division_id] = division.local_price if use_stripe is False: return jsonify({'data': dict_div_to_sku}) product_list = stripe.Product.list() items = product_list['data'] for item in items: dict_sku_prices[item['skus']['data'][0] ['id']] = item['skus']['data'][0]['price'] / 100 for division in divisions: if division.use_stripe: dict_div_to_sku[division.division_id] = dict_sku_prices[ division.stripe_sku] return jsonify({'data': dict_div_to_sku})
def confirm_tokens(tokens): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) #tokens_data = json.loads(request.data)['total_tokens'] #for token in tokens_data: for token in tokens: token = fetch_entity(tables.Token, token['token_id']) if token: token.paid_for = True tables.db_handle.session.commit() audit_log = tables.AuditLog() audit_log.purchase_date = datetime.datetime.now() if token.player_id: audit_log.player_id = token.player_id if token.team_id: audit_log.team_id = token.team_id audit_log.token_id = new_token.token_id audit_log.deskworker_id = current_user.user_id tokens_left_string = calc_audit_log_remaining_tokens( player_id, team_id) audit_log.remaining_tokens = tokens_left_string db.session.add(audit_log) tables.db_handle.session.commit() #DB.session.add(new_audit_log_entry) #tables.db_handle.session.commit() db.session.commit() return jsonify({'data': token.to_dict_simple()})
def send_push_notification(message, user_id=None, player_id=None, postpone=None, players=None, title="PAPA SCORING NOTIFICATION"): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) if user_id: user = fetch_entity(tables.User, user_id) token = user.ioniccloud_push_token token_list = [token] if player_id: player = fetch_entity(tables.Player, player_id) user = player.user token = user.ioniccloud_push_token token_list = [token] if players: token_list = [] for player_queue_item in players: player = fetch_entity(tables.Player, player_queue_item['player_id']) user = player.user token = user.ioniccloud_push_token token_list.append(token) url = "https://api.ionic.io/push/notifications" api_key = current_app.td_config['IONICCLOUD_API_KEY'] payload = { "tokens": token_list, "profile": current_app.td_config['IONICCLOUD_PROFILE_TAG'], "notification": { "ios": { "message": message, "sound": "default", "priority": 10 }, "android": { "message": message, "sound": "default" } #"message":message } } if postpone: now = datetime.datetime.now() now_plus = now + datetime.timedelta(seconds=postpone) now_plus_adjusted = now_plus + datetime.timedelta(hours=5) #2017-01-07T14:15:00Z scheduled_time_string = now_plus_adjusted.strftime( "%Y-%m-%dT%H:%M:%SZ") payload['scheduled'] = scheduled_time_string headers = { 'Authorization': "Bearer %s" % api_key, 'Content-Type': "application/json" } response = requests.post(url, data=json.dumps(payload), headers=headers)
def check_player_is_on_device(player_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) player = fetch_entity(tables.Player, player_id) if player and player.user.ioniccloud_push_token: return True return False
def route_add_division_machine_team(division_id,division_machine_id,team_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) division_machine = fetch_entity(tables.DivisionMachine,division_machine_id) team = fetch_entity(tables.Team,team_id) if division_machine.team_id or division_machine.player_id: raise Conflict('The machine is already being played') if check_player_team_can_start_game(current_app,division_machine,team=team) is False: raise BadRequest('Player can not start game - either no tickets or already on another machine') if tables.DivisionMachine.query.filter_by(player_id=team.players[0].player_id).first() or tables.DivisionMachine.query.filter_by(player_id=team.players[1].player_id).first(): raise BadRequest('Team can not start game - one player is playing on another machine') set_token_start_time(current_app,None,division_machine,team_id=team_id) division_machine.team_id=team.team_id tables.db_handle.session.commit() players_to_alert = [] removed_queues = [] for player in team.players: queue = tables.Queue.query.filter_by(player_id=player.player_id).first() if queue: players_to_alert = players_to_alert + get_player_list_to_notify(player.player_id,queue.division_machine) removed_queue = remove_player_from_queue(current_app,player,commit=True) removed_queues.append(removed_queue) db.session.commit() if all(item is not None and item is not False for item in removed_queues) and len(players_to_alert) > 0: push_notification_message = "The queue for %s has changed! Please check the queue to see your new position." % queue.division_machine.machine.machine_name send_push_notification(push_notification_message, players=players_to_alert) return jsonify({'data':division_machine.to_dict_simple()})
def create_ticket_purchase(app, ticket_count, player_id, user_id, purchase_summary_id, division_id=None, metadivision_id=None, commit=True): if ticket_count == 0: return db = db_util.app_db_handle(app) tables = db_util.app_db_tables(app) if division_id: division = tables.Division.query.filter_by(division_id=division_id).first() if metadivision_id: division = tables.MetaDivision.query.filter_by(meta_division_id=metadivision_id).first() discount_for = division.discount_ticket_count discount_price = division.discount_ticket_price if discount_for is None or discount_price is None: ticket_purchase = create_base_ticket_purchase(app,player_id,division_id,metadivision_id,user_id,purchase_summary_id) ticket_purchase.amount=ticket_count ticket_purchase.description="1" db.session.add(ticket_purchase) db.session.commit() return if ticket_count >= discount_for: #discount_count = ticket_count/discount_for #normal_count = ticket_count%discount_for normal_cost = division.local_price if division.discount_ticket_count: div_discount_count = division.discount_ticket_count div_discount_cost = division.discount_ticket_price else: div_discount_count = 1 div_discount_cost = 0 increment=division.min_num_tickets_to_purchase if increment is None: increment = 1 max_count = int(current_app.td_config['MAX_TICKETS_ALLOWED_PER_DIVISION']) counts = get_discount_normal_ticket_counts(max_count,div_discount_count,div_discount_cost,increment,normal_cost) normal_count=counts[1][ticket_count] discount_count=counts[2][ticket_count] else: discount_count = 0 normal_count = ticket_count increment=division.min_num_tickets_to_purchase if discount_count > 0: ticket_purchase = create_base_ticket_purchase(app,player_id,division_id,metadivision_id,user_id,purchase_summary_id) ticket_purchase.amount=discount_count ticket_purchase.description="%s"%discount_for db.session.add(ticket_purchase) if normal_count > 0: ticket_purchase = create_base_ticket_purchase(app,player_id,division_id,metadivision_id,user_id,purchase_summary_id) ticket_purchase.amount=normal_count ticket_purchase.description="%s"%increment db.session.add(ticket_purchase) if commit: db.session.commit() return {'discount_count':discount_count,'normal_count':normal_count}
def route_get_divisions(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) divisions = {division.division_id:division.to_dict_simple() for division in tables.Division.query.all()} #FIXME : this is a hack, and should be fixed divisions['metadivisions'] = {metadivision.meta_division_id:metadivision.to_dict_simple() for metadivision in tables.MetaDivision.query.all()} return jsonify({'data': divisions})
def route_delete_division_machine(division_id,division_machine_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) division_machine = fetch_entity(tables.DivisionMachine,division_machine_id) division_machine.removed=True tables.db_handle.session.commit() return jsonify({'data':division_machine.to_dict_simple()})
def create_audit_log(action, action_date, description, user_id=None, player_id=None, team_id=None, division_machine_id=None, entry_id=None, token_id=None, amount=None, commit=True): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) audit_log = tables.AuditLog() audit_log.action = action audit_log.action_date = action_date audit_log.description = description if user_id: audit_log.user_id = user_id if player_id: audit_log.player_id = player_id if team_id: audit_log.team_id = team_id if division_machine_id: audit_log.division_machine_id = division_machine_id if entry_id: audit_log.entry_id = entry_id if token_id: audit_log.token_id = token_id if amount: audit_log.amount = amount db.session.add(audit_log) if commit is True: db.session.commit()
def create_entry(app,division_machine_id,division_id,score,player_id=None,team_id=None): db = db_util.app_db_handle(app) tables = db_util.app_db_tables(app) entry = tables.Entry( division_id=division_id ) if player_id: existing_score = tables.Score.query.filter_by(division_machine_id=division_machine_id,score=score).join(tables.Entry).filter_by(player_id=player_id).first() if existing_score: return existing_score.entry entry.player_id=player_id if team_id: existing_score = tables.Score.query.filter_by(division_machine_id=division_machine_id,score=score).join(tables.Entry).filter_by(team_id=team_id).first() if existing_score: return existing_score.entry entry.team_id=team_id db.session.add(entry) ##db.session.commit() score = tables.Score( score=score, ##entry_id=entry.entry_id, division_machine_id=division_machine_id ) db.session.add(score) entry.scores.append(score) db.session.commit() return entry
def route_update_user(user_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) user = fetch_entity(tables.User, user_id) input_data = json.loads(request.data) if 'username' not in input_data: raise BadRequest("You did not specify a username") if input_data['username'] != user.username: user.username = input_data['username'] if 'has_picture' in input_data: user.has_picture = True if 'password' in input_data: user.crypt_password(input_data['password']) if 'roles' in input_data: check_roles_exist(tables, input_data['roles']) roles = current_app.tables.Role.query.all() user_roles = user.roles for role in roles: if role in user_roles and str( role.role_id) not in input_data['roles']: #print "removing %s"%role.name user.roles.remove(role) if role not in user_roles and str( role.role_id) in input_data['roles']: #print "removing %s"%role.name user.roles.append(role) if 'pic_file' in input_data: os.system('mv %s/%s /var/www/html/pics/user_%s.jpg' % (current_app.config['UPLOAD_FOLDER'], input_data['pic_file'], user.user_id)) db.session.commit() return jsonify({'data': user.to_dict_simple()})
def add_player_to_machine_from_queue(division_machine_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) division_machine = fetch_entity(tables.DivisionMachine, division_machine_id) division = fetch_entity(tables.Division, division_machine.division_id) if division.active is False: raise BadRequest('Division is not active') if len(division_machine.queue) == 0: raise BadRequest('Trying to add player from an empty queue') if division_machine.player_id is not None: raise BadRequest( 'Trying to add player from a queue to a machine in use') root_queue = tables.Queue.query.filter_by( division_machine_id=division_machine_id, parent_id=None).first() player = fetch_entity(tables.Player, root_queue.player_id) if check_player_team_can_start_game( current_app, division_machine, player=player) is False: raise BadRequest( 'Player can not start game - either no tickets or already on another machine' ) with db.session.no_autoflush: try: queues_to_lock = tables.Queue.query.with_for_update().filter_by( division_machine_id=division_machine.division_machine_id).all( ) players_to_alert = get_player_list_to_notify( player.player_id, division_machine) set_token_start_time(current_app, player, division_machine, commit=False) division_machine.player_id = root_queue.player_id if len(root_queue.queue_child) > 0: root_queue.queue_child.remove(root_queue.queue_child[0]) db.session.delete(root_queue) create_audit_log_ex( current_app, "Player added to machine from queue", user_id=current_user.user_id, player_id=player.player_id, division_machine_id=division_machine.division_machine_id, description="Player added to machine %s queue by %s" % (division_machine.machine.machine_name, current_user.username), commit=False) db.session.commit() return_dict = { 'division_machine': division_machine.to_dict_simple() } if len(players_to_alert) > 0: send_push_notification( "The queue for %s has changed! Please check the queue to see your new position." % division_machine.machine.machine_name, players=players_to_alert) return jsonify({'data': division_machine.to_dict_simple()}) except Exception as e: db.session.commit() raise e
def create_tournament(app,tournament_data): db = db_util.app_db_handle(app) tables = db_util.app_db_tables(app) if 'division_is_limited_herb' in tournament_data and tournament_data['division_is_limited_herb']: tournament_data['use_stripe'] = False tournament_data['local_price'] = 99 if 'use_stripe' in tournament_data and tournament_data['use_stripe'] and tournament_data['single_division'] is True: if get_valid_sku(tournament_data['stripe_sku'],app.td_config['STRIPE_API_KEY'])['sku'] is None: raise BadRequest('invalid SKU specified') new_tournament = tables.Tournament( tournament_name=tournament_data['tournament_name'] ) db.session.add(new_tournament) db.session.commit() if 'single_division' in tournament_data and tournament_data['single_division']: new_tournament.single_division=True tournament_data['division_name']= new_tournament.tournament_name+"_single" tournament_data['tournament_id']= new_tournament.tournament_id create_division(app,tournament_data) else: new_tournament.single_division=False db.session.commit() return new_tournament
def create_meta_division(app,meta_division_data): db = db_util.app_db_handle(app) tables = db_util.app_db_tables(app) new_meta_division = tables.MetaDivision( ) if 'meta_division_name' in meta_division_data: new_meta_division.meta_division_name=meta_division_data['meta_division_name'] if 'divisions' in meta_division_data: for division in meta_division_data['divisions']: division_table = fetch_entity(tables.Division,int(division)) new_meta_division.divisions.append(division_table) if 'use_stripe' in meta_division_data and meta_division_data['use_stripe']: new_meta_division.use_stripe = True if get_valid_sku(meta_division_data['stripe_sku'],app.td_config['STRIPE_API_KEY'])['sku'] is None: raise BadRequest('invalid SKU specified') new_meta_division.stripe_sku=meta_division_data['stripe_sku'] if 'discount_stripe_sku' in meta_division_data and meta_division_data['discount_stripe_sku']: if get_valid_sku(meta_division_data['discount_stripe_sku'],app.td_config['STRIPE_API_KEY'])['sku'] is None: raise BadRequest('invalid SKU specified') new_meta_division.discount_stripe_sku=meta_division_data['discount_stripe_sku'] new_meta_division.discount_ticket_count=meta_division_data['discount_ticket_count'] set_stripe_api_key(app.td_config['STRIPE_API_KEY']) fetch_stripe_price(app,new_meta_division) else: new_meta_division.use_stripe = False if 'local_price' in meta_division_data and meta_division_data['use_stripe'] == False: new_meta_division.local_price=meta_division_data['local_price'] tables.db_handle.session.add(new_meta_division) tables.db_handle.session.commit() return new_meta_division
def test_players_fast(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) players = { player.player_id: player.to_dict_fast() for player in tables.Player.query.filter_by(active=True).all() } return jsonify({'data': players})
def route_get_roles(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) roles = tables.Role.query.all() if roles is None: return jsonify({'data': None}) roles_dict = {role.role_id: role.to_dict_simple() for role in roles} return jsonify({'data': roles_dict})
def route_get_players(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) players = { player.player_id: player.to_dict_simple() for player in tables.Player.query.all() } return jsonify({'data': players})
def route_get_all_tournaments(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) tournaments_dict = { tournament.tournament_id: tournament.to_dict_simple() for tournament in tables.Tournament.query.all() } return jsonify({'data': tournaments_dict})
def route_get_teams(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) teams = { team.team_id: team.to_dict_simple() for team in tables.Team.query.all() } return jsonify({'data': teams})
def create_player(app,player_data,player_id=None): db = db_util.app_db_handle(app) tables = db_util.app_db_tables(app) player_role = tables.Role.query.filter_by(name='player').first() queue_role = tables.Role.query.filter_by(name='queue').first() token_role = tables.Role.query.filter_by(name='token').first() new_player = tables.Player( first_name=player_data['first_name'], last_name=player_data['last_name'], asshole_count=0 ) if player_id: new_player.player_id=player_id if 'active' in player_data and player_data['active'] is False: new_player.active=False else: new_player.active=True pin_range = set(range(1523, 9999)) existing_player_pins = set([player.pin for player in tables.Player.query.all()]) allowed_values = pin_range - existing_player_pins random_value = random.choice(list(allowed_values)) new_player.pin = random_value #if app.td_config['DB_TYPE']=='sqlite': # new_player.pin= random.randrange(1234,9999999) # db.session.commit() db.session.add(new_player) db.session.commit() new_user = tables.User( username="******" % (new_player.first_name,new_player.last_name,new_player.pin), pin=new_player.pin, is_player=True, roles=[player_role,queue_role,token_role] ) db.session.add(new_user) db.session.commit() new_player.user_id=new_user.user_id db.session.commit() if 'ifpa_ranking' in player_data and player_data['ifpa_ranking'] != 0: new_player.ifpa_ranking = player_data['ifpa_ranking'] if 'player_tshirt_size' in player_data: new_player.tshirt_size = player_data['player_tshirt_size'] if 'email_address' in player_data: new_player.email_address = player_data['email_address'] if 'linked_division_id' in player_data and tables.Division.query.filter_by(division_id=player_data['linked_division_id']).first(): new_player.linked_division_id = player_data['linked_division_id'] if 'pic_file' in player_data: new_player.has_pic=True save_path = "%s/%s"%(app.config['UPLOAD_FOLDER'],player_data['pic_file']) subprocess.call(["convert", save_path,"-resize", "128x128","-define","jpeg:extent=15kb", "%s_resize"%save_path]) subprocess.call(["mv","%s_resize"%save_path,save_path]) os.system('mv %s/%s %s/player_%s.jpg' % (app.config['UPLOAD_FOLDER'],player_data['pic_file'],app.config['UPLOAD_FOLDER'],new_player.player_id)) db.session.commit() return new_player
def route_get_players_for_division_with_tickets(division_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) players = { player.player_id: player.to_dict_simple() for player in tables.Player.query.filter_by( linked_division_id=division_id).all() } return jsonify({'data': players})
def route_audit_log_missing_scores(player_id,audit_log_id,minutes): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) users = {user.user_id:user.to_dict_simple() for user in tables.User.query.all()} divisions = {division.division_id:division.to_dict_simple() for division in tables.Division.query.all()} metadivisions = {meta_division.meta_division_id:meta_division.to_dict_simple() for meta_division in tables.MetaDivision.query.all()} division_machines = {division_machine.division_machine_id:division_machine.to_dict_simple() for division_machine in tables.DivisionMachine.query.all()} players = {player.player_id:player.to_dict_simple() for player in tables.Player.query.all()} teams = {team.team_id:team.to_dict_simple() for team in tables.Team.query.all()} audit_log_base = fetch_entity(tables.AuditLog,audit_log_id) if audit_log_base.action_date: audit_log_base_date = audit_log_base.action_date #if audit_log_base.game_started_date: # audit_log_base_date = audit_log_base.game_started_date audit_log_end_range = audit_log_base_date+datetime.timedelta(minutes=int(minutes)) print "%s - %s" % (audit_log_base_date,audit_log_end_range) division_id = audit_log_base.token.division_id metadivision_id = audit_log_base.token.metadivision_id audit_logs_query = tables.AuditLog.query if metadivision_id: div_string = " for metadivision %s" % metadivisions[metadivision_id]['meta_division_name'] audit_logs_query = audit_logs_query.filter(tables.AuditLog.token.has(metadivision_id=metadivision_id)) else: div_string = " for division %s" % divisions[division_id]['tournament_name'] audit_logs_query = audit_logs_query.filter(tables.AuditLog.token.has(division_id=division_id)) audit_logs_query=audit_logs_query.filter_by(action="Score Added") audit_logs = audit_logs_query.filter( and_( tables.AuditLog.action_date >= audit_log_base_date, tables.AuditLog.action_date <= audit_log_end_range ) ).order_by(asc(tables.AuditLog.action_date)).all() #audit_logs = audit_logs_query.all() audit_log_list = [] audit_log_index = 0 print len(audit_logs) for audit_log in audit_logs: #while audit_log_index < len(audit_logs): #audit_log=audit_logs[audit_log_index] if audit_log.division_machine_id: machine_name=division_machines[audit_log.division_machine_id]['division_machine_name'] if audit_log.team_id: player_team_string = "team %s " % teams[audit_log.team_id]['team_name'] else: player_team_string = "player %s "% players[audit_log.player_id]['first_name']+" "+players[audit_log.player_id]['first_name'] if audit_log.action == "Voided": continue division_machine_name = division_machines[audit_log.division_machine_id]['division_machine_name'] score = locale.format("%d",audit_log.entry.scores[0].score,grouping=True) audit_log_list.append({ 'audit_log_id':audit_log.audit_log_id, 'contents': [audit_log.action_date,audit_log.action,player_team_string,score,division_machine_name] }) return jsonify({'data':audit_log_list})
def test_in_line_players_fast(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) players = { player.player_id: player.to_dict_fast() for player in tables.Player.query.filter_by(pre_reg_paid=False, active=False).all() } return jsonify({'data': players})
def route_get_all_users(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) users = tables.User.query.all() users_dict = { user.user_id: user.to_dict_simple() for user in users if user.is_player is False } return jsonify({'data': users_dict})
def route_delete_user(user_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) user = tables.User.query.filter_by(user_id=user_id).first() if user is None: raise BadRequest("Tried to delete a user that does not exist") db.session.delete(user) db.session.commit() return jsonify({'data': 'deleted'})
def route_get_machines(): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) machines = tables.Machine.query.all() return jsonify({ 'data': {machine.machine_id: machine.to_dict_simple() for machine in machines} })
def route_remove_division_machine_team(division_id,division_machine_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) division_machine = fetch_entity(tables.DivisionMachine,division_machine_id) if division_machine.team_id is None: raise BadRequest('No team playing on this machine') division_machine.team_id=None tables.db_handle.session.commit() return jsonify({'data':division_machine.to_dict_simple()})
def get_queue_for_player(player_id): db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) player = fetch_entity(tables.Player, player_id) queue = tables.Queue.query.filter_by(player_id=player_id).first() if queue: return jsonify({'data': queue.to_dict_simple()}) else: return jsonify({'data': None})
def route_get_division_machines_longest_playtime(division_id,division_machine_id): f = open('/tmp/workfile%s'%division_id, 'w') db = db_util.app_db_handle(current_app) tables = db_util.app_db_tables(current_app) if division_machine_id == "0": if division_id == "0": division_machines = tables.DivisionMachine.query.all() else: division_machines = tables.DivisionMachine.query.filter_by(division_id=division_id).all() else: division_machines = [fetch_entity(tables.DivisionMachine,division_machine_id)] division_machine_names = {division_machine.division_machine_id:division_machine.machine.machine_name for division_machine in tables.DivisionMachine.query.all()} print division_machine_names division_machine_ids = [division_machine.division_machine_id for division_machine in division_machines] audit_logs = tables.AuditLog.query.filter(and_(tables.AuditLog.division_machine_id.in_(division_machine_ids), or_(tables.AuditLog.action == action for action in ('Game Started', 'Score Added', 'Score Voided', 'Jagoff Declared', 'Player Removed') ))).order_by(asc(tables.AuditLog.audit_log_id)).all() start_times = {} avg_times = {} for audit_log in audit_logs: if audit_log.action == "Game Started": start_times[audit_log.division_machine_id] = audit_log.action_date if audit_log.action == "Score Added" or audit_log.action == "Score Voided" or audit_log.action == "Jagoff Declared": if audit_log.division_machine_id not in avg_times: avg_times[audit_log.division_machine_id]=[] epoch = datetime.datetime.fromtimestamp(0) start_time=(start_times[audit_log.division_machine_id]-epoch).total_seconds() end_time = (audit_log.action_date - epoch).total_seconds() #f.write(str(datetime.datetime.fromtimestamp(start_time))+" "+str(datetime.datetime.fromtimestamp(end_time))+" "+str(start_time)+" "+str(end_time)+"\n") json_string = "{\"start_time\":\"%s\",\"end_time\":\"%s\",\"machine\":\"%s\",\"player\":\"%s\"},\n"%(str(start_time), str(end_time), division_machine_names[audit_log.division_machine_id], audit_log.player_id ) f.write(json_string) time_delta = audit_log.action_date - start_times[audit_log.division_machine_id] division_machine = tables.DivisionMachine.query.filter_by(division_machine_id=audit_log.division_machine_id).first() #f.write(str(time_delta.total_seconds()/60)+" ("+str(time_delta.total_seconds())+") on "+ division_machine.machine.machine_name +" ("+str(audit_log.audit_log_id)+")\n") avg_times[audit_log.division_machine_id].append(time_delta.total_seconds()) for avg_time_division_machine_id,machine_times in avg_times.iteritems(): total_time = 0 avg_game_time = 0 total_time = sum(machine_times) avg_game_time = total_time/len(machine_times) division_machine = tables.DivisionMachine.query.filter_by(division_machine_id=avg_time_division_machine_id).first() division_machine.avg_play_time = datetime.datetime.fromtimestamp(avg_game_time).strftime('%M min') db.session.commit() f.close() return jsonify({})