def render_change(self, record): """Fixes cost col when balance < 0. We have an issue where sub balances can go negative due to problems with the billing system. Negative balances cause events that cost X *appear* to cost X - the subscriber's balance. """ if record.oldamt < 0 and record.kind != 'add_money': return humanize_credits(0, CURRENCIES[record.network.subscriber_currency]) else: return humanize_credits(record.change, CURRENCIES[record.network.subscriber_currency])
def humanize_credits(amount_raw): """Given a raw amount from the subscriber registry, this will return a human readable Money instance in the local Currency. """ currency_code = configdb['currency_code'] money = currency.humanize_credits(amount_raw, currency.CURRENCIES[currency_code]) return money
def currency(context, amount, *args, **kwargs): if 'unit' in kwargs: currency = CURRENCIES[kwargs['unit']] else: currency = context['currency'] money = humanize_credits(amount, currency) if 'amount_only' in kwargs and kwargs['amount_only']: return money.amount_str() return money
def render_balance(record): """Show the subscriber's balance in a humanized currency.""" return humanize_credits(record.balance, CURRENCIES[record.network.subscriber_currency])
def render_newamt(self, record): return humanize_credits(record.newamt, CURRENCIES[record.network.subscriber_currency])
def _handle_request(self, request): """Process request. We want filters to persist even when someone changes pages without re-submitting the form. Page changes will always come over a GET request, not a POST. - If it's a GET, we should try to pull settings from the session. - If it's a POST, we should replace whatever is in the session. - If it's a GET with no page, we should blank out the session. """ profile = UserProfile.objects.get(user=request.user) network = profile.network # Process parameters. # We want filters to persist even when someone changes pages without # re-submitting the form. Page changes will always come over a GET # request, not a POST. # - If it's a GET, we should try to pull settings from the session. # - If it's a POST, we should replace whatever is in the session. # - If it's a GET with no page variable, we should blank out the # session. if request.method == "POST": page = 1 request.session['keyword'] = request.POST.get('keyword', None) request.session['start_date'] = request.POST.get( 'start_date', None) request.session['end_date'] = request.POST.get('end_date', None) request.session['services'] = request.POST.getlist( 'services[]', None) # Added to check password to download the csv if (request.user.check_password(request.POST.get('password'))): response = {'status': 'ok'} return HttpResponse(json.dumps(response), content_type="application/json") # We always just do a redirect to GET. We include page reference # to retain the search parameters in the session. return redirect( urlresolvers.reverse('network-activity') + "?page=1") elif request.method == "GET": page = request.GET.get('page', 1) if 'page' not in request.GET: # Reset filtering params. request.session['keyword'] = None request.session['start_date'] = None request.session['end_date'] = None request.session['services'] = None else: return HttpResponseBadRequest() # Determine if there has been any activity on the network (if not, we # won't show the filter boxes). network_has_activity = UsageEvent.objects.filter( network=network).exists() # Read filtering params out of the session. keyword = request.session['keyword'] start_date = request.session['start_date'] end_date = request.session['end_date'] services = request.session['services'] events = self._get_events(profile, keyword, start_date, end_date, services) event_count = events.count() currency = CURRENCIES[network.subscriber_currency] # If a CSV has been requested, return that here. # TODO(shaddi): Kind of a hack, probably should be exposed as REST API if request.method == "GET" and request.GET.get('csv', False): headers = [ 'Transaction ID', 'Day', 'Time', 'Time Zone', 'Subscriber IMSI', 'BTS Identifier', 'BTS Name', 'Type of Event', 'Description', 'From Number', 'To Number', 'Billable Call Duration (sec)', 'Total Call Duration (sec)', 'Tariff (%s)' % (currency, ), 'Cost (%s)' % (currency, ), 'Prior Balance (%s)' % (currency, ), 'Final Balance (%s)' % (currency, ), 'Bytes Uploaded', 'Bytes Downloaded', ] response = HttpResponse(content_type='text/csv') # TODO(shaddi): use a filename that captures the search terms? response['Content-Disposition'] = ('attachment;filename=' '"etage-%s.csv"') \ % (datetime.datetime.now().date(),) writer = csv.writer(response) writer.writerow(headers) # Forcibly limit to 7000 items. timezone = pytz.timezone(profile.timezone) for e in events[:7000]: #first strip the IMSI off if present subscriber = e.subscriber_imsi if e.subscriber_imsi.startswith('IMSI'): subscriber = e.subscriber_imsi[4:] tz_date = django_utils_timezone.localtime(e.date, timezone) writer.writerow([ e.transaction_id, tz_date.date().strftime("%m-%d-%Y"), tz_date.time().strftime("%I:%M:%S %p"), timezone, subscriber, e.bts_uuid, e.bts.nickname if e.bts else "<deleted BTS>", e.kind, e.reason, e.from_number, e.to_number, e.billsec, e.call_duration, humanize_credits(e.tariff, currency=currency).amount_str() if e.tariff else None, humanize_credits(e.change, currency=currency).amount_str() if e.change else None, humanize_credits(e.oldamt, currency=currency).amount_str() if e.oldamt else None, humanize_credits(e.newamt, currency=currency).amount_str() if e.newamt else None, e.uploaded_bytes, e.downloaded_bytes, ]) return response # Otherwise, we paginate. event_paginator = Paginator(events, 25) try: events = event_paginator.page(page) except PageNotAnInteger: # If page is not an integer, deliver first page. events = event_paginator.page(1) except EmptyPage: # If page is out of range (e.g. 999), deliver last page of results. events = event_paginator.page(event_paginator.num_pages) # Setup the context for the template. context = { 'networks': get_objects_for_user(request.user, 'view_network', klass=Network), 'currency': CURRENCIES[network.subscriber_currency], 'user_profile': profile, 'network_has_activity': network_has_activity, 'events': events, 'event_count': event_count, } # Setup various stuff for filter form generation. service_names = ["SMS", "Call", "GPRS", "Transfer", "Other"] if not services: context['service_types'] = [("SMS", True), ("Call", True), ("GPRS", True), ("Transfer", True), ("Other", True)] else: context['service_types'] = [] for name in service_names: if name.lower() in services: context['service_types'].append((name, True)) else: context['service_types'].append((name, False)) context['eventfilter'] = { 'keyword': keyword, 'start_date': start_date, 'end_date': end_date } template = get_template('dashboard/activity.html') html = template.render(context, request) return HttpResponse(html)
def get(self, request): """Handles GET requests.""" user_profile = models.UserProfile.objects.get(user=request.user) network = user_profile.network currency = network.subscriber_currency # Count the associated denomination with selected network. denom = models.NetworkDenomination.objects.filter(network=network) denom_count = denom.count() dnm_id = request.GET.get('id', None) if dnm_id: response = {'status': 'ok', 'messages': [], 'data': {}} denom = models.NetworkDenomination.objects.get(id=dnm_id) denom_data = { 'id': denom.id, 'start_amount': humanize_credits(denom.start_amount, CURRENCIES[currency]).amount, 'end_amount': humanize_credits(denom.end_amount, CURRENCIES[currency]).amount, 'validity_days': denom.validity_days } response["data"] = denom_data return http.HttpResponse(json.dumps(response), content_type="application/json") # Configure the table of denominations. Do not show any pagination # controls if the total number of donominations is small. if not user_profile.user.is_staff: denom_table = django_tables.DenominationListTable(list(denom)) else: denom_table = django_tables.DenominationTable(list(denom)) towers_per_page = 8 paginate = False if denom > towers_per_page: paginate = {'per_page': towers_per_page} tables.RequestConfig(request, paginate=paginate).configure(denom_table) # Set the context with various stats. context = { 'networks': get_objects_for_user(request.user, 'view_network', klass=models.Network), 'currency': CURRENCIES[user_profile.network.subscriber_currency], 'user_profile': user_profile, 'network': network, 'number_country': NUMBER_COUNTRIES[network.number_country], 'denomination': denom_count, 'denominations_table': denom_table, } # Render template. info_template = template.loader.get_template( 'dashboard/network_detail/denomination.html') html = info_template.render(context, request) return http.HttpResponse(html)
def render_start_amount(self, record): return humanize_credits(record.start_amount, CURRENCIES[record.network.subscriber_currency])