<commit_before>#
# CDR-Stats License
# http://www.cdr-stats.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2013 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# <NAME> <<EMAIL>>
#
from django.contrib.auth.decorators import login_required, permission_required
from django.views.decorators.cache import cache_page
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.conf import settings
from django.template.context import RequestContext
from voip_billing.models import VoIPRetailRate
from voip_billing.forms import PrefixRetailRrateForm, SimulatorForm, DailyBillingForm,\
    HourlyBillingForm
from voip_billing.function_def import prefix_allowed_to_call, get_rounded_value
from voip_billing.rate_engine import rate_engine
from voip_billing.constants import RATE_COLUMN_NAME
from mongodb_connection import mongodb
from cdr.decorators import check_cdr_exists, check_user_accountcode, \
    check_user_voipplan
from cdr.aggregate import pipeline_daily_billing_report, pipeline_hourly_billing_report
from common.common_functions import current_view, ceil_strdate, get_pagination_vars
from common.common_constants import EXPORT_CHOICE
from datetime import datetime
import logging
import time
import requests
import ast
import tablib


@permission_required('user_profile.call_rate', login_url='/')
@login_required
@check_user_voipplan
@cache_page(60 * 5)
def voip_rates(request):
    """List voip call rates according to country prefix

    **Attributes**:

        * ``template`` - voip_billing/rates.html
        * ``form`` - PrefixRetailRrateForm

    **Logic Description**:

        get all call rates from voip rate API and list them in template
        with pagination & sorting column
    """
    template = 'voip_billing/rates.html'
    form = PrefixRetailRrateForm()
    final_rate_list = []
    # Get pagination data
    sort_col_field_list = ['prefix', 'retail_rate', 'destination']
    default_sort_field = 'prefix'
    pagination_data =\
        get_pagination_vars(request, sort_col_field_list, default_sort_field)

    PAGE_SIZE = pagination_data['PAGE_SIZE']
    sort_order = pagination_data['sort_order']

    order = 'ASC'
    if "-" in sort_order:
        order = 'DESC'
        sort_order = sort_order[1:]

    dialcode = ''
    if request.method == 'POST':
        form = PrefixRetailRrateForm(request.POST)
        if form.is_valid():
            dialcode = request.POST.get('prefix')
            request.session['dialcode'] = dialcode
    else:
        # pagination with prefix code
        if (request.session.get('dialcode') and
           (request.GET.get('page') or request.GET.get('sort_by'))):
            dialcode = request.session.get('dialcode')
            form = PrefixRetailRrateForm(initial={'prefix': dialcode})
        else:
            # Reset variables
            request.session['dialcode'] = ''
            request.session['final_rate_list'] = ''
            dialcode = ''

    if dialcode:
        response = requests.get('http://localhost:8000/api/v1/voip_rate/?dialcode=%s&sort_field=%s&sort_order=%s' % (dialcode, sort_order, order),
            auth=(request.user, request.user))
    else:
        # Default listing or rate
        response = requests.get('http://localhost:8000/api/v1/voip_rate/?sort_field=%s&sort_order=%s' % (sort_order, order),
            auth=(request.user, request.user))

    rate_list = response.content
    # due to string response of API, we need to convert response in to array
    rate_list = rate_list.replace('[', '').replace(']', '').replace('}, {', '}|{').split('|')
    for i in rate_list:
        # convert string into dict
        final_rate_list.append(ast.literal_eval(i))

    request.session['final_rate_list'] = final_rate_list

    variables = RequestContext(request, {
        'module': current_view(request),
        'form': form,
        'user': request.user,
        'rate_list': final_rate_list,
        'rate_list_count': len(final_rate_list),
        'col_name_with_order': pagination_data['col_name_with_order'],
        'PAGE_SIZE': PAGE_SIZE,
        'RATE_COLUMN_NAME': RATE_COLUMN_NAME,
        'sort_order': sort_order,
    })
    return render_to_response(template, variables,
           context_instance=RequestContext(request))


@permission_required('user_profile.export_call_rate', login_url='/')
@login_required
def export_rate(request):
    """
    **Logic Description**:<commit_msg>fix static URL + check API status result ensure the api result is 200 status<commit_after>#
# CDR-Stats License
# http://www.cdr-stats.org
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Copyright (C) 2011-2013 Star2Billing S.L.
#
# The Initial Developer of the Original Code is
# <NAME> <<EMAIL>>
#
from django.contrib.auth.decorators import login_required, permission_required
from django.views.decorators.cache import cache_page
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.conf import settings
from django.template.context import RequestContext
from voip_billing.models import VoIPRetailRate
from voip_billing.forms import PrefixRetailRrateForm, SimulatorForm, DailyBillingForm,\
    HourlyBillingForm
from voip_billing.function_def import prefix_allowed_to_call, get_rounded_value
from voip_billing.rate_engine import rate_engine
from voip_billing.constants import RATE_COLUMN_NAME
from mongodb_connection import mongodb
from cdr.decorators import check_cdr_exists, check_user_accountcode, \
    check_user_voipplan
from cdr.aggregate import pipeline_daily_billing_report, pipeline_hourly_billing_report
from common.common_functions import current_view, ceil_strdate, get_pagination_vars
from common.common_constants import EXPORT_CHOICE
from datetime import datetime
import logging
import time
import requests
import ast
import tablib


@permission_required('user_profile.call_rate', login_url='/')
@login_required
@check_user_voipplan
@cache_page(60 * 5)
def voip_rates(request):
    """List voip call rates according to country prefix

    **Attributes**:

        * ``template`` - voip_billing/rates.html
        * ``form`` - PrefixRetailRrateForm

    **Logic Description**:

        get all call rates from voip rate API and list them in template
        with pagination & sorting column
    """
    template = 'voip_billing/rates.html'
    form = PrefixRetailRrateForm()
    final_rate_list = []
    # Get pagination data
    sort_col_field_list = ['prefix', 'retail_rate', 'destination']
    default_sort_field = 'prefix'
    pagination_data =\
        get_pagination_vars(request, sort_col_field_list, default_sort_field)

    PAGE_SIZE = pagination_data['PAGE_SIZE']
    sort_order = pagination_data['sort_order']

    order = 'ASC'
    if "-" in sort_order:
        order = 'DESC'
        sort_order = sort_order[1:]

    dialcode = ''
    if request.method == 'POST':
        form = PrefixRetailRrateForm(request.POST)
        if form.is_valid():
            dialcode = request.POST.get('prefix')
            request.session['dialcode'] = dialcode
    else:
        # pagination with prefix code
        if (request.session.get('dialcode') and
           (request.GET.get('page') or request.GET.get('sort_by'))):
            dialcode = request.session.get('dialcode')
            form = PrefixRetailRrateForm(initial={'prefix': dialcode})
        else:
            # Reset variables
            request.session['dialcode'] = ''
            request.session['final_rate_list'] = ''
            dialcode = ''
    full_url = request.build_absolute_uri('/')
    if dialcode:
        api_url = full_url + 'api/v1/voip_rate/?dialcode=%s&sort_field=%s&sort_order=%s' % (dialcode, sort_order, order)
        response = requests.get(api_url, auth=(request.user, request.user))
    else:
        # Default listing or rate
        api_url = full_url + 'api/v1/voip_rate/?sort_field=%s&sort_order=%s' % (sort_order, order)
        response = requests.get(api_url, auth=(request.user, request.user))

    if response.status_code == 200:
        rate_list = response.content
        # due to string response of API, we need to convert response in to array
        rate_list = rate_list.replace('[', '').replace(']', '').replace('}, {', '}|{').split('|')
        for i in rate_list:
            # convert string into dict
            final_rate_list.append(ast.literal_eval(i))

    request.session['final_rate_list'] = final_rate_list

    variables = RequestContext(request, {
        'module': current_view(request),
        'form': form,
        'user': request.user,
        'rate_list': final_rate_list,
        'rate_list_count': len(final_rate_list),
        'col_name_with_order': pagination_data['col_name_with_order'],
        'PAGE_SIZE': PAGE_SIZE,
        'RATE_COLUMN_NAME': RATE_COLUMN_NAME,
        'sort_order': sort_order,
    })
    return render_to_response(template, variables,
           context_instance=RequestContext(request))


@permission_required('user_profile.export_call_rate', login_url='/')
@login_required
def export_rate(request):
    """
    **Logic Description**:
{'fraction_non_alphanumeric': 0.10354685018528322, 'fraction_numerical': 0.005505558496559026, 'mean_word_length': 3.6808721506442024, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5262786', 'n_tokens_mistral': 2924, 'n_tokens_neox': 2834, 'n_words': 681}