def roles_data(request): try: params = extract_datatable_params(request) role_type_id = int(request.GET['role_type']) role_type = get_object_or_404(RoleType, pk=role_type_id) except (KeyError, ValueError), e: return HttpResponseBadRequest(e)
def cyno_alts_data(request): try: params = extract_datatable_params(request) corp_id = request.GET.get('corp') except KeyError: return HttpResponseBadRequest() if corp_id: try: query = Corporation.objects.get( corporationID=int(corp_id)).members.filter(is_cyno_alt=True) except Corporation.DoesNotExist: query = Corporation.objects.mine().members.filter(is_cyno_alt=True) except ValueError: # corp_id cannot be casted to int, we take all corps query = Member.objects.exclude(corp=None).filter(is_cyno_alt=True) else: query = Corporation.objects.mine().members.all() total_members,\ filtered_members,\ members = get_members(query=query, first_id=params.first_id, last_id=params.last_id, search_str=params.search, sort_by=params.column, asc=params.asc, for_csv=params.format == 'csv') if params.format == 'csv': return datatable_csv_data(members, filename='members.csv') else: return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def orders_data(request): try: params = extract_datatable_params(request) display_mode = getattr(request, request.method).get('display_mode', 'open') except Exception, e: return HttpResponseBadRequest(str(e))
def skilled_list(request): try: params = extract_datatable_params(request) corp_id = request.GET.get('corp') skills = json.loads(request.GET.get("skills", "")) except KeyError: return HttpResponseBadRequest() if corp_id: try: members = Corporation.objects.get( corporationID=int(corp_id)).members.all() except Corporation.DoesNotExist: members = Corporation.objects.mine().members.all() except ValueError: # corp_id cannot be casted to int, we take all corps members = Member.objects.exclude(corp=None) else: members = Corporation.objects.mine().members.all() query = members for skill in skills: query &= members.filter(skills__eve_type_id=skill['id'], skills__level__gte=skill['lvl']) total_members,\ filtered_members,\ members = get_members(query=query.distinct(), first_id=params.first_id, last_id=params.last_id, sort_by=params.column, asc=params.asc) return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def cyno_alts_data(request): try: params = extract_datatable_params(request) corp_id = request.GET.get("corp") except KeyError: return HttpResponseBadRequest() if corp_id: try: query = Corporation.objects.get(corporationID=int(corp_id)).members.filter(is_cyno_alt=True) except Corporation.DoesNotExist: query = Corporation.objects.mine().members.filter(is_cyno_alt=True) except ValueError: # corp_id cannot be casted to int, we take all corps query = Member.objects.exclude(corp=None).filter(is_cyno_alt=True) else: query = Corporation.objects.mine().members.all() total_members, filtered_members, members = get_members( query=query, first_id=params.first_id, last_id=params.last_id, search_str=params.search, sort_by=params.column, asc=params.asc, for_csv=params.format == "csv", ) if params.format == "csv": return datatable_csv_data(members, filename="members.csv") else: return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def skilled_list(request): try: params = extract_datatable_params(request) corp_id = request.GET.get('corp') skills = json.loads(request.GET.get("skills", "")) except KeyError: return HttpResponseBadRequest() if corp_id: try: members = Corporation.objects.get(corporationID=int(corp_id)).members.all() except Corporation.DoesNotExist: members = Corporation.objects.mine().members.all() except ValueError: # corp_id cannot be casted to int, we take all corps members = Member.objects.exclude(corp=None) else: members = Corporation.objects.mine().members.all() query = members for skill in skills: query &= members.filter(skills__eve_type_id=skill['id'], skills__level__gte=skill['lvl']) total_members,\ filtered_members,\ members = get_members(query=query.distinct(), first_id=params.first_id, last_id=params.last_id, sort_by=params.column, asc=params.asc) return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def composition_data(request, title_id): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() title = get_object_or_404(Title, pk=int(title_id)) query = title.roles.all() if params.asc: query = query.order_by("roleID") else: query = query.order_by("-roleID") total_compos = query.count() query = query[params.first_id:params.last_id] role_list = [] for role in query: role_list.append([ role.permalink, role.roleType.permalink, role.get_access_lvl() ]) return datatable_ajax_data(role_list, params.sEcho, total_compos)
def composition_data(request, title_id): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() title = get_object_or_404(Title, pk=int(title_id)) query = title.roles.all() if params.asc: query = query.order_by("roleID") else: query = query.order_by("-roleID") total_compos = query.count() query = query[params.first_id:params.last_id] role_list = [] for role in query: role_list.append( [role.permalink, role.roleType.permalink, role.get_access_lvl()]) return datatable_ajax_data(role_list, params.sEcho, total_compos)
def oper_data(request, pos_id): try: params = extract_datatable_params(request) pos_id = int(pos_id) except: return HttpResponseBadRequest() pos = get_object_or_404(POS, item_id=pos_id) oper_table = [] members = Setting.get('hr_corp_members_group_name') for user in pos.operators.all(): oper_table.append([ user.username, ', '.join(user.characters.all().values_list('name', flat=True)), ', '.join( user.groups.exclude(name=members).values_list('name', flat=True)), ]) operator_count = pos.operators.all().count() json_data = { "sEcho": params.sEcho, "iTotalRecords": operator_count, "iTotalDisplayRecords": operator_count, "aaData": oper_table, } return HttpResponse(json.dumps(json_data))
def myorders_data(request): """ Serves URL /shop/orders/data/ (jQuery datatables plugin) """ try: params = extract_datatable_params(request) except Exception, e: return HttpResponseBadRequest(str(e))
def blueprints_data(request): # pull request params try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.displayMode = REQ.get('displayMode', 'originals') except Exception, e: return HttpResponseBadRequest(str(e))
def details_data(request, supply_id): """ Serves URL /industry/catalog/supplies/<supply_id>//data/ """ try: params = extract_datatable_params(request) supply_id = int(supply_id) except Exception, e: return HttpResponseBadRequest(str(e))
def blueprints_data(request): """ Serves URL /industry/catalog/blueprints/data/ """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.displayMode = REQ.get('displayMode', 'all') except Exception, e: return HttpResponseBadRequest(str(e))
def contracts_data(request): try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.type = int(REQ.get('type', 0)) # default to All params.status = int(REQ.get('status', 0)) # default to All except (ValueError, KeyError): return HttpResponseBadRequest() query = Contract.objects.all() total_entries = query.count() if params.search or params.type or params.status: search_args = Q() if params.search: # Search for contract title search_args |= Q(title__icontains=params.search) # Search for contract item in the contracts matching_ids = [t.typeID for t in Type.objects.filter(typeName__icontains=params.search)[:100]] # HACK: Django 1.3. distincts always on the default order attribute, so we use an aggregation # to get unique ids query_items = ContractItem.objects.filter(Q(typeID__in=matching_ids)).values('contract').annotate(Count('contract')) for match in query_items: search_args |= Q(contractID=match['contract']) if params.type: search_args &= Q(type=params.type) if params.status: search_args &= Q(status=params.status) query = query.filter(search_args) filtered_entries = query.count() entries = [] for entry in query[params.first_id:params.last_id]: entries.append([ entry.permalink_type, entry.status_html, entry.permalink, print_date(entry.dateIssued), print_date(entry.dateExpired), print_date(entry.dateAccepted), print_date(entry.dateCompleted), print_float(entry.price), print_float(entry.reward), print_float(entry.collateral), print_float(entry.buyout), print_volume(entry.volume, rounded=True), ]) return datatable_ajax_data(entries, params.sEcho, total_entries, filtered_entries)
def silo_data(request, pos_id): try: params = extract_datatable_params(request) pos_id = int(pos_id) except: return HttpResponseBadRequest() pos = get_object_or_404(POS, item_id=pos_id) #silo's are actually the moon mins. this is just the quickest way #using the Assets table. might make this work properly at some point. silos = Asset.objects.filter(closest_object_id=pos.moon_id, flag=constants.SILO_TYPEID) silo_table = [] for silo in silos: mineral = Type.objects.get(typeID=silo.eve_type_id) if pos.fuel_type_id == constants.GALLENTE_FUEL_BLOCK_TYPEID: remaining_vol = (constants.SILO_VOLUME * 2.0) - silo.volume remaining_per = int( (1.0 * silo.volume / (constants.SILO_VOLUME * 2.0)) * 100) elif pos.fuel_type_id == constants.AMARR_FUEL_BLOCK_TYPEID: remaining_vol = (constants.SILO_VOLUME * 1.5) - silo.volume remaining_per = int( (1.0 * silo.volume / (constants.SILO_VOLUME * 1.5)) * 100) else: remaining_vol = constants.SILO_VOLUME - silo.volume remaining_per = int( (1.0 * silo.volume / (constants.SILO_VOLUME)) * 100) if mineral.typeID in constants.COMPLEX_REACTIONS: hours_to_full = remaining_vol / ( mineral.volume * constants.COMPLEX_REACTIONS[mineral.typeID]) elif mineral.typeID in constants.SIMPLE_REACTIONS: hours_to_full = remaining_vol / (mineral.volume * 200) elif mineral.typeID in constants.UNREFINED: hours_to_full = remaining_vol / (mineral.volume * 1) else: hours_to_full = remaining_vol / (mineral.volume * 100) silo_div = '<div class="progress"><div class="bar" style="width: ' silo_div += str(remaining_per) + '%;"><span style="color:black;">' silo_div += print_duration(seconds=hours_to_full * 3600, verbose=False) silo_div += '</span></div></div>' silo_table.append([ silo.eve_type_id, mineral.typeName, silo.quantity, silo_div, #print_duration(seconds=hours_to_full * 3600, verbose=False) ]) silo_count = silos.count() json_data = { "sEcho": params.sEcho, "iTotalRecords": silo_count, "iTotalDisplayRecords": silo_count, "aaData": silo_table, } return HttpResponse(json.dumps(json_data))
def materials(request, blueprint_id): """ Serves URL /industry/catalog/blueprints/<blueprint_id>/materials/ (jQuery datatables) """ try: bp = get_object_or_404(OwnedBlueprint, id=int(blueprint_id)) params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.activityID = int(REQ.get('activityID', '1')) except (KeyError, ValueError), e: raise HttpResponseBadRequest(str(e))
def titles_data(request): try: params = extract_datatable_params(request) corp_id = request.GET.get('corp') except KeyError: return HttpResponseBadRequest() if corp_id: try: query = Corporation.objects.get( corporationID=int(corp_id)).titles.all() except Corporation.DoesNotExist: query = Corporation.objects.mine().titles.all() except ValueError: # corp_id cannot be casted to int, we take all corps query = Title.objects.all() else: query = Corporation.objects.mine().titles.all() sort_by = TITLES_COLUMNS[params.column]['db_field'] if params.column == 0: # SQL hack for making a case insensitive sort sort_col = "%s_nocase" % sort_by query = query.extra(select={sort_col: 'LOWER("%s")' % sort_by}) else: sort_col = sort_by if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=[sort_col]) # fetch the number of members having each title query = query.extra(select={ "title_members": SQL_TITLE_MEMBERS, "roles_in_title": SQL_ROLES_IN_TITLES }) titles = [] for title in query: if title.title_compo_diffs.all(): modification_date = print_time_min( title.title_compo_diffs.latest('id').date) else: modification_date = "-" titles.append([ title.permalink, title.accessLvl, '<a href="/%s/titles/%d/members/">%d</a>' % (app_prefix, title.id, title.title_members), title.roles_in_title, modification_date ]) return datatable_ajax_data(titles, params.sEcho)
def items_data(request): """ Serves URL /industry/catalog/items/data/ (jQuery datatables plugin) """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.showUnavailable = REQ.get('showUnavailable', 'true') == 'true' except: return HttpResponseBadRequest() query = CatalogEntry.objects.all() query = query.annotate(blueprint_count=Count("blueprints")) query = query.annotate(order_count=Count("order_rows")) if not params.showUnavailable: query = query.filter(is_available=True) sort_col = COLUMNS[params.column][1] # SQL hack for making a case insensitive sort if params.column == 1: sort_col = sort_col + "_nocase" sort_val = db.fix_mysql_quotes('LOWER("%s")' % COLUMNS[params.column]) query = query.extra(select={sort_col: sort_val}) if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=([sort_col])) if params.search: total_items = query.count() query = query.filter(typeName__icontains=params.search) filtered_items = query.count() else: total_items = filtered_items = query.count() items = [] for item in query[params.first_id:params.last_id]: items.append([ item.permalink, bool(item.is_available), print_float(item.fixed_price), print_float(item.production_cost), print_float(item.public_price), item.blueprint_count, item.order_count, item.typeID, ]) return datatable_ajax_data(data=items, echo=params.sEcho, total=total_items, filtered=filtered_items)
def details_data(request, contract_id): """ Serves URL /accounting/contracts/<contract_id>//data/ """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST contract_id = int(contract_id) params.included = REQ.get('included', 'All') params.singleton = REQ.get('singleton', 'All') params.grouped = int(REQ.get('grouped', 0)) except Exception, e: return HttpResponseBadRequest(str(e))
def silo_data(request, pos_id): try: params = extract_datatable_params(request) pos_id = int(pos_id) except: return HttpResponseBadRequest() pos = get_object_or_404(POS, item_id=pos_id) #silo's are actually the moon mins. this is just the quickest way #using the Assets table. might make this work properly at some point. silos = Asset.objects.filter(closest_object_id = pos.moon_id, flag = constants.SILO_TYPEID) silo_table = [] for silo in silos: mineral = Type.objects.get(typeID = silo.eve_type_id) if pos.fuel_type_id == constants.GALLENTE_FUEL_BLOCK_TYPEID: remaining_vol = (constants.SILO_VOLUME * 2.0) - silo.volume remaining_per = int((1.0 * silo.volume / (constants.SILO_VOLUME * 2.0)) * 100) elif pos.fuel_type_id == constants.AMARR_FUEL_BLOCK_TYPEID: remaining_vol = (constants.SILO_VOLUME * 1.5) - silo.volume remaining_per = int((1.0 * silo.volume / (constants.SILO_VOLUME * 1.5)) * 100) else: remaining_vol = constants.SILO_VOLUME - silo.volume remaining_per = int((1.0 * silo.volume / (constants.SILO_VOLUME)) * 100) if mineral.typeID in constants.COMPLEX_REACTIONS: hours_to_full = remaining_vol / (mineral.volume * constants.COMPLEX_REACTIONS[mineral.typeID]) elif mineral.typeID in constants.SIMPLE_REACTIONS: hours_to_full = remaining_vol / (mineral.volume * 200) elif mineral.typeID in constants.UNREFINED: hours_to_full = remaining_vol / (mineral.volume * 1) else: hours_to_full = remaining_vol / (mineral.volume * 100) silo_div = '<div class="progress"><div class="bar" style="width: ' silo_div += str(remaining_per)+'%;"><span style="color:black;">' silo_div += print_duration(seconds=hours_to_full * 3600, verbose=False) silo_div += '</span></div></div>' silo_table.append([ silo.eve_type_id, mineral.typeName, silo.quantity, silo_div, #print_duration(seconds=hours_to_full * 3600, verbose=False) ]) silo_count = silos.count() json_data = { "sEcho" : params.sEcho, "iTotalRecords" : silo_count, "iTotalDisplayRecords" : silo_count, "aaData" : silo_table, } return HttpResponse(json.dumps(json_data))
def titles_data(request): try: params = extract_datatable_params(request) corp_id = request.GET.get("corp") except KeyError: return HttpResponseBadRequest() if corp_id: try: query = Corporation.objects.get(corporationID=int(corp_id)).titles.all() except Corporation.DoesNotExist: query = Corporation.objects.mine().titles.all() except ValueError: # corp_id cannot be casted to int, we take all corps query = Title.objects.all() else: query = Corporation.objects.mine().titles.all() sort_by = TITLES_COLUMNS[params.column]["db_field"] if params.column == 0: # SQL hack for making a case insensitive sort sort_col = "%s_nocase" % sort_by query = query.extra(select={sort_col: 'LOWER("%s")' % sort_by}) else: sort_col = sort_by if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=[sort_col]) # fetch the number of members having each title query = query.extra(select={"title_members": SQL_TITLE_MEMBERS, "roles_in_title": SQL_ROLES_IN_TITLES}) titles = [] for title in query: if title.title_compo_diffs.all(): modification_date = print_time_min(title.title_compo_diffs.latest("id").date) else: modification_date = "-" titles.append( [ title.permalink, title.accessLvl, '<a href="/%s/titles/%d/members/">%d</a>' % (app_prefix, title.id, title.title_members), title.roles_in_title, modification_date, ] ) return datatable_ajax_data(titles, params.sEcho)
def wallets_data(request): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() my_corp = Corporation.objects.mine() query = my_corp.wallets.all() total_entries = filtered_entries = query.count() entries = [] for wallet in query: try: balance = JournalEntry.objects.filter(wallet=wallet.wallet).latest().balance except JournalEntry.DoesNotExist: # no journal information, we assume the balance is 0.0 balance = 0.0 entries.append([ wallet, balance ]) if params.column == 0: # sort by walletID sort_key = lambda e: e[0].wallet.walletID else: # sort by balance sort_key = lambda e: e[1] entries.sort(key=sort_key, reverse=not params.asc) total_balance = 0 for wallet in entries: total_balance += wallet[1] wallet[1] = wallet_journal_permalink(wallet[0], wallet[1]) wallet[0] = wallet[0].name # Append total amount value = WALLET_LINK % ("/accounting/journal/", "Click to access this wallet's journal", print_float(total_balance)) entries.append(['<b>Total</b>', "<b>%s</b>" % value]) json_data = { "sEcho" : params.sEcho, "iTotalRecords" : total_entries, "iTotalDisplayRecords" : filtered_entries, "aaData" : entries, } return HttpResponse(json.dumps(json_data))
def items_data(request): """ Serves URL /industry/catalog/items/data/ (jQuery datatables plugin) """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.showUnavailable = REQ.get('showUnavailable', 'true') == 'true' except: return HttpResponseBadRequest() query = CatalogEntry.objects.all() query = query.annotate(blueprint_count=Count("blueprints")) query = query.annotate(order_count=Count("order_rows")) if not params.showUnavailable: query = query.filter(is_available=True) sort_col = COLUMNS[params.column][1] # SQL hack for making a case insensitive sort if params.column == 1: sort_col = sort_col + "_nocase" sort_val = db.fix_mysql_quotes('LOWER("%s")' % COLUMNS[params.column]) query = query.extra(select={ sort_col : sort_val }) if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=([sort_col])) if params.search: total_items = query.count() query = query.filter(typeName__icontains=params.search) filtered_items = query.count() else: total_items = filtered_items = query.count() items = [] for item in query[params.first_id:params.last_id]: items.append([ item.permalink, bool(item.is_available), print_float(item.fixed_price), print_float(item.production_cost), print_float(item.public_price), item.blueprint_count, item.order_count, item.typeID, ]) return datatable_ajax_data(data=items, echo=params.sEcho, total=total_items, filtered=filtered_items)
def wallets_data(request): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() my_corp = Corporation.objects.mine() query = my_corp.wallets.all() total_entries = filtered_entries = query.count() entries = [] for wallet in query: try: balance = JournalEntry.objects.filter( wallet=wallet.wallet).latest().balance except JournalEntry.DoesNotExist: # no journal information, we assume the balance is 0.0 balance = 0.0 entries.append([wallet, balance]) if params.column == 0: # sort by walletID sort_key = lambda e: e[0].wallet.walletID else: # sort by balance sort_key = lambda e: e[1] entries.sort(key=sort_key, reverse=not params.asc) total_balance = 0 for wallet in entries: total_balance += wallet[1] wallet[1] = wallet_journal_permalink(wallet[0], wallet[1]) wallet[0] = wallet[0].name # Append total amount value = WALLET_LINK % ("/accounting/journal/", "Click to access this wallet's journal", print_float(total_balance)) entries.append(['<b>Total</b>', "<b>%s</b>" % value]) json_data = { "sEcho": params.sEcho, "iTotalRecords": total_entries, "iTotalDisplayRecords": filtered_entries, "aaData": entries, } return HttpResponse(json.dumps(json_data))
def unassociated_data(request): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() total_members,\ filtered_members,\ members = get_members(query=Corporation.objects.mine().members.filter(owner=None), first_id=params.first_id, last_id=params.last_id, search_str=params.search, sort_by=params.column, asc=params.asc) return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def jobs_list_data(request): try: params = extract_datatable_params(request) activity = getattr(request, request.method)['activity'] try: activity = int(activity) except ValueError: pass state = getattr(request, request.method)['state'] try: state = int(state) except ValueError: pass assignment = getattr(request, request.method)['assignment'] except (KeyError, ValueError), e: return HttpResponseBadRequest(str(e))
def player_contrib_data(request): """ View function URL : '/accounting/contributions/players/data/' """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.from_date = timezone.make_aware( datetime.strptime(REQ.get('from_date', None), DATE_PATTERN), timezone.get_current_timezone()) to_date = datetime.strptime(REQ.get('to_date', None), DATE_PATTERN) if to_date.hour == 0 and to_date.minute == 0 and to_date.second == 0: to_date += timedelta(1) params.to_date = timezone.make_aware(to_date, timezone.get_current_timezone()) except: return HttpResponseBadRequest() contributions = player_contributions(since=params.from_date, until=params.to_date, order_by=columns[params.column], ascending=params.asc) count = len(contributions[:]) contributions = contributions[params.first_id:params.last_id] contrib_list = [] for c in contributions: if c.username == None: contrib_list.append( [tr('not associated'), print_float(c.tax_contrib)]) else: contrib_list.append([ '<a href="%s" class="player">%s</a>' % (c.get_absolute_url(), c.username), print_float(c.tax_contrib) ]) json_data = { "sEcho": params.sEcho, "iTotalRecords": count, "iTotalDisplayRecords": count, "aaData": contrib_list } return HttpResponse(json.dumps(json_data))
def members_data(request, title_id): try: params = extract_datatable_params(request) title = get_object_or_404(Title, pk=int(title_id)) except (KeyError, ValueError): return HttpResponseBadRequest() total_members,\ filtered_members,\ members = get_members(query=title.members.all(), first_id=params.first_id, last_id=params.last_id, search_str=params.search, sort_by=params.column, asc=params.asc) return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def player_list_data(request): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() query = User.objects.select_related(depth=2).filter(is_active=True) query = query.annotate(account_count=Count("eve_accounts")) query = query.annotate(char_count=Count("characters")) query = query.annotate(group_count=Count("groups")) query = query.filter(eve_accounts__gt=0) sort_by = PLAYERS_COLUMNS[params.column]['db_field'] # SQL hack for making a case insensitive sort if sort_by == "username": sort_col = "%s_nocase" % sort_by query = query.extra(select={sort_col: 'LOWER("%s")' % sort_by}) else: sort_col = sort_by if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=[sort_col]) if params.search: total_count = query.count() query = query.filter(username__icontains=params.search) filtered_count = query.count() else: total_count = filtered_count = query.count() player_list = [] for player in query[params.first_id:params.last_id]: player_list.append([ '<a href="/hr/players/%d/" class="player">%s</a>' % (player.id, player.username), player.is_staff and player.is_superuser, player.eve_accounts.all().count(), player.characters.all().count(), player.groups.all().count(), print_time_min(player.last_login), print_time_min(player.date_joined) ]) return datatable_ajax_data(player_list, params.sEcho, total_count, filtered_count)
def fuel_data(request, pos_id): try: params = extract_datatable_params(request) pos_id = int(pos_id) except: return HttpResponseBadRequest() pos = get_object_or_404(POS, item_id=pos_id) fuelTypeIDs = ( pos.fuel_type_id, constants.STRONTIUM_CLATHRATES_TYPEID, ) fuelTable = [] for type_id in fuelTypeIDs: try: fuel = pos.fuel_levels.filter(type_id=type_id).latest() quantity = fuel.current_fuel() consumption = fuel.consumption except FuelLevel.DoesNotExist: quantity = 0 consumption = 0 if consumption == 0: timeLeft = '-' else: hoursLeft = int(quantity / consumption) timeLeft = print_duration(seconds=hoursLeft * 3600, verbose=False) fuelTable.append([ type_id, Type.objects.get(typeID=type_id).typeName, print_fuel_quantity(quantity), '%d / hour' % consumption, '%d / day' % (consumption * 24), timeLeft, ]) json_data = { "sEcho": params.sEcho, "iTotalRecords": len(fuelTypeIDs), "iTotalDisplayRecords": len(fuelTypeIDs), "aaData": fuelTable } return HttpResponse(json.dumps(json_data))
def fuel_data(request, pos_id): try: params = extract_datatable_params(request) pos_id = int(pos_id) except: return HttpResponseBadRequest() pos = get_object_or_404(POS, item_id=pos_id) fuelTypeIDs = ( pos.fuel_type_id, constants.STRONTIUM_CLATHRATES_TYPEID, ) fuelTable = [] for type_id in fuelTypeIDs: try: fuel = pos.fuel_levels.filter(type_id=type_id).latest() quantity = fuel.current_fuel() consumption = fuel.consumption except FuelLevel.DoesNotExist: quantity = 0 consumption = 0 if consumption == 0: timeLeft = '-' else: hoursLeft = int(quantity / consumption) timeLeft = print_duration(seconds=hoursLeft * 3600, verbose=False) fuelTable.append([ type_id, Type.objects.get(typeID=type_id).typeName, print_fuel_quantity(quantity), '%d / hour' % consumption, '%d / day' % (consumption * 24), timeLeft, ]) json_data = { "sEcho" : params.sEcho, "iTotalRecords" : len(fuelTypeIDs), "iTotalDisplayRecords" : len(fuelTypeIDs), "aaData" : fuelTable } return HttpResponse(json.dumps(json_data))
def player_contrib_data(request): """ View function URL : '/accounting/contributions/players/data/' """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.from_date = timezone.make_aware(datetime.strptime(REQ.get('from_date', None), DATE_PATTERN), timezone.get_current_timezone()) to_date = datetime.strptime(REQ.get('to_date', None), DATE_PATTERN) if to_date.hour == 0 and to_date.minute == 0 and to_date.second == 0: to_date += timedelta(1) params.to_date = timezone.make_aware(to_date, timezone.get_current_timezone()) except: return HttpResponseBadRequest() contributions = player_contributions(since=params.from_date, until=params.to_date, order_by=columns[params.column], ascending=params.asc) count = len(contributions[:]) contributions = contributions[params.first_id:params.last_id] contrib_list = [] for c in contributions: if c.username == None: contrib_list.append([ tr('not associated'), print_float(c.tax_contrib) ]) else: contrib_list.append([ '<a href="%s" class="player">%s</a>' % (c.get_absolute_url(),c.username), print_float(c.tax_contrib) ]) json_data = { "sEcho" : params.sEcho, "iTotalRecords" : count, "iTotalDisplayRecords" : count, "aaData" : contrib_list } return HttpResponse(json.dumps(json_data))
def player_list_data(request): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() query = User.objects.select_related(depth=2).filter(is_active=True) query = query.annotate(account_count=Count("eve_accounts")) query = query.annotate(char_count=Count("characters")) query = query.annotate(group_count=Count("groups")) query = query.filter(eve_accounts__gt=0) sort_by = PLAYERS_COLUMNS[params.column]['db_field'] # SQL hack for making a case insensitive sort if sort_by == "username": sort_col = "%s_nocase" % sort_by query = query.extra(select={sort_col : 'LOWER("%s")' % sort_by}) else: sort_col = sort_by if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=[sort_col]) if params.search: total_count = query.count() query = query.filter(username__icontains=params.search) filtered_count = query.count() else: total_count = filtered_count = query.count() player_list = [] for player in query[params.first_id:params.last_id]: player_list.append([ '<a href="/hr/players/%d/" class="player">%s</a>' % (player.id, player.username), player.is_staff and player.is_superuser, player.eve_accounts.all().count(), player.characters.all().count(), player.groups.all().count(), print_time_min(player.last_login), print_time_min(player.date_joined) ]) return datatable_ajax_data(player_list, params.sEcho, total_count, filtered_count)
def timers_data(request): try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.display_all = REQ.get('display_all', 'days') except: return HttpResponseBadRequest() timers = Timer.objects.filter(Q(timer__gte=datetime.now(utc))) # Set the sort order if params.column in ordering_map: sort_order = '' sort_order += '-' if not params.asc else '' sort_order += ordering_map[params.column] timers = timers.order_by(sort_order) if not params.display_all: timers = timers.filter(timers__gte=datetime.utcnow()) # Build result list for formatted/labeled data timer_list = [] total_entries = filtered_entries = timers.count() for timer in timers: t = { '0': btn_edit % timer.id + btn_remove % timer.id, '1': link_dotlan % (timer.location_label(), timer.location_label()), '2': timer.structure_label(), '3': timer.cycle_label(), '4': link_dotlan % (timer.location_dotlan(), timer.location) if timer.location else na, '5': timer.owner if timer.owner else na, '6': '<i class="icon-ok"></i>' if timer.friendly else na, '7': timer.timer.strftime('%Y-%m-%d %H:%M:%S'), '8': timer.notes, '9': create_time_remaining(timer.timer), } timer_list.append(t) json_data = { "sEcho" : params.sEcho, "iTotalRecords" : total_entries, "iTotalDisplayRecords" : filtered_entries, "aaData" : timer_list, } return HttpResponse(json.dumps(json_data))
def task_list_data(request): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() tasks = [] query = ScheduledTask.objects.filter(function__in=FUNCTIONS, is_active=True) for task in query.order_by('-priority'): tasks.append([ task.function, task.next_execution_admin_display(), task.frequency_admin_display(), print_time_min(task.last_execution), task.is_last_exec_success, task.is_running, task.is_scheduled, task.as_html() ]) return datatable_ajax_data(tasks, params.sEcho)
def compo_diff_data(request, title_id): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() title = get_object_or_404(Title, pk=int(title_id)) query = TitleCompoDiff.objects.filter(title=title).order_by("-date") total_diffs = query.count() query = query[params.first_id:params.last_id] diff_list = [] for diff in query: diff_list.append([ diff.new, diff.role.permalink, diff.role.roleType.permalink, print_time_min(diff.date) ]) return datatable_ajax_data(diff_list, params.sEcho, total_diffs)
def system_contrib_data(request): """ View function URL : '/accounting/contributions/systems/data/' """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.from_date = timezone.make_aware( datetime.strptime(REQ.get('from_date', None), DATE_PATTERN), timezone.get_current_timezone()) to_date = datetime.strptime(REQ.get('to_date', None), DATE_PATTERN) if to_date.hour == 0 and to_date.minute == 0 and to_date.second == 0: to_date += timedelta(1) params.to_date = timezone.make_aware(to_date, timezone.get_current_timezone()) # In the database query below, we use a BETWEEN operator. # The upper bound 'to_date' will be excluded from the interval # because it is a datetime with time set to 00:00 (beginning of the day). # We add one day in order to include the last day in the interval. except: return HttpResponseBadRequest() contributions = system_contributions(since=params.from_date, until=params.to_date, order_by=columns[params.column], ascending=params.asc) count = len(contributions) contributions = contributions[params.first_id:params.last_id] contrib_list = [] for system, amount in contributions: contrib_list.append(['<b>%s</b>' % system, print_float(amount)]) json_data = { "sEcho": params.sEcho, "iTotalRecords": count, "iTotalDisplayRecords": count, "aaData": contrib_list } return HttpResponse(json.dumps(json_data))
def system_contrib_data(request): """ View function URL : '/accounting/contributions/systems/data/' """ try: params = extract_datatable_params(request) REQ = request.GET if request.method == 'GET' else request.POST params.from_date = timezone.make_aware(datetime.strptime(REQ.get('from_date', None), DATE_PATTERN), timezone.get_current_timezone()) to_date = datetime.strptime(REQ.get('to_date', None), DATE_PATTERN) if to_date.hour == 0 and to_date.minute == 0 and to_date.second == 0: to_date += timedelta(1) params.to_date = timezone.make_aware(to_date, timezone.get_current_timezone()) # In the database query below, we use a BETWEEN operator. # The upper bound 'to_date' will be excluded from the interval # because it is a datetime with time set to 00:00 (beginning of the day). # We add one day in order to include the last day in the interval. except: return HttpResponseBadRequest() contributions = system_contributions(since=params.from_date, until=params.to_date, order_by=columns[params.column], ascending=params.asc) count = len(contributions) contributions = contributions[params.first_id:params.last_id] contrib_list = [] for system, amount in contributions: contrib_list.append([ '<b>%s</b>' % system, print_float(amount) ]) json_data = { "sEcho" : params.sEcho, "iTotalRecords" : count, "iTotalDisplayRecords" : count, "aaData" : contrib_list } return HttpResponse(json.dumps(json_data))
def changes_data(request): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() titles = TitleCompoDiff.objects.select_related( depth=1).all().order_by("-date") count = titles.count() changes = titles[params.first_id:params.last_id] change_list = [] for c in changes: change_list.append([ c.new, c.title.permalink, c.role.permalink, print_time_min(c.date) ]) return datatable_ajax_data(change_list, params.sEcho, total=count)
def history_data(request): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() query = MemberDiff.objects.all() if params.column == 0 or params.column > 3: params.column = 3 params.asc = False sort_col = COLUMNS[params.column]['db_field'] # SQL hack for making a case insensitive sort if params.column in (1, 2): sort_col = sort_col + "_nocase" sort_val = db.fix_mysql_quotes('LOWER("%s")' % COLUMNS[params.column]['db_field']) query = query.extra(select={ sort_col : sort_val }) if not params.asc: sort_col = "-" + sort_col query = query.extra(order_by=([sort_col])) if params.search: total_members = query.count() search_args = Q(name__icontains=params.search) | Q(nickname__icontains=params.search) query = query.filter(search_args) filtered_members = query.count() else: total_members = filtered_members = query.count() members = [] for diff in query[params.first_id:params.last_id]: members.append([ diff.new, diff.permalink, truncate_words(diff.nickname, 5), print_time_min(diff.date) ]) return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def changes_data(request): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() titles = TitleCompoDiff.objects.select_related(depth=1).all().order_by("-date") count = titles.count() changes = titles[params.first_id:params.last_id] change_list = [] for c in changes: change_list.append([ c.new, c.title.permalink, c.role.permalink, print_time_min(c.date) ]) return datatable_ajax_data(change_list, params.sEcho, total=count)
def access_changes_data(request): try: params = extract_datatable_params(request) if params.column == 1: lambda_sort = lambda e: e.member.name.lower() else: lambda_sort = lambda e: e.date except: return HttpResponseBadRequest() roles_query = RoleMemberDiff.objects.select_related(depth=1).all() titles_query = TitleMemberDiff.objects.select_related(depth=1).all() if params.search: total_count = roles_query.count() + titles_query.count() roles_search_args = Q(member__name__icontains=params.search) | Q( role__roleName__icontains=params.search) roles_query = roles_query.filter(roles_search_args) titles_search_args = Q(member__name__icontains=params.search) | Q( title__titleName__icontains=params.search) titles_query = titles_query.filter(titles_search_args) filtered_count = roles_query.count() + titles_query.count() else: total_count = filtered_count = roles_query.count( ) + titles_query.count() changes = list(roles_query) + list(titles_query) changes.sort(key=lambda_sort, reverse=not params.asc) changes = changes[params.first_id:params.last_id] change_list = [] for c in changes: change_list.append([ c.new, c.member_permalink, c.access_permalink, print_time_min(c.date) ]) return datatable_ajax_data(change_list, params.sEcho, total_count, filtered_count)
def access_changes_data(request): try: params = extract_datatable_params(request) if params.column == 1: lambda_sort = lambda e: e.member.name.lower() else: lambda_sort = lambda e: e.date except: return HttpResponseBadRequest() roles_query = RoleMemberDiff.objects.select_related(depth=1).all() titles_query = TitleMemberDiff.objects.select_related(depth=1).all() if params.search: total_count = roles_query.count() + titles_query.count() roles_search_args = Q(member__name__icontains=params.search) | Q(role__roleName__icontains=params.search) roles_query = roles_query.filter(roles_search_args) titles_search_args = Q(member__name__icontains=params.search) | Q(title__titleName__icontains=params.search) titles_query = titles_query.filter(titles_search_args) filtered_count = roles_query.count() + titles_query.count() else: total_count = filtered_count = roles_query.count() + titles_query.count() changes = list(roles_query) + list(titles_query) changes.sort(key=lambda_sort, reverse=not params.asc) changes = changes[params.first_id:params.last_id] change_list = [] for c in changes: change_list.append([ c.new, c.member_permalink, c.access_permalink, print_time_min(c.date) ]) return datatable_ajax_data(change_list, params.sEcho, total_count, filtered_count)
def player_details_data(request, player_id): try: params = extract_datatable_params(request) except KeyError: return HttpResponseBadRequest() player = get_object_or_404(User, id=int(player_id)) total_members,\ filtered_members,\ members = get_members(query=Member.objects.filter(owner=player), first_id=params.first_id, last_id=params.last_id, search_str=params.search, sort_by=params.column, asc=params.asc) json_data = { "sEcho": params.sEcho, "iTotalRecords": total_members, "iTotalDisplayRecords": filtered_members, "aaData": members } return HttpResponse(json.dumps(json_data))
def members_data(request): try: params = extract_datatable_params(request) ships = request.GET.get('show_ships', 'all') corp_id = request.GET.get('corp') except KeyError: return HttpResponseBadRequest() if corp_id: try: query = Corporation.objects.get(corporationID=int(corp_id)).members.all() except Corporation.DoesNotExist: query = Corporation.objects.mine().members.all() except ValueError: # corp_id cannot be casted to int, we take all corps query = Member.objects.exclude(corp=None) else: query = Corporation.objects.mine().members.all() if ships == 'supers': query = query.filter(ship__in=SUPER_CAPITALS) total_members,\ filtered_members,\ members = get_members(query=query, first_id=params.first_id, last_id=params.last_id, search_str=params.search, sort_by=params.column, asc=params.asc, for_csv=params.format == 'csv') if params.format == 'csv': return datatable_csv_data(members, filename='members.csv') else: return datatable_ajax_data(members, params.sEcho, total_members, filtered_members)
def access_changes_member_data(request, characterID): try: params = extract_datatable_params(request) except: return HttpResponseBadRequest() roles = RoleMemberDiff.objects.filter(member=characterID).order_by("-id") titles = TitleMemberDiff.objects.filter(member=characterID).order_by("-id") count = roles.count() + titles.count() changes = list(roles) + list(titles) changes.sort(key=lambda e: e.date, reverse=True) changes = changes[params.first_id:params.last_id] change_list = [] for change in changes: change_list.append([ change.new, change.access_permalink, print_time_min(change.date) ]) return datatable_ajax_data(change_list, params.sEcho, count)