Esempio n. 1
0
def voipcall_record_common_fun(request):
    """Return Form with Initial data or Array (kwargs) for Voipcall_Report
    Changelist_view"""
    start_date = ''
    end_date = ''
    start_date = getvar(request, 'from_date')
    end_date = getvar(request, 'to_date')

    # Assign form field value to local variable
    disposition = getvar(request, 'status')
    campaign_id = getvar(request, 'campaign_id')
    leg_type = getvar(request, 'leg_type')

    kwargs = {}
    if start_date and end_date:
        kwargs['starting_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['starting_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['starting_date__lte'] = end_date

    if disposition and disposition != 'all':
        kwargs['disposition__exact'] = disposition

    if campaign_id and campaign_id != '0':
        kwargs['callrequest__campaign_id'] = campaign_id

    if leg_type and leg_type != '':
        kwargs['leg_type__exact'] = leg_type

    if len(kwargs) == 0:
        tday = datetime.today()
        kwargs['starting_date__gte'] = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        kwargs['starting_date__lte'] = datetime(tday.year, tday.month, tday.day, 23, 59, 59).replace(tzinfo=utc)
    return kwargs
Esempio n. 2
0
def voipcall_search_admin_form_fun(request):
    """Return query string for Voipcall_Report Changelist_view"""
    start_date = ''
    end_date = ''
    if request.POST.get('from_date'):
        start_date = request.POST.get('from_date')

    if request.POST.get('to_date'):
        end_date = request.POST.get('to_date')

    # Assign form field value to local variable
    disposition = getvar(request, 'status')
    campaign_id = getvar(request, 'campaign_id')
    leg_type = getvar(request, 'leg_type')
    query_string = ''

    if start_date and end_date:
        date_string = 'starting_date__gte=' + start_date + \
            '&starting_date__lte=' + end_date + '+23%3A59%3A59'
        query_string = return_query_string(query_string, date_string)

    if start_date and end_date == '':
        date_string = 'starting_date__gte=' + start_date
        query_string = return_query_string(query_string, date_string)

    if start_date == '' and end_date:
        date_string = 'starting_date__lte=' + end_date
        query_string = return_query_string(query_string, date_string)

    if disposition and disposition != 'all':
        disposition_string = 'disposition__exact=' + disposition
        query_string = return_query_string(query_string, disposition_string)

    if campaign_id and campaign_id != '0':
        campaign_string = 'callrequest__campaign_id=' + str(campaign_id)
        query_string = return_query_string(query_string, campaign_string)

    if leg_type and leg_type != '':
        leg_type_string = 'leg_type__exact=' + str(leg_type)
        query_string = return_query_string(query_string, leg_type_string)

    if start_date == '' and end_date == '':
        tday = datetime.today()
        end_date = start_date = tday.strftime("%Y-%m-%d")
        date_string = 'starting_date__gte=' + start_date + \
            '&starting_date__lte=' + end_date + '+23%3A59%3A59'
        query_string = return_query_string(query_string, date_string)

    return query_string
Esempio n. 3
0
def cdr_realtime(request):
    """Call realtime view

    **Attributes**:

        * ``template`` - cdr/realtime.html
        * ``form`` - SwitchForm
        * ``mongodb_collection`` - MONGO_CDRSTATS['CONC_CALL_AGG'] (map-reduce collection)

    **Logic Description**:

        get all call records from mongodb collection for
        concurrent analytics
    """
    logging.debug("CDR realtime view start")
    query_var = {}
    switch_id = 0
    list_switch = Switch.objects.all()
    form = SwitchForm(request.POST or None)
    if form.is_valid():
        switch_id = int(getvar(request, "switch_id"))
        if switch_id and switch_id != 0:
            query_var["value.switch_id"] = switch_id

    now = datetime.now()
    start_date = datetime(now.year, now.month, now.day, 0, 0, 0, 0)
    end_date = datetime(now.year, now.month, now.day, 23, 59, 59, 999999)

    query_var["value.call_date"] = {"$gte": start_date, "$lt": end_date}
    if not request.user.is_superuser:  # not superuser
        query_var["value.accountcode"] = request.user.userprofile.accountcode

    # calls_in_day = mongodb.conc_call_agg.find(query_var).sort([('_id.g_Millisec', -1)])
    calls_in_day = {}

    final_data = []
    for d in calls_in_day:
        dt = int(d["_id"]["g_Millisec"])
        final_data.append((dt, int(d["value"]["numbercall__max"])))

    logging.debug("Realtime view end")
    variables = {
        "form": form,
        "final_data": final_data,
        "list_switch": list_switch,
        "colorgraph1": "180, 0, 0",
        "colorgraph2": "0, 180, 0",
        "colorgraph3": "0, 0, 180",
        "realtime_graph_maxcall": settings.REALTIME_Y_AXIS_LIMIT,
    }
    return render_to_response("cdr/graph_realtime.html", variables, context_instance=RequestContext(request))
Esempio n. 4
0
def cdr_daily_comparison(request):
    """
    Hourly CDR graph that compare with previous dates

    **Attributes**:

        * ``template`` - cdr/daily_comparison.html
        * ``form`` - CompareCallSearchForm

    **Logic Description**:

        get the call records aggregated from the CDR table
        using the materialized view and compare with other date records


    # hourly_charttype = "lineWithFocusChart"
    # daily_charttype = "lineWithFocusChart"
    # hourly_chartdata = {'x': []}
    # daily_chartdata = {'x': []}
    # metric = 'nbcalls'  # Default metric

    """
    # Default
    metric = 'nbcalls'
    switch_id = 0
    hourly_charttype = "multiBarChart"
    hourly_chartdata = {'x': []}
    compare_days = 2
    compare_type = COMPARE_WITH.previous_days
    today_date = datetime.today()
    form = CompareCallSearchForm(request.POST or None,
                                 initial={'from_date': today_date.strftime('%Y-%m-%d'),
                                          'compare_days': compare_days,
                                          'compare_type': compare_type,
                                          'switch_id': 0})

    today_date = datetime(today_date.year, today_date.month, today_date.day)
    current_date = today_date

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        current_date = ceil_strdate(str(from_date), 'start')
        # current_date = trunc_date_start(from_date)
        switch_id = getvar(request, 'switch_id')
        compare_days = int(getvar(request, 'compare_days'))
        metric = getvar(request, 'metric')

    kwargs = {}

    if switch_id and switch_id != '0':
        kwargs['switch_id'] = int(switch_id)

    xdata = [i for i in range(0, 24)]
    hourly_chartdata = {'x': xdata}

    y_count = 1
    for nday in range(1, compare_days + 1):
        start_date = current_date + relativedelta(days=-int(nday-1))
        start_date = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0, 0)
        end_date = current_date + relativedelta(days=-int(nday-1))
        end_date = datetime(end_date.year, end_date.month, end_date.day, 23, 59, 59, 999999)
        # Get hourly Data
        hourly_data = get_report_compare_cdr(request.user, 'hour', start_date, end_date, switch_id)

        extra_serie = {
            "tooltip": {"y_start": "", "y_end": " " + metric}
        }
        # We only need to set x axis once, so let's do it for nbcalls
        # hourly_chartdata['x'] = hourly_data["nbcalls"]["x_timestamp"]
        for switch in hourly_data[metric]["columns"]:
            serie = get_switch_ip_addr(switch) + "_day_" + str(nday)
            hourly_chartdata['name' + str(y_count)] = serie
            hourly_chartdata['y' + str(y_count)] = hourly_data[metric]["values"][str(switch)]
            hourly_chartdata['extra' + str(y_count)] = extra_serie
            y_count += 1

    variables = {
        'form': form,
        'from_date': current_date,
        'metric': metric,
        'compare_days': compare_days,
        'hourly_charttype': hourly_charttype,
        'hourly_chartdata': hourly_chartdata,
        'hourly_chartcontainer': 'hourly_chartcontainer',
        'hourly_extra': {
            'x_is_date': False,
            'x_axis_format': '',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
    }
    return render_to_response('cdr/daily_comparison.html', variables, context_instance=RequestContext(request))
Esempio n. 5
0
def cdr_country_report(request):
    """CDR country report

    **Attributes**:

        * ``template`` - cdr/country_report.html
        * ``form`` - CountryReportForm

    **Logic Description**:

        Retrieve call records from Postgresql for all countries
        and create reporting information for those countries
    """
    metric = 'nbcalls'
    tday = datetime.today()

    switch_id = 0
    hourly_charttype = "lineWithFocusChart"
    hourly_chartdata = {'x': []}
    country_id_list = []
    total_metric = 0

    # assign initial value in form fields
    form = CountryReportForm(request.POST or None,
                             initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                    'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                    'switch_id': switch_id})

    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')
        metric = getvar(request, 'metric')
        country_id = form.cleaned_data['country_id']
        # convert list value in int
        country_id_list = [int(row) for row in country_id]
        # handle 0 (All) selection
        if 0 in country_id_list:
            country_id_list = []

    # check metric is valid
    if metric not in ['nbcalls', 'duration', 'billsec', 'buy_cost', 'sell_cost']:
        metric = 'nbcalls'

    hourly_data = get_report_cdr_per_country(request.user, 'hour', start_date, end_date, switch_id, country_id_list)

    extra_serie = {
        "tooltip": {"y_start": "", "y_end": " " + metric},
        "date_format": "%d %b %y %H:%M%p"
    }
    for country in hourly_data[metric]["columns"]:
        hourly_chartdata['x'] = hourly_data[metric]["x_timestamp"]
        country_name = get_country_name(int(country)).encode('utf-8')
        hourly_chartdata['name' + str(country)] = country_name.decode('ascii', 'ignore').replace("'", " ")
        hourly_chartdata['y' + str(country)] = hourly_data[metric]["values"][str(country)]
        hourly_chartdata['extra' + str(country)] = extra_serie

    total_calls = hourly_data["nbcalls"]["total"]
    total_duration = hourly_data["duration"]["total"]
    total_billsec = hourly_data["billsec"]["total"]
    total_buy_cost = hourly_data["buy_cost"]["total"]
    total_sell_cost = hourly_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    top_country = 10
    country_data = custom_sql_aggr_top_country(request.user, switch_id, top_country, start_date, end_date)

    # Build pie chart data for last 24h calls per country
    (xdata, ydata) = ([], [])
    for country in country_data:
        xdata.append(get_country_name(country["country_id"]))
        ydata.append(percentage(country["nbcalls"], total_calls))

    color_list = ['#FFC36C', '#FFFF9D', '#BEEB9F', '#79BD8F', '#FFB391',
        '#58A6A6', '#86BF30', '#F2D022', '#D9AA1E', '#D98236']

    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    country_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    country_analytic_charttype = "pieChart"

    country_extra = {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
    }

    data = {
        'action': 'tabs-1',
        'total_metric': total_metric,
        'start_date': start_date,
        'end_date': end_date,
        'metric': metric,
        'form': form,
        'NUM_COUNTRY': settings.NUM_COUNTRY,
        'hourly_charttype': hourly_charttype,
        'hourly_chartdata': hourly_chartdata,
        'hourly_chartcontainer': 'hourly_container',
        'hourly_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': False,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,

        'country_analytic_charttype': country_analytic_charttype,
        'country_analytic_chartdata': country_analytic_chartdata,
        'country_chartcontainer': 'country_piechart_container',
        'country_extra': country_extra,
        'top_country': top_country,
    }
    return render_to_response('cdr/country_report.html', data, context_instance=RequestContext(request))
Esempio n. 6
0
def dnc_contact_list(request):
    """DNC Contact list for the logged in user

    **Attributes**:

        * ``template`` - dnc/dnc_contact/list.html
        * ``form`` - ContactSearchForm

    **Logic Description**:

        * List all dnc contacts from dnc lists belonging to the logged in user
    """
    sort_col_field_list = ['id', 'dnc', 'phone_number', 'updated_date']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')
    form = DNCContactSearchForm(request.user, request.POST or None)
    dnc_id_list = DNC.objects.values_list('id', flat=True).filter(user=request.user)
    phone_number = ''
    dnc = ''
    post_var_with_page = 0
    if form.is_valid():
        request.session['session_phone_number'] = ''
        request.session['session_dnc'] = ''
        post_var_with_page = 1
        phone_number = getvar(request, 'phone_number', setsession=True)
        dnc = getvar(request, 'dnc', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        phone_number = request.session.get('session_phone_number')
        dnc = request.session.get('session_dnc')
        form = DNCContactSearchForm(request.user, initial={'phone_number': phone_number, 'dnc': dnc})

    if post_var_with_page == 0:
        # default
        # unset session var
        request.session['session_phone_number'] = ''
        request.session['session_dnc'] = ''

    kwargs = {'dnc__in': dnc_id_list}
    if dnc and dnc != '0':
        kwargs['dnc_id'] = dnc

    phone_number_type = '1'
    phone_number = source_desti_field_chk(phone_number, phone_number_type, 'phone_number')
    for i in phone_number:
        kwargs[i] = phone_number[i]

    phone_number_list = []
    all_phone_number_list = []
    phone_number_count = 0

    if dnc_id_list:
        all_phone_number_list = DNCContact.objects.values(
            'id', 'dnc__name', 'phone_number', 'updated_date').filter(**kwargs).order_by(pag_vars['sort_order'])

        phone_number_list = all_phone_number_list[pag_vars['start_page']:pag_vars['end_page']]
        phone_number_count = all_phone_number_list.count()

    data = {
        'phone_number_list': phone_number_list,
        'all_phone_number_list': all_phone_number_list,
        'total_phone_numbers': phone_number_count,
        'DNC_CONTACT_COLUMN_NAME': DNC_CONTACT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'form': form,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dnc/dnc_contact/list.html', data, context_instance=RequestContext(request))
Esempio n. 7
0
def cdr_dashboard(request):
    """CDR dashboard on the last 24 hours

    **Attributes**:

        * ``template`` - cdr/dashboard.html
        * ``form`` - SwitchForm

    **Logic Description**:

        Display calls aggregated information for the last 24hours, several report will be
        created and displayed such as hourly call report and hangup cause/country analytics.
    """
    logging.debug('CDR dashboard view start')
    form = SwitchForm(request.POST or None)

    if form.is_valid():
        logging.debug('CDR dashboard view with search option')
        switch_id = int(getvar(request, 'switch_id'))
    else:
        switch_id = 0

    # Get list of calls/duration for each of the last 24 hours
    (calls_hour_aggr, total_calls, total_duration, total_billsec, total_buy_cost, total_sell_cost) = custom_sql_matv_voip_cdr_aggr_last24hours(request.user, switch_id)

    # Build chart data for last 24h calls
    (xdata, ydata, ydata2, ydata3, ydata4, ydata5) = ([], [], [], [], [], [])
    for i in calls_hour_aggr:
        start_time = (time.mktime(calls_hour_aggr[i]['calltime'].timetuple()) * 1000)
        xdata.append(start_time)
        ydata.append(int(calls_hour_aggr[i]['nbcalls']))
        ydata2.append(int(calls_hour_aggr[i]['duration']/60))
        ydata3.append(int(calls_hour_aggr[i]['billsec']/60))
        ydata4.append(int(calls_hour_aggr[i]['buy_cost']))
        ydata5.append(int(calls_hour_aggr[i]['sell_cost']))

    tooltip_date = "%d %b %y %H:%M %p"
    extra_serie1 = {"tooltip": {"y_start": "", "y_end": " calls"}, "date_format": tooltip_date}
    extra_serie2 = {"tooltip": {"y_start": "", "y_end": " min"}, "date_format": tooltip_date}
    extra_serie3 = {"tooltip": {"y_start": "", "y_end": " min"}, "date_format": tooltip_date}
    extra_serie4 = {"tooltip": {"y_start": "", "y_end": ""}, "date_format": tooltip_date}
    extra_serie5 = {"tooltip": {"y_start": "", "y_end": ""}, "date_format": tooltip_date}

    kwargs1 = {}
    kwargs1['bar'] = True

    final_chartdata = {
        'x': xdata,
        'name1': 'Calls', 'y1': ydata, 'extra1': extra_serie1, 'kwargs1': kwargs1,
        'name2': 'Duration', 'y2': ydata2, 'extra2': extra_serie2,
        'name3': 'Billsec', 'y3': ydata3, 'extra3': extra_serie3,
        'name4': 'Buy cost', 'y4': ydata4, 'extra4': extra_serie4,
        'name5': 'Sell cost', 'y5': ydata5, 'extra5': extra_serie5,
    }
    final_charttype = "linePlusBarChart"

    # Get top 5 of country calls for last 24 hours
    country_data = custom_sql_aggr_top_country_last24hours(request.user, switch_id, limit=5)

    # Build pie chart data for last 24h calls per country
    (xdata, ydata) = ([], [])
    for country in country_data:
        xdata.append(get_country_name(country["country_id"]))
        ydata.append(percentage(country["nbcalls"], total_calls))

    color_list = ['#FFC36C', '#FFFF9D', '#BEEB9F', '#79BD8F', '#FFB391']
    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    country_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    country_analytic_charttype = "pieChart"

    country_extra = {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
    }

    # Get top 10 of hangup cause calls for last 24 hours
    hangup_cause_data = custom_sql_aggr_top_hangup_last24hours(request.user, switch_id)

    # hangup analytic pie chart data
    (xdata, ydata) = ([], [])
    for hangup_cause in hangup_cause_data:
        xdata.append(str(get_hangupcause_name(hangup_cause["hangup_cause_id"])))
        ydata.append(str(percentage(hangup_cause["nbcalls"], total_calls)))

    color_list = ['#2A343F', '#7E8282', '#EA9664', '#30998F', '#449935']
    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    hangup_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    hangup_analytic_charttype = "pieChart"

    hangup_extra = country_extra

    logging.debug("Result calls_hour_aggr %d" % len(calls_hour_aggr))
    logging.debug("Result hangup_cause_data %d" % len(hangup_cause_data))
    logging.debug("Result country_data %d" % len(country_data))

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    final_extra = {
        'x_is_date': True,
        'x_axis_format': '%H:%M',
        # 'x_axis_format': '%d %b %Y',
        'tag_script_js': True,
        'jquery_on_ready': True,
        'focus_enable': True,
    }

    logging.debug('CDR dashboard view end')
    variables = {
        'total_calls': total_calls,
        'total_duration': int_convert_to_minute(total_duration),
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
        'hangup_analytic': hangup_cause_data,
        'form': form,
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_chartcontainer': 'final_container',
        'final_extra': final_extra,
        'hangup_analytic_charttype': hangup_analytic_charttype,
        'hangup_analytic_chartdata': hangup_analytic_chartdata,
        'hangup_chartcontainer': 'hangup_piechart_container',
        'hangup_extra': hangup_extra,
        'country_analytic_charttype': country_analytic_charttype,
        'country_analytic_chartdata': country_analytic_chartdata,
        'country_chartcontainer': 'country_piechart_container',
        'country_extra': country_extra,
    }
    return render_to_response('cdr/dashboard.html', variables, context_instance=RequestContext(request))
Esempio n. 8
0
def cdr_view(request):
    """List of CDRs

    **Attributes**:

        * ``template`` - cdr/list.html
        * ``form`` - CdrSearchForm

    **Logic Description**:

        * get the call records as well as daily call analytics
          from postgresql according to search parameters
    """
    logging.debug('CDR View Start')
    result = 1  # default min
    switch_id = 0  # default all
    hangup_cause_id = 0  # default all
    destination, destination_type, accountcode = '', '', ''
    direction, duration, duration_type = '', '', ''
    caller_id_number, caller_id_number_type, country_id = '', '', ''
    action = 'tabs-1'
    menu = 'on'
    records_per_page = settings.PAGE_SIZE

    form = CdrSearchForm(request.POST or None)
    if form.is_valid():
        logging.debug('CDR Search View')
        # set session var value
        field_list = ['destination', 'result', 'destination_type', 'accountcode',
                      'caller_id_number', 'caller_id_number_type', 'duration',
                      'duration_type', 'hangup_cause_id', 'switch_id', 'direction',
                      'country_id', 'export_query_var']
        unset_session_var(request, field_list)
        from_date = getvar(request, 'from_date', setsession=False)
        to_date = getvar(request, 'to_date', setsession=False)
        result = getvar(request, 'result', setsession=True)
        destination = getvar(request, 'destination', setsession=True)
        destination_type = getvar(request, 'destination_type', setsession=True)
        accountcode = getvar(request, 'accountcode', setsession=True)
        caller_id_number = getvar(request, 'caller_id_number', setsession=True)
        caller_id_number_type = getvar(request, 'caller_id_number_type', setsession=True)
        duration = getvar(request, 'duration', setsession=True)
        duration_type = getvar(request, 'duration_type', setsession=True)
        direction = getvar(request, 'direction', setsession=True)
        if direction and direction != 'all' and direction != '0':
            request.session['session_direction'] = str(direction)

        switch_id = getvar(request, 'switch_id', setsession=True)
        hangup_cause_id = getvar(request, 'hangup_cause_id', setsession=True)
        records_per_page = getvar(request, 'records_per_page', setsession=True)

        country_id = form.cleaned_data.get('country_id')
        # convert list value in int
        country_id = [int(row) for row in country_id]
        if len(country_id) >= 1:
            request.session['session_country_id'] = country_id

        start_date = ceil_strdate(str(from_date), 'start', True)
        end_date = ceil_strdate(str(to_date), 'end', True)
        converted_start_date = start_date.strftime('%Y-%m-%d %H:%M')
        converted_end_date = end_date.strftime('%Y-%m-%d %H:%M')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

    menu = show_menu(request)

    using_session = False
    # Display a specific page or sort
    if request.GET.get('page') or request.GET.get('sort_by'):
        using_session = True
        from_date = start_date = request.session.get('session_start_date')
        to_date = end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(start_date, 'start', True)
        end_date = ceil_strdate(end_date, 'end', True)

        destination = request.session.get('session_destination')
        destination_type = request.session.get('session_destination_type')
        accountcode = request.session.get('session_accountcode')
        caller_id_number = request.session.get('session_caller_id_number')
        caller_id_number_type = request.session.get('session_caller_id_number_type')
        duration = request.session.get('session_duration')
        duration_type = request.session.get('session_duration_type')
        direction = request.session.get('session_direction')
        switch_id = request.session.get('session_switch_id')
        hangup_cause_id = request.session.get('session_hangup_cause_id')
        result = request.session.get('session_result')
        records_per_page = request.session.get('session_records_per_page')
        country_id = request.session['session_country_id']

    # Set default cause we display page for the first time
    if request.method == 'GET' and not using_session:
        tday = datetime.today()
        from_date = datetime(tday.year, tday.month, 1, 0, 0, 0, 0)
        last_day = ((datetime(tday.year, tday.month, 1, 23, 59, 59, 999999) +
                     relativedelta(months=1)) -
                    relativedelta(days=1)).strftime('%d')
        # to_date = tday.strftime('%Y-%m-' + last_day + ' 23:59')
        to_date = datetime(tday.year, tday.month, int(last_day), 23, 59, 59, 999999)
        start_date = ceil_strdate(str(from_date), 'start', True)
        end_date = ceil_strdate(str(to_date), 'end', True)

        converted_start_date = start_date.strftime('%Y-%m-%d %H:%M')
        converted_end_date = end_date.strftime('%Y-%m-%d %H:%M')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date
        request.session['session_result'] = 1
        field_list = [
            'destination', 'destination_type', 'accountcode',
            'caller_id_number', 'caller_id_number_type', 'duration',
            'duration_type', 'hangup_cause_id',
            'switch_id', 'direction', 'country_id']
        unset_session_var(request, field_list)
        request.session['session_records_per_page'] = records_per_page
        request.session['session_country_id'] = ''

    # Define no of records per page
    records_per_page = int(records_per_page)

    sort_col_field_list = ['id', 'caller_id_number', 'destination_number', 'starting_date']
    page_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')

    # Build filter for CDR.object
    kwargs = {}
    if hangup_cause_id and hangup_cause_id != '0':
        kwargs['hangup_cause_id'] = int(hangup_cause_id)

    if switch_id and switch_id != '0':
        kwargs['switch_id'] = int(switch_id)

    if direction and direction != 'all' and direction != "0":
        kwargs['direction'] = direction

    if len(country_id) >= 1 and country_id[0] != 0:
        kwargs['country_id__in'] = country_id

    if start_date:
        kwargs['starting_date__gte'] = start_date

    if end_date:
        kwargs['starting_date__lte'] = end_date

    if destination:
        operator_query = get_filter_operator_str('destination_number', destination_type)
        kwargs[operator_query] = destination

    if duration:
        operator_query = get_filter_operator_int('duration', duration_type)
        kwargs[operator_query] = duration

    if caller_id_number:
        operator_query = get_filter_operator_str('caller_id_number', caller_id_number_type)
        kwargs[operator_query] = caller_id_number

    # user are restricted to their own CDRs
    if not request.user.is_superuser:
        kwargs['user_id'] = request.user.id

    if request.user.is_superuser and accountcode:
        try:
            user_prof = UserProfile.objects.get(accountcode=accountcode)
            kwargs['user_id'] = user_prof.user.id
        except UserProfile.DoesNotExist:
            # cannot find a user for this accountcode
            pass

    cdrs = CDR.objects.filter(**kwargs).order_by(page_vars['sort_order'])
    page_cdr_list = cdrs[page_vars['start_page']:page_vars['end_page']]
    cdr_count = cdrs.count()

    logging.debug('Create cdr result')

    # store query_var in session without date
    export_kwargs = kwargs.copy()
    if 'starting_date__gte' in export_kwargs:
        export_kwargs['starting_date__gte'] = export_kwargs['starting_date__gte'].strftime('%Y-%m-%dT%H:%M:%S')
    if 'starting_date__lte' in export_kwargs:
        export_kwargs['starting_date__lte'] = export_kwargs['starting_date__lte'].strftime('%Y-%m-%dT%H:%M:%S')

    request.session['session_export_kwargs'] = export_kwargs

    form = CdrSearchForm(
        initial={
            'from_date': from_date,
            'to_date': to_date,
            'destination': destination,
            'destination_type': destination_type,
            'accountcode': accountcode,
            'caller_id_number': caller_id_number,
            'caller_id_number_type': caller_id_number_type,
            'duration': duration,
            'duration_type': duration_type,
            'result': result,
            'direction': direction,
            'hangup_cause_id': hangup_cause_id,
            'switch_id': switch_id,
            'country_id': country_id,
            'records_per_page': records_per_page
        }
    )

    template_data = {
        'page_cdr_list': page_cdr_list,
        'cdrs': cdrs,
        'form': form,
        'cdr_count': cdr_count,
        'cdr_daily_data': {},
        'col_name_with_order': page_vars['col_name_with_order'],
        'menu': menu,
        'start_date': start_date,
        'end_date': end_date,
        'action': action,
        'result': result,
        'CDR_COLUMN_NAME': CDR_COLUMN_NAME,
        'records_per_page': records_per_page,
        'up_icon': '<i class="glyphicon glyphicon-chevron-up"></i>',
        'down_icon': '<i class="glyphicon glyphicon-chevron-down"></i>'
    }
    logging.debug('CDR View End')
    return render_to_response('cdr/list.html', template_data, context_instance=RequestContext(request))
Esempio n. 9
0
def sms_campaign_list(request):
    """List all sms campaigns for the logged in user

    **Attributes**:

        * ``template`` - mod_sms/list.html

    **Logic Description**:

        * List all sms campaigns belonging to the logged in user
    """
    form = SMSCampaignSearchForm(request.user, request.POST or None)
    sort_col_field_list = [
        'id', 'name', 'startingdate', 'status', 'totalcontact'
    ]
    pag_vars = get_pagination_vars(request,
                                   sort_col_field_list,
                                   default_sort_field='id')

    phonebook_id = ''
    status = 'all'
    post_var_with_page = 0
    if form.is_valid():
        field_list = ['phonebook_id', 'status']
        unset_session_var(request, field_list)
        post_var_with_page = 1
        phonebook_id = getvar(request, 'phonebook_id', setsession=True)
        status = getvar(request, 'status', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        phonebook_id = request.session.get('session_phonebook_id')
        status = request.session.get('session_status')
        form = SMSCampaignSearchForm(request.user,
                                     initial={
                                         'status': status,
                                         'phonebook_id': phonebook_id
                                     })

    if post_var_with_page == 0:
        # default
        # unset session var
        field_list = ['status', 'phonebook_id']
        unset_session_var(request, field_list)

    kwargs = {}
    if phonebook_id and phonebook_id != '0':
        kwargs['phonebook__id__in'] = [int(phonebook_id)]

    if status and status != 'all':
        kwargs['status'] = status

    smscampaign_list = SMSCampaign.objects.filter(user=request.user).order_by(
        pag_vars['sort_order'])
    smscampaign_count = smscampaign_list.count()
    if kwargs:
        all_smscampaign_list = smscampaign_list.filter(**kwargs).order_by(
            pag_vars['sort_order'])
        smscampaign_list = all_smscampaign_list[
            pag_vars['start_page']:pag_vars['end_page']]
        smscampaign_count = all_smscampaign_list.count()

    data = {
        'form': form,
        'smscampaign_list': smscampaign_list,
        'total_campaign': smscampaign_count,
        'SMS_CAMPAIGN_COLUMN_NAME': SMS_CAMPAIGN_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'info_msg': request.session.get('info_msg'),
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    request.session['info_msg'] = ''
    return render_to_response('mod_sms/list.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 10
0
def subscriber_list(request):
    """
    Subscriber list for the logged in user

    **Attributes**:

        * ``template`` - dialer_campaign/subscriber/list.html
        * ``form`` - SubscriberSearchForm

    **Logic Description**:

        * List all subscribers belonging to the logged in user & their campaign
    """
    sort_col_field_list = ['contact', 'updated_date', 'count_attempt', 'completion_count_attempt',
                           'status', 'disposition', 'collected_data', 'agent']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')
    form = SubscriberSearchForm(request.user, request.POST or None)
    campaign_id = ''
    agent_id = ''
    status = 'all'
    start_date = end_date = None
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        field_list = ['start_date', 'end_date', 'status', 'campaign_id', 'agent_id']
        unset_session_var(request, field_list)
        campaign_id = getvar(request, 'campaign_id', setsession=True)
        agent_id = getvar(request, 'agent_id', setsession=True)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        status = getvar(request, 'status', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')

        start_date = ceil_strdate(str(start_date), 'start')
        end_date = ceil_strdate(str(end_date), 'end')

        campaign_id = request.session.get('session_campaign_id')
        agent_id = request.session.get('session_agent_id')
        status = request.session.get('session_status')
        form = SubscriberSearchForm(
            request.user,
            initial={'from_date': start_date.strftime('%Y-%m-%d'),
                     'to_date': end_date.strftime('%Y-%m-%d'),
                     'campaign_id': campaign_id,
                     'agent_id': agent_id,
                     'status': status})

    if post_var_with_page == 0:
        # default
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-%d')
        to_date = tday.strftime('%Y-%m-%d')
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999).replace(tzinfo=utc)

        form = SubscriberSearchForm(request.user, initial={'from_date': from_date, 'to_date': to_date})
        # unset session var
        request.session['session_start_date'] = start_date
        request.session['session_end_date'] = end_date
        request.session['session_status'] = ''
        request.session['session_campaign_id'] = ''
        request.session['session_agent_id'] = ''

    kwargs = {}
    # updated_date might be replaced with last_attempt
    if start_date and end_date:
        kwargs['updated_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['updated_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['updated_date__lte'] = end_date

    if campaign_id and campaign_id != '0':
        kwargs['campaign_id'] = campaign_id

    # if agent_id and agent_id != '0':
    #    kwargs['agent_id'] = agent_id

    if status and status != 'all':
        kwargs['status'] = status

    subscriber_list = []
    all_subscriber_list = []
    subscriber_count = 0

    if request.user.is_superuser:
        subscriber_list = Subscriber.objects.all()
    else:
        subscriber_list = Subscriber.objects.filter(campaign__user=request.user)

    if kwargs:
        subscriber_list = subscriber_list.filter(**kwargs)
        request.session['subscriber_list_kwargs'] = kwargs

    all_subscriber_list = subscriber_list.order_by(pag_vars['sort_order'])
    subscriber_list = all_subscriber_list[pag_vars['start_page']:pag_vars['end_page']]
    subscriber_count = all_subscriber_list.count()

    data = {
        'subscriber_list': subscriber_list,
        'all_subscriber_list': all_subscriber_list,
        'total_subscribers': subscriber_count,
        'SUBSCRIBER_COLUMN_NAME': SUBSCRIBER_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'form': form,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dialer_campaign/subscriber/list.html', data, context_instance=RequestContext(request))
Esempio n. 11
0
    def changelist_view(self, request, extra_context=None):
        """
        Override changelist_view method of django-admin for search parameters

        **Attributes**:

            * ``form`` - AdminVoipSearchForm
            * ``template`` - admin/dialer_cdr/voipcall/change_list.html

        **Logic Description**:

            * VoIP report Record Listing with search option & Daily Call Report
              search Parameters: by date, by status and by billed.
        """
        opts = VoIPCall._meta
        query_string = ""
        form = AdminVoipSearchForm()
        if request.method == "POST":
            # Session variable get record set with searched option into export file
            request.session["admin_voipcall_record_kwargs"] = voipcall_record_common_fun(request)

            query_string = voipcall_search_admin_form_fun(request)
            return HttpResponseRedirect("/admin/%s/%s/?%s" % (opts.app_label, opts.object_name.lower(), query_string))
        else:
            disposition = ""
            from_date = ""
            to_date = ""
            campaign_id = ""
            leg_type = ""

            from_date = getvar(request, "starting_date__gte")
            to_date = getvar(request, "starting_date__lte")[0:10]
            disposition = getvar(request, "disposition__exact")
            campaign_id = getvar(request, "callrequest__campaign_id")
            leg_type = getvar(request, "leg_type__exact")

            form = AdminVoipSearchForm(
                initial={
                    "disposition": disposition,
                    "from_date": from_date,
                    "to_date": to_date,
                    "campaign_id": campaign_id,
                    "leg_type": leg_type,
                }
            )

        ChangeList = self.get_changelist(request)
        try:
            cl = ChangeList(
                request,
                self.model,
                self.list_display,
                self.list_display_links,
                self.list_filter,
                self.date_hierarchy,
                self.search_fields,
                self.list_select_related,
                self.list_per_page,
                self.list_max_show_all,
                self.list_editable,
                self,
            )
        except IncorrectLookupParameters:
            if ERROR_FLAG in request.GET.keys():
                return render_to_response("admin/invalid_setup.html", {"title": _("Database error")})
            return HttpResponseRedirect("%s?%s=1" % (request.path, ERROR_FLAG))

        if request.META["QUERY_STRING"] == "":
            # Default
            # Session variable get record set with searched option into export file
            request.session["admin_voipcall_record_kwargs"] = voipcall_record_common_fun(request)

            query_string = voipcall_search_admin_form_fun(request)
            return HttpResponseRedirect("/admin/%s/%s/?%s" % (opts.app_label, opts.object_name.lower(), query_string))

        cl.formset = None

        selection_note_all = ungettext("%(total_count)s selected", "All %(total_count)s selected", cl.result_count)

        ctx = {
            "selection_note": _("0 of %(cnt)s selected") % {"cnt": len(cl.result_list)},
            "selection_note_all": selection_note_all % {"total_count": cl.result_count},
            "cl": cl,
            "form": form,
            "opts": opts,
            "model_name": opts.object_name.lower(),
            "app_label": APP_LABEL,
            "title": _("call report"),
        }
        return super(VoIPCallAdmin, self).changelist_view(request, extra_context=ctx)
Esempio n. 12
0
def subscriber_list(request):
    """
    Subscriber list for the logged in user

    **Attributes**:

        * ``template`` - dialer_campaign/subscriber/list.html
        * ``form`` - SubscriberSearchForm

    **Logic Description**:

        * List all subscribers belonging to the logged in user & their campaign
    """
    sort_col_field_list = [
        'contact', 'updated_date', 'count_attempt', 'completion_count_attempt',
        'status', 'disposition', 'collected_data', 'agent'
    ]
    pag_vars = get_pagination_vars(request,
                                   sort_col_field_list,
                                   default_sort_field='id')
    form = SubscriberSearchForm(request.user, request.POST or None)
    campaign_id = ''
    agent_id = ''
    status = 'all'
    start_date = end_date = None
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        field_list = [
            'start_date', 'end_date', 'status', 'campaign_id', 'agent_id'
        ]
        unset_session_var(request, field_list)
        campaign_id = getvar(request, 'campaign_id', setsession=True)
        agent_id = getvar(request, 'agent_id', setsession=True)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        status = getvar(request, 'status', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')

        start_date = ceil_strdate(str(start_date), 'start')
        end_date = ceil_strdate(str(end_date), 'end')

        campaign_id = request.session.get('session_campaign_id')
        agent_id = request.session.get('session_agent_id')
        status = request.session.get('session_status')
        form = SubscriberSearchForm(request.user,
                                    initial={
                                        'from_date':
                                        start_date.strftime('%Y-%m-%d'),
                                        'to_date':
                                        end_date.strftime('%Y-%m-%d'),
                                        'campaign_id':
                                        campaign_id,
                                        'agent_id':
                                        agent_id,
                                        'status':
                                        status
                                    })

    if post_var_with_page == 0:
        # default
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-%d')
        to_date = tday.strftime('%Y-%m-%d')
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0,
                              0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59,
                            999999).replace(tzinfo=utc)

        form = SubscriberSearchForm(request.user,
                                    initial={
                                        'from_date': from_date,
                                        'to_date': to_date
                                    })
        # unset session var
        request.session['session_start_date'] = start_date
        request.session['session_end_date'] = end_date
        request.session['session_status'] = ''
        request.session['session_campaign_id'] = ''
        request.session['session_agent_id'] = ''

    kwargs = {}
    # updated_date might be replaced with last_attempt
    if start_date and end_date:
        kwargs['updated_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['updated_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['updated_date__lte'] = end_date

    if campaign_id and campaign_id != '0':
        kwargs['campaign_id'] = campaign_id

    # if agent_id and agent_id != '0':
    #    kwargs['agent_id'] = agent_id

    if status and status != 'all':
        kwargs['status'] = status

    subscriber_list = []
    all_subscriber_list = []
    subscriber_count = 0

    if request.user.is_superuser:
        subscriber_list = Subscriber.objects.all()
    else:
        subscriber_list = Subscriber.objects.filter(
            campaign__user=request.user)

    if kwargs:
        subscriber_list = subscriber_list.filter(**kwargs)
        request.session['subscriber_list_kwargs'] = kwargs

    all_subscriber_list = subscriber_list.order_by(pag_vars['sort_order'])
    subscriber_list = all_subscriber_list[
        pag_vars['start_page']:pag_vars['end_page']]
    subscriber_count = all_subscriber_list.count()

    data = {
        'subscriber_list': subscriber_list,
        'all_subscriber_list': all_subscriber_list,
        'total_subscribers': subscriber_count,
        'SUBSCRIBER_COLUMN_NAME': SUBSCRIBER_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'form': form,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dialer_campaign/subscriber/list.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 13
0
def cdr_dashboard(request):
    """CDR dashboard on the last 24 hours

    **Attributes**:

        * ``template`` - cdr/dashboard.html
        * ``form`` - SwitchForm

    **Logic Description**:

        Display calls aggregated information for the last 24hours, several report will be
        created and displayed such as hourly call report and hangup cause/country analytics.
    """
    logging.debug('CDR dashboard view start')
    form = SwitchForm(request.POST or None)

    if form.is_valid():
        logging.debug('CDR dashboard view with search option')
        switch_id = int(getvar(request, 'switch_id'))
    else:
        switch_id = 0

    # Get list of calls/duration for each of the last 24 hours
    (calls_hour_aggr, total_calls, total_duration, total_billsec, total_buy_cost, total_sell_cost) = custom_sql_matv_voip_cdr_aggr_last24hours(request.user, switch_id)

    # Build chart data for last 24h calls
    (xdata, ydata, ydata2, ydata3, ydata4, ydata5) = ([], [], [], [], [], [])
    for i in calls_hour_aggr:
        start_time = (time.mktime(calls_hour_aggr[i]['calltime'].timetuple()) * 1000)
        xdata.append(start_time)
        ydata.append(int(calls_hour_aggr[i]['nbcalls']))
        ydata2.append(int(calls_hour_aggr[i]['duration']/60))
        ydata3.append(int(calls_hour_aggr[i]['billsec']/60))
        ydata4.append(int(calls_hour_aggr[i]['buy_cost']))
        ydata5.append(int(calls_hour_aggr[i]['sell_cost']))

    tooltip_date = "%d %b %y %H:%M %p"
    extra_serie1 = {"tooltip": {"y_start": "", "y_end": " calls"}, "date_format": tooltip_date}
    extra_serie2 = {"tooltip": {"y_start": "", "y_end": " min"}, "date_format": tooltip_date}
    extra_serie3 = {"tooltip": {"y_start": "", "y_end": " min"}, "date_format": tooltip_date}
    extra_serie4 = {"tooltip": {"y_start": "", "y_end": ""}, "date_format": tooltip_date}
    extra_serie5 = {"tooltip": {"y_start": "", "y_end": ""}, "date_format": tooltip_date}

    kwargs1 = {}
    kwargs1['bar'] = True

    final_chartdata = {
        'x': xdata,
        'name1': 'Calls', 'y1': ydata, 'extra1': extra_serie1, 'kwargs1': kwargs1,
        'name2': 'Duration', 'y2': ydata2, 'extra2': extra_serie2,
        'name3': 'Billsec', 'y3': ydata3, 'extra3': extra_serie3,
        'name4': 'Buy cost', 'y4': ydata4, 'extra4': extra_serie4,
        'name5': 'Sell cost', 'y5': ydata5, 'extra5': extra_serie5,
    }
    final_charttype = "linePlusBarChart"

    # Get top 5 of country calls for last 24 hours
    country_data = custom_sql_aggr_top_country_last24hours(request.user, switch_id, limit=5)

    # Build pie chart data for last 24h calls per country
    (xdata, ydata) = ([], [])
    for country in country_data:
        xdata.append(get_country_name(country["country_id"]))
        ydata.append(percentage(country["nbcalls"], total_calls))

    color_list = ['#FFC36C', '#FFFF9D', '#BEEB9F', '#79BD8F', '#FFB391']
    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    country_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    country_analytic_charttype = "pieChart"

    country_extra = {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
    }

    # Get top 10 of hangup cause calls for last 24 hours
    hangup_cause_data = custom_sql_aggr_top_hangup_last24hours(request.user, switch_id)

    # hangup analytic pie chart data
    (xdata, ydata) = ([], [])
    for hangup_cause in hangup_cause_data:
        xdata.append(str(get_hangupcause_name(hangup_cause["hangup_cause_id"])))
        ydata.append(str(percentage(hangup_cause["nbcalls"], total_calls)))

    color_list = ['#2A343F', '#7E8282', '#EA9664', '#30998F', '#449935']
    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    hangup_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    hangup_analytic_charttype = "pieChart"

    hangup_extra = country_extra

    logging.debug("Result calls_hour_aggr %d" % len(calls_hour_aggr))
    logging.debug("Result hangup_cause_data %d" % len(hangup_cause_data))
    logging.debug("Result country_data %d" % len(country_data))

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    final_extra = {
        'x_is_date': True,
        'x_axis_format': '%H:%M',
        # 'x_axis_format': '%d %b %Y',
        'tag_script_js': True,
        'jquery_on_ready': True,
        'focus_enable': True,
    }

    logging.debug('CDR dashboard view end')
    variables = {
        'total_calls': total_calls,
        'total_duration': int_convert_to_minute(total_duration),
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
        'hangup_analytic': hangup_cause_data,
        'form': form,
        'final_chartdata': final_chartdata,
        'final_charttype': final_charttype,
        'final_chartcontainer': 'final_container',
        'final_extra': final_extra,
        'hangup_analytic_charttype': hangup_analytic_charttype,
        'hangup_analytic_chartdata': hangup_analytic_chartdata,
        'hangup_chartcontainer': 'hangup_piechart_container',
        'hangup_extra': hangup_extra,
        'country_analytic_charttype': country_analytic_charttype,
        'country_analytic_chartdata': country_analytic_chartdata,
        'country_chartcontainer': 'country_piechart_container',
        'country_extra': country_extra,
    }
    return render_to_response('cdr/dashboard.html', variables, context_instance=RequestContext(request))
Esempio n. 14
0
def voipcall_report(request):
    """VoIP Call Report

    **Attributes**:

        * ``form`` - VoipSearchForm
        * ``template`` - dialer_cdr/voipcall_report.html

    **Logic Description**:

        * Get VoIP call list according to search parameters for loggedin user

    **Important variable**:

        * ``request.session['voipcall_record_kwargs']`` - stores voipcall kwargs
    """
    sort_col_field_list = ['starting_date', 'leg_type', 'disposition', 'used_gateway', 'callerid',
                           'callid', 'phone_number', 'duration', 'billsec', 'amd_status']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='starting_date')
    action = 'tabs-1'
    form = VoipSearchForm(request.user, request.POST or None)
    if form.is_valid():
        # Valid form
        field_list = ['start_date', 'end_date', 'disposition', 'campaign_id', 'leg_type']
        unset_session_var(request, field_list)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        disposition = getvar(request, 'disposition', setsession=True)
        campaign_id = getvar(request, 'campaign_id', setsession=True)
        leg_type = getvar(request, 'leg_type', setsession=True)
        form = VoipSearchForm(request.user, initial={'from_date': start_date.strftime('%Y-%m-%d'),
                                                     'to_date': end_date.strftime('%Y-%m-%d'),
                                                     'disposition': disposition,
                                                     'campaign_id': campaign_id,
                                                     'leg_type': leg_type})

    elif request.GET.get('page') or request.GET.get('sort_by'):
        # Pagination / Sort
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(start_date, 'start')
        end_date = ceil_strdate(end_date, 'end')

        disposition = request.session.get('session_disposition')
        campaign_id = request.session.get('session_campaign_id')
        leg_type = request.session.get('session_leg_type')
        form = VoipSearchForm(request.user, initial={'from_date': start_date.strftime('%Y-%m-%d'),
                                                     'to_date': end_date.strftime('%Y-%m-%d'),
                                                     'disposition': disposition,
                                                     'campaign_id': campaign_id,
                                                     'leg_type': leg_type})
    else:
        # Default
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-%d')
        to_date = tday.strftime('%Y-%m-%d')
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999).replace(tzinfo=utc)
        disposition = 'all'
        campaign_id = 0
        leg_type = ''
        form = VoipSearchForm(request.user, initial={'from_date': from_date,
                                                     'to_date': to_date,
                                                     'disposition': disposition,
                                                     'campaign_id': campaign_id,
                                                     'leg_type': leg_type})
        # unset session var
        request.session['session_start_date'] = start_date
        request.session['session_end_date'] = end_date
        request.session['session_disposition'] = disposition
        request.session['session_campaign_id'] = ''
        request.session['session_leg_type'] = ''

    kwargs = {}
    if start_date and end_date:
        kwargs['starting_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['starting_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['starting_date__lte'] = end_date

    if disposition and disposition != 'all':
        kwargs['disposition__exact'] = disposition

    if campaign_id and int(campaign_id) != 0:
        kwargs['callrequest__campaign_id'] = campaign_id

    if leg_type and leg_type != '':
        kwargs['leg_type__exact'] = leg_type

    if not request.user.is_superuser:
        kwargs['user_id'] = request.user.id

    voipcall_list = VoIPCall.objects.filter(**kwargs)
    all_voipcall_list = voipcall_list.values_list('id', flat=True)

    # Session variable is used to get record set with searched option
    # into export file
    request.session['voipcall_record_kwargs'] = kwargs

    if request.GET.get('page') or request.GET.get('sort_by'):
        daily_data = request.session['voipcall_daily_data']
    else:
        if not voipcall_list:
            request.session['voipcall_daily_data'] = ''
        daily_data = get_voipcall_daily_data(voipcall_list)
        request.session['voipcall_daily_data'] = daily_data

    voipcall_list = voipcall_list.order_by(pag_vars['sort_order'])[pag_vars['start_page']:pag_vars['end_page']]

    data = {
        'form': form,
        'total_data': daily_data['total_data'],
        'total_duration': daily_data['total_duration'],
        'total_calls': daily_data['total_calls'],
        'total_avg_duration': daily_data['total_avg_duration'],
        'max_duration': daily_data['max_duration'],
        'all_voipcall_list': all_voipcall_list,
        'voipcall_list': voipcall_list,
        'CDR_REPORT_COLUMN_NAME': CDR_REPORT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'start_date': start_date,
        'end_date': end_date,
        'action': action,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dialer_cdr/voipcall_report.html', data, context_instance=RequestContext(request))
Esempio n. 15
0
def billing_report(request):
    """CDR billing graph by daily basis

    **Attributes**:

        * ``template`` - voip_billing/billing_report.html
        * ``form`` - BillingReportForm

    **Logic Description**:

        Retrieve call records from PostgreSQL and build the
        daily billing analytics for given date range
    """
    switch_id = 0
    tday = datetime.today()
    total_data = []
    charttype = "lineWithFocusChart"
    hourly_chartdata = {"x": []}

    form = BillingReportForm(request.POST or None,
                             initial={
                                 'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                 'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                 'switch_id': switch_id
                             })
    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')

    metrics = ['buy_cost', 'sell_cost']

    hourly_data = get_report_cdr_per_switch(request.user, 'hour', start_date,
                                            end_date, switch_id)

    hourly_chartdata['x'] = hourly_data["nbcalls"]["x_timestamp"]

    i = 0
    for metric in metrics:
        extra_serie = {
            "tooltip": {
                "y_start": "",
                "y_end": " " + metric
            },
            "date_format": "%d %b %y %H:%M%p"
        }
        for switch in hourly_data[metric]["columns"]:
            i = i + 1
            hourly_chartdata[
                'name' + str(i)] = get_switch_ip_addr(switch) + "_" + metric
            hourly_chartdata['y' + str(i)] = hourly_data[metric]["values"][str(
                switch)]
            hourly_chartdata['extra' + str(i)] = extra_serie

    total_calls = hourly_data["nbcalls"]["total"]
    total_duration = hourly_data["duration"]["total"]
    total_billsec = hourly_data["billsec"]["total"]
    total_buy_cost = hourly_data["buy_cost"]["total"]
    total_sell_cost = hourly_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    country_data = custom_sql_aggr_top_country(request.user, switch_id, 10,
                                               start_date, end_date)

    data = {
        'form': form,
        'total_data': total_data,
        'start_date': start_date,
        'end_date': end_date,
        'charttype': charttype,
        'chartdata': hourly_chartdata,
        'chartcontainer': 'chart_container',
        'extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
    }
    return render_to_response('voip_billing/billing_report.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 16
0
def event_list(request):
    """Event list for the logged in user

    **Attributes**:

        * ``template`` - appointment/event/list.html

    **Logic Description**:

        * List all events which belong to the logged in user.
    """
    today = datetime.utcnow().replace(tzinfo=utc)
    form = EventSearchForm(request.user, request.POST or None, initial={'start': today.strftime('%Y-%m-%d %H:%M')})
    sort_col_field_list = ['id', 'start', 'end', 'title', 'calendar', 'status', 'created_on']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')

    start_date = ''
    calendar_id = ''
    calendar_user_id = ''
    post_var_with_page = 0
    if form.is_valid():
        field_list = ['start_date', 'calendar_id', 'calendar_user_id']
        unset_session_var(request, field_list)

        start_date = getvar(request, 'start_date')
        start_date = ceil_strdate(str(start_date), 'start')
        converted_start_date = start_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date

        calendar_id = getvar(request, 'calendar_id', setsession=True)
        calendar_user_id = getvar(request, 'calendar_user_id', setsession=True)
        post_var_with_page = 1

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        start_date = ceil_strdate(start_date, 'start')
        calendar_id = request.session.get('session_calendar_id')
        calendar_user_id = request.session.get('session_calendar_user_id')
        form = EventSearchForm(request.user, initial={'start_date': start_date.strftime('%Y-%m-%d %H:%M'),
                                                      'calendar_id': calendar_id,
                                                      'calendar_user_id': calendar_user_id,
                                                      })

    if post_var_with_page == 0:
        # default unset session var
        field_list = ['start_date', 'calendar_id', 'calendar_user_id']
        unset_session_var(request, field_list)

    kwargs = {}
    calendar_user_id_list = get_calendar_user_id_list(request.user)
    kwargs['calendar__user_id__in'] = calendar_user_id_list
    if start_date:
        kwargs['start__gte'] = start_date

    if calendar_id and int(calendar_id) != 0:
        kwargs['calendar_id'] = calendar_id

    if calendar_user_id and int(calendar_user_id) != 0:
        kwargs['creator_id'] = calendar_user_id

    all_event_list = Event.objects.filter(**kwargs).order_by(pag_vars['sort_order'])
    event_list = all_event_list[pag_vars['start_page']:pag_vars['end_page']]
    data = {
        'form': form,
        'msg': request.session.get('msg'),
        'all_event_list': all_event_list,
        'event_list': event_list,
        'total_event': all_event_list.count(),
        'EVENT_COLUMN_NAME': EVENT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('appointment/event/list.html', data, context_instance=RequestContext(request))
Esempio n. 17
0
    def subscriber_report(self, request):
        """
        Get subscriber report

        **Attributes**:

            * ``form`` - SubscriberReportForm
            * ``template`` - admin/dialer_campaign/subscriber/subscriber_report.html
        """
        opts = Subscriber._meta
        tday = datetime.today()
        form = SubscriberReportForm(
            request.POST or None, initial={"from_date": tday.strftime("%Y-%m-%d"), "to_date": tday.strftime("%Y-%m-%d")}
        )
        total_subscriber = 0
        total_pending = 0
        total_pause = 0
        total_abort = 0
        total_fail = 0
        total_sent = 0
        total_in_process = 0
        total_not_auth = 0
        total_completed = 0

        if form.is_valid():
            start_date = ""
            end_date = ""
            from_date = getvar(request, "from_date")
            to_date = getvar(request, "to_date")
            start_date = ceil_strdate(str(from_date), "start")
            end_date = ceil_strdate(str(to_date), "end")
            campaign_id = getvar(request, "campaign_id")
            kwargs = {}
            if start_date and end_date:
                kwargs["updated_date__range"] = (start_date, end_date)
            if start_date and end_date == "":
                kwargs["updated_date__gte"] = start_date
            if start_date == "" and end_date:
                kwargs["updated_date__lte"] = end_date
            if campaign_id and campaign_id != "0":
                kwargs["campaign_id"] = campaign_id

            select_data = {"updated_date": "SUBSTR(CAST(updated_date as CHAR(30)),1,10)"}
            subscriber = (
                Subscriber.objects.filter(**kwargs)
                .extra(select=select_data)
                .values("updated_date", "status")
                .annotate(Count("updated_date"))
                .order_by("updated_date")
            )

            for i in subscriber:
                total_subscriber += i["updated_date__count"]
                if i["status"] == SUBSCRIBER_STATUS.PENDING:
                    total_pending += i["updated_date__count"]
                elif i["status"] == SUBSCRIBER_STATUS.PAUSE:
                    total_pause += i["updated_date__count"]
                elif i["status"] == SUBSCRIBER_STATUS.ABORT:
                    total_abort += i["updated_date__count"]
                elif i["status"] == SUBSCRIBER_STATUS.FAIL:
                    total_fail += i["updated_date__count"]
                elif i["status"] == SUBSCRIBER_STATUS.SENT:
                    total_sent += i["updated_date__count"]
                elif i["status"] == SUBSCRIBER_STATUS.IN_PROCESS:
                    total_in_process += i["updated_date__count"]
                elif i["status"] == SUBSCRIBER_STATUS.NOT_AUTHORIZED:
                    total_not_auth += i["updated_date__count"]
                else:
                    # status COMPLETED
                    total_completed += i["updated_date__count"]

        ctx = RequestContext(
            request,
            {
                "form": form,
                "opts": opts,
                "total_subscriber": total_subscriber,
                "total_pending": total_pending,
                "total_pause": total_pause,
                "total_abort": total_abort,
                "total_fail": total_fail,
                "total_sent": total_sent,
                "total_in_process": total_in_process,
                "total_not_auth": total_not_auth,
                "total_completed": total_completed,
                "SUBSCRIBER_STATUS_NAME": SUBSCRIBER_STATUS_NAME,
                "model_name": opts.object_name.lower(),
                "app_label": _("Dialer Campaign"),
                "title": _("subscriber report"),
            },
        )

        return render_to_response("admin/dialer_campaign/subscriber/subscriber_report.html", context_instance=ctx)
Esempio n. 18
0
def alert_report(request):
    """
    To get alarm report for logged in user

    **Attributes**:

        * ``form`` - AlarmReportForm
        * ``template`` - cdr_alert/alarm_report.html
    """
    form = AlarmReportForm(request.user, request.POST or None)
    sort_col_field_list = [
        'id', 'alarm', 'calculatedvalue', 'status', 'daterun'
    ]
    page_data = get_pagination_vars(request,
                                    sort_col_field_list,
                                    default_sort_field='id')

    alarm_id = 0
    action = 'tabs-1'
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        request.session['session_alarm_id'] = ''
        alarm_id = getvar(request, 'alarm_id', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        alarm_id = request.session.get('session_alarm_id')
        form = AlarmReportForm(request.user, initial={'alarm_id': alarm_id})

    if post_var_with_page == 0:
        # unset session var
        request.session['session_alarm_id'] = ''

    kwargs = {}
    if alarm_id and int(alarm_id) != 0:
        kwargs['alarm_id'] = int(alarm_id)
    kwargs['alarm__user'] = request.user

    alarm_report_list = AlarmReport.objects.filter(**kwargs)
    all_alarm_list = alarm_report_list.order_by(page_data['sort_order'])
    alarm_list = all_alarm_list[page_data['start_page']:page_data['end_page']]
    contact_alarm = all_alarm_list.count()

    days_report = last_seven_days_report(request, kwargs)

    data = {
        'form': form,
        'action': action,
        'total_data': days_report['total_data'],
        'start_date': days_report['start_date'],
        'end_date': days_report['end_date'],
        'all_alarm_list': all_alarm_list,
        'rows': alarm_list,
        'total_count': contact_alarm,
        'ALARM_REPORT_COLUMN_NAME': ALARM_REPORT_COLUMN_NAME,
        'col_name_with_order': page_data['col_name_with_order'],
        'charttype': days_report['charttype'],
        'chartdata': days_report['chartdata'],
        'chartcontainer': 'chartcontainer',
        'extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %y',
            'tag_script_js': False,
            'jquery_on_ready': True,
        },
    }
    return render_to_response('cdr_alert/alarm_report.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 19
0
def sms_report(request):
    """SMS Report

    **Attributes**:

        * ``form`` - SMSSearchForm
        * ``template`` - mod_sms/sms_report.html

    **Logic Description**:

        * Get SMS list according to search parameters for logged-in user

    **Important variable**:

        * ``request.session['sms_record_kwargs']`` - stores sms kwargs
    """
    sort_col_field_list = [
        'send_date', 'recipient_number', 'uuid', 'status', 'status_message',
        'gateway'
    ]
    pag_vars = get_pagination_vars(request,
                                   sort_col_field_list,
                                   default_sort_field='send_date')

    from_date = ''
    to_date = ''
    status = 'all'
    smscampaign = ''

    form = SMSSearchForm(request.user, request.POST or None)
    action = 'tabs-1'
    kwargs = {}
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        field_list = ['start_date', 'end_date', 'status', 'smscampaign']
        unset_session_var(request, field_list)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        status = getvar(request, 'status', setsession=True)
        smscampaign = getvar(request, 'smscampaign', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(start_date, 'start')
        end_date = ceil_strdate(end_date, 'end')
        status = request.session.get('session_status')
        smscampaign = request.session.get('session_smscampaign')

        form = SMSSearchForm(request.user,
                             initial={
                                 'from_date': start_date.strftime('%Y-%m-%d'),
                                 'to_date': end_date.strftime('%Y-%m-%d'),
                                 'status': status,
                                 'smscampaign': smscampaign
                             })

    if post_var_with_page == 0:
        # default
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-%d')
        to_date = tday.strftime('%Y-%m-%d')
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0,
                              0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59,
                            999999).replace(tzinfo=utc)
        status = 'all'
        smscampaign = ''
        form = SMSSearchForm(request.user,
                             initial={
                                 'from_date': from_date,
                                 'to_date': to_date,
                                 'status': status,
                                 'smscampaign': smscampaign
                             })
        # unset session var
        request.session['session_start_date'] = start_date
        request.session['session_end_date'] = end_date
        request.session['session_status'] = status
        request.session['session_smscampaign'] = smscampaign

    kwargs['sender'] = request.user

    if start_date and end_date:
        kwargs['send_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['send_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['send_date__lte'] = end_date

    if status and status != 'all':
        kwargs['status__exact'] = status

    if smscampaign and smscampaign != '0':
        kwargs['sms_campaign_id'] = smscampaign

    smslist = SMSMessage.objects.filter(**kwargs)
    all_sms_list = smslist.values_list('id', flat=True)
    sms_list = smslist.order_by(
        pag_vars['sort_order'])[pag_vars['start_page']:pag_vars['end_page']]

    # Session variable is used to get record set with searched option
    # into export file
    request.session['sms_record_kwargs'] = kwargs

    select_data = {"send_date": "SUBSTR(CAST(send_date as CHAR(30)),1,10)"}
    # Get Total Rrecords from SMSMessage Report table for Daily SMS Report
    total_data = all_sms_list.extra(select=select_data).values('send_date')\
        .annotate(Count('send_date')).order_by('-send_date')

    # Following code will count total sms
    if total_data.count() != 0:
        total_sms = sum([x['send_date__count'] for x in total_data])
    else:
        total_sms = 0

    data = {
        'form': form,
        'from_date': from_date,
        'all_sms_list': all_sms_list,
        'sms_list': sms_list,
        'sms_count': all_sms_list.count() if all_sms_list else 0,
        'SMS_REPORT_COLUMN_NAME': SMS_REPORT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'start_date': start_date,
        'end_date': end_date,
        'to_date': to_date,
        'action': action,
        'status': status,
        'total_data': total_data.reverse(),
        'total_sms': total_sms,
    }

    return render_to_response('mod_sms/sms_report.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 20
0
def sms_report(request):
    """SMS Report

    **Attributes**:

        * ``form`` - SMSSearchForm
        * ``template`` - mod_sms/sms_report.html

    **Logic Description**:

        * Get SMS list according to search parameters for logged-in user

    **Important variable**:

        * ``request.session['sms_record_kwargs']`` - stores sms kwargs
    """
    sort_col_field_list = ['send_date', 'recipient_number', 'uuid', 'status', 'status_message', 'gateway']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='send_date')

    from_date = ''
    to_date = ''
    status = 'all'
    smscampaign = ''

    form = SMSSearchForm(request.user, request.POST or None)
    action = 'tabs-1'
    kwargs = {}
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        field_list = ['start_date', 'end_date', 'status', 'smscampaign']
        unset_session_var(request, field_list)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        status = getvar(request, 'status', setsession=True)
        smscampaign = getvar(request, 'smscampaign', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(start_date, 'start')
        end_date = ceil_strdate(end_date, 'end')
        status = request.session.get('session_status')
        smscampaign = request.session.get('session_smscampaign')

        form = SMSSearchForm(request.user,
                             initial={'from_date': start_date.strftime('%Y-%m-%d'),
                                      'to_date': end_date.strftime('%Y-%m-%d'),
                                      'status': status,
                                      'smscampaign': smscampaign})

    if post_var_with_page == 0:
        # default
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-%d')
        to_date = tday.strftime('%Y-%m-%d')
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999).replace(tzinfo=utc)
        status = 'all'
        smscampaign = ''
        form = SMSSearchForm(request.user, initial={'from_date': from_date, 'to_date': to_date,
                                                    'status': status, 'smscampaign': smscampaign})
        # unset session var
        request.session['session_start_date'] = start_date
        request.session['session_end_date'] = end_date
        request.session['session_status'] = status
        request.session['session_smscampaign'] = smscampaign

    kwargs['sender'] = request.user

    if start_date and end_date:
        kwargs['send_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['send_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['send_date__lte'] = end_date

    if status and status != 'all':
        kwargs['status__exact'] = status

    if smscampaign and smscampaign != '0':
        kwargs['sms_campaign_id'] = smscampaign

    smslist = SMSMessage.objects.filter(**kwargs)
    all_sms_list = smslist.values_list('id', flat=True)
    sms_list = smslist.order_by(pag_vars['sort_order'])[pag_vars['start_page']:pag_vars['end_page']]

    # Session variable is used to get record set with searched option
    # into export file
    request.session['sms_record_kwargs'] = kwargs

    select_data = {"send_date": "SUBSTR(CAST(send_date as CHAR(30)),1,10)"}
    # Get Total Rrecords from SMSMessage Report table for Daily SMS Report
    total_data = all_sms_list.extra(select=select_data).values('send_date')\
        .annotate(Count('send_date')).order_by('-send_date')

    # Following code will count total sms
    if total_data.count() != 0:
        total_sms = sum([x['send_date__count'] for x in total_data])
    else:
        total_sms = 0

    data = {
        'form': form,
        'from_date': from_date,
        'all_sms_list': all_sms_list,
        'sms_list': sms_list,
        'sms_count': all_sms_list.count() if all_sms_list else 0,
        'SMS_REPORT_COLUMN_NAME': SMS_REPORT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'start_date': start_date,
        'end_date': end_date,
        'to_date': to_date,
        'action': action,
        'status': status,
        'total_data': total_data.reverse(),
        'total_sms': total_sms,
    }

    return render_to_response('mod_sms/sms_report.html', data, context_instance=RequestContext(request))
Esempio n. 21
0
def cdr_view(request):
    """List of CDRs

    **Attributes**:

        * ``template`` - cdr/list.html
        * ``form`` - CdrSearchForm

    **Logic Description**:

        * get the call records as well as daily call analytics
          from postgresql according to search parameters
    """
    logging.debug('CDR View Start')
    result = 1  # default min
    switch_id = 0  # default all
    hangup_cause_id = 0  # default all
    destination, destination_type, accountcode, call_record, custom_carrier = '', '', '', '', ''
    direction, duration, duration_type = '', '', ''
    caller_id_number, caller_id_number_type, country_id = '', '', ''
    action = 'tabs-1'
    menu = 'on'
    records_per_page = settings.PAGE_SIZE

    form = CdrSearchForm(request.POST or None)
    if form.is_valid():
        logging.debug('CDR Search View')
        # set session var value
        field_list = ['destination', 'result', 'destination_type', 'accountcode',
                      'caller_id_number', 'caller_id_number_type', 'duration',
                      'duration_type', 'hangup_cause_id', 'switch_id', 'direction',
                      'country_id', 'export_query_var']
        unset_session_var(request, field_list)
        from_date = getvar(request, 'from_date', setsession=False)
        to_date = getvar(request, 'to_date', setsession=False)
        result = getvar(request, 'result', setsession=True)
        destination = getvar(request, 'destination', setsession=True)
        destination_type = getvar(request, 'destination_type', setsession=True)
        accountcode = getvar(request, 'accountcode', setsession=True)
        caller_id_number = getvar(request, 'caller_id_number', setsession=True)
        caller_id_number_type = getvar(request, 'caller_id_number_type', setsession=True)
        duration = getvar(request, 'duration', setsession=True)
        duration_type = getvar(request, 'duration_type', setsession=True)
        direction = getvar(request, 'direction', setsession=True)
        if direction and direction != 'all' and direction != '0':
            request.session['session_direction'] = str(direction)

        switch_id = getvar(request, 'switch_id', setsession=True)
        hangup_cause_id = getvar(request, 'hangup_cause_id', setsession=True)
        records_per_page = getvar(request, 'records_per_page', setsession=True)
	logging.debug(records_per_page)
        country_id = form.cleaned_data.get('country_id')
        # convert list value in int
        country_id = [int(row) for row in country_id]
        if len(country_id) >= 1:
            request.session['session_country_id'] = country_id

        start_date = ceil_strdate(str(from_date), 'start', True)
        end_date = ceil_strdate(str(to_date), 'end', True)
        converted_start_date = start_date.strftime('%Y-%m-%d %H:%M')
        converted_end_date = end_date.strftime('%Y-%m-%d %H:%M')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date
	call_record = getvar(request, 'call_record', setsession=True)
	custom_carrier = getvar(request, 'custom_carrier', setsession=True)

    menu = show_menu(request)

    using_session = False
    # Display a specific page or sort
    if request.GET.get('page') or request.GET.get('sort_by'):
        using_session = True
        from_date = start_date = request.session.get('session_start_date')
        to_date = end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(start_date, 'start', True)
        end_date = ceil_strdate(end_date, 'end', True)

        destination = request.session.get('session_destination')
        destination_type = request.session.get('session_destination_type')
        accountcode = request.session.get('session_accountcode')
        caller_id_number = request.session.get('session_caller_id_number')
        caller_id_number_type = request.session.get('session_caller_id_number_type')
        duration = request.session.get('session_duration')
        duration_type = request.session.get('session_duration_type')
        direction = request.session.get('session_direction')
        switch_id = request.session.get('session_switch_id')
        hangup_cause_id = request.session.get('session_hangup_cause_id')
        result = request.session.get('session_result')
        records_per_page = request.session.get('session_records_per_page')
	logging.debug(records_per_page)
        country_id = request.session['session_country_id']
	
	#call_record = request.session['call_record']

    # Set default cause we display page for the first time
    if request.method == 'GET' and not using_session:
        tday = datetime.today()
        from_date = datetime(tday.year, tday.month, 1, 0, 0, 0, 0)
        last_day = ((datetime(tday.year, tday.month, 1, 23, 59, 59, 999999) +
                     relativedelta(months=1)) -
                    relativedelta(days=1)).strftime('%d')
        # to_date = tday.strftime('%Y-%m-' + last_day + ' 23:59')
        to_date = datetime(tday.year, tday.month, int(last_day), 23, 59, 59, 999999)
        start_date = ceil_strdate(str(from_date), 'start', True)
        end_date = ceil_strdate(str(to_date), 'end', True)

        converted_start_date = start_date.strftime('%Y-%m-%d %H:%M')
        converted_end_date = end_date.strftime('%Y-%m-%d %H:%M')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date
        request.session['session_result'] = 1
        field_list = [
            'destination', 'destination_type', 'accountcode',
            'caller_id_number', 'caller_id_number_type', 'duration',
            'duration_type', 'hangup_cause_id',
            'switch_id', 'direction', 'country_id']
        unset_session_var(request, field_list)
        request.session['session_records_per_page'] = records_per_page
	logging.debug("test 2: %s", request.session['session_records_per_page'])
        request.session['session_country_id'] = ''
	

    # Define no of records per page
    records_per_page = int(records_per_page)
    logging.debug(records_per_page)
    sort_col_field_list = ['id', 'caller_id_number', 'destination_number', 'starting_date']
    page_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')
    # Build filter for CDR.object
    kwargs = {}
    if hangup_cause_id and hangup_cause_id != '0':
        kwargs['hangup_cause_id'] = int(hangup_cause_id)

    if switch_id and switch_id != '0':
        kwargs['switch_id'] = int(switch_id)

    if direction and direction != 'all' and direction != "0":
        kwargs['direction'] = direction

    if len(country_id) >= 1 and country_id[0] != 0:
        kwargs['country_id__in'] = country_id

    if start_date:
        kwargs['starting_date__gte'] = start_date

    if end_date:
        kwargs['starting_date__lte'] = end_date

    if destination:
        operator_query = get_filter_operator_str('destination_number', destination_type)
        kwargs[operator_query] = destination

    if duration:
        operator_query = get_filter_operator_int('duration', duration_type)
        kwargs[operator_query] = duration

    if caller_id_number:
        operator_query = get_filter_operator_str('caller_id_number', caller_id_number_type)
        kwargs[operator_query] = caller_id_number
#        kwargs[operator_query] = "asd"

    # user are restricted to their own CDRs
    if not request.user.is_superuser:
        kwargs['user_id'] = request.user.id

    if request.user.is_superuser and accountcode:
        try:
            acc = AccountCode.objects.get(accountcode=accountcode)
            kwargs['user_id'] = acc.user.id
            # on specific accountcode filter let only display that one
            kwargs['accountcode'] = accountcode
        except AccountCode.DoesNotExist:
            # cannot find a user for this accountcode
            pass

    #kwargs['call_record'] = destination

    cdrs = CDR.objects.filter(**kwargs).order_by(page_vars['sort_order'])
    if page_vars['PAGE_NUMBER']:
	    page_vars['start_page'] = ( page_vars['PAGE_NUMBER'] - 1 ) *  records_per_page
    page_vars['end_page'] = page_vars['start_page'] + records_per_page 
    page_cdr_list = cdrs[page_vars['start_page']:page_vars['end_page']]
    cdr_count = cdrs.count()
    logging.debug('Create cdr result')

    # store query_var in session without date
    export_kwargs = kwargs.copy()
    if 'starting_date__gte' in export_kwargs:
        export_kwargs['starting_date__gte'] = export_kwargs['starting_date__gte'].strftime('%Y-%m-%dT%H:%M:%S')
    if 'starting_date__lte' in export_kwargs:
        export_kwargs['starting_date__lte'] = export_kwargs['starting_date__lte'].strftime('%Y-%m-%dT%H:%M:%S')

    request.session['session_export_kwargs'] = export_kwargs
    form = CdrSearchForm(
        initial={
            'from_date': from_date,
            'to_date': to_date,
            'destination': destination,
            'destination_type': destination_type,
            'accountcode': accountcode,
            'caller_id_number': caller_id_number,
            'caller_id_number_type': caller_id_number_type,
            'duration': duration,
            'duration_type': duration_type,
            'result': result,
            'direction': direction,
            'hangup_cause_id': hangup_cause_id,
            'switch_id': switch_id,
            'country_id': country_id,
            'records_per_page': records_per_page
        }
    )

    template_data = {
        'page_cdr_list': page_cdr_list,
        'cdrs': cdrs,
        'form': form,
        'cdr_count': cdr_count,
        'cdr_daily_data': {},
        'col_name_with_order': page_vars['col_name_with_order'],
        'menu': menu,
        'start_date': start_date,
        'end_date': end_date,
        'action': action,
        'result': result,
        'CDR_COLUMN_NAME': CDR_COLUMN_NAME,
        'records_per_page': records_per_page,
        'up_icon': '<i class="glyphicon glyphicon-chevron-up"></i>',
        'down_icon': '<i class="glyphicon glyphicon-chevron-down"></i>'
    }
    logging.debug('CDR View End')
    return render_to_response('cdr/list.html', template_data, context_instance=RequestContext(request))
Esempio n. 22
0
def campaign_list(request):
    """List all campaigns for the logged in user

    **Attributes**:

        * ``template`` - dialer_campaign/campaign/list.html

    **Logic Description**:

        * List all campaigns belonging to the logged in user
    """
    form = CampaignSearchForm(request.user, request.POST or None)
    request.session['pagination_path'] = request.META[
        'PATH_INFO'] + '?' + request.META['QUERY_STRING']
    sort_col_field_list = [
        'id', 'name', 'startingdate', 'status', 'totalcontact'
    ]
    pag_vars = get_pagination_vars(request,
                                   sort_col_field_list,
                                   default_sort_field='id')
    phonebook_id = ''
    status = 'all'
    post_var_with_page = 0

    if form.is_valid():
        field_list = ['phonebook_id', 'status']
        unset_session_var(request, field_list)
        phonebook_id = getvar(request, 'phonebook_id', setsession=True)
        status = getvar(request, 'status', setsession=True)
        post_var_with_page = 1

    # This logic to retain searched result set while accessing pagination or sorting on column
    # post_var_with_page will check following thing
    # 1) if page has previously searched value, then post_var_with_page become 1
    # 2) if not then post_var_with_page remain 0 & flush the session variables' value
    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        phonebook_id = request.session.get('session_phonebook_id')
        status = request.session.get('session_status')
        form = CampaignSearchForm(request.user,
                                  initial={
                                      'status': status,
                                      'phonebook_id': phonebook_id
                                  })

    if post_var_with_page == 0:
        # default / unset session var
        field_list = ['status', 'phonebook_id']
        unset_session_var(request, field_list)

    # Set search on user as default
    kwargs = {'user': request.user}
    if phonebook_id and phonebook_id != '0':
        kwargs['phonebook__id__in'] = [int(phonebook_id)]
    if status and status != 'all':
        kwargs['status'] = status

    all_campaign_list = Campaign.objects.filter(**kwargs).order_by(
        pag_vars['sort_order'])
    campaign_list = all_campaign_list[
        pag_vars['start_page']:pag_vars['end_page']]
    campaign_count = all_campaign_list.count()

    data = {
        'form': form,
        'all_campaign_list': all_campaign_list,
        'campaign_list': campaign_list,
        'total_campaign': campaign_count,
        'CAMPAIGN_COLUMN_NAME': CAMPAIGN_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'info_msg': request.session.get('info_msg'),
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    request.session['info_msg'] = ''
    return render_to_response('dialer_campaign/campaign/list.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 23
0
def cdr_overview(request):
    """CDR graph by hourly/daily/monthly basis

    **Attributes**:

        * ``template`` - cdr/overview.html
        * ``form`` - CdrOverviewForm

    **Logic Description**:

        Get Call records from Postgresql table and build
        all monthly, daily, hourly analytics
    """
    # initialize variables
    hourly_charttype = "lineWithFocusChart"
    daily_charttype = "lineWithFocusChart"
    hourly_chartdata = {'x': []}
    daily_chartdata = {'x': []}
    metric = 'nbcalls'  # Default metric

    action = 'tabs-1'
    tday = datetime.today()
    switch_id = 0
    # assign initial value in form fields
    form = CdrOverviewForm(request.POST or None,
                           initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                    'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                    'switch_id': switch_id})
    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)
    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')
        metric = getvar(request, 'metric')

    # get the number of hour that diff the date
    delta = end_date - start_date
    hour_diff = abs(divmod(delta.days * 86400 + delta.seconds, 60)[0]) / 60
    if hour_diff <= 72:
        display_chart = 'hourly'
    else:
        display_chart = 'daily'

    # check metric is valid
    if metric not in ['nbcalls', 'duration', 'billsec', 'buy_cost', 'sell_cost']:
        metric = 'nbcalls'

    extra_serie = {
        "tooltip": {"y_start": "", "y_end": " " + metric},
        "date_format": "%d %b %y %H:%M%p"
    }

    if display_chart == 'hourly':
        hourly_data = get_report_cdr_per_switch(request.user, 'hour', start_date, end_date, switch_id)

        for switch in hourly_data[metric]["columns"]:
            hourly_chartdata['x'] = hourly_data[metric]["x_timestamp"]
            hourly_chartdata['name' + str(switch)] = get_switch_ip_addr(switch)
            hourly_chartdata['y' + str(switch)] = hourly_data[metric]["values"][str(switch)]
            hourly_chartdata['extra' + str(switch)] = extra_serie

        total_calls = hourly_data["nbcalls"]["total"]
        total_duration = hourly_data["duration"]["total"]
        total_billsec = hourly_data["billsec"]["total"]
        total_buy_cost = hourly_data["buy_cost"]["total"]
        total_sell_cost = hourly_data["sell_cost"]["total"]

    elif display_chart == 'daily':
        daily_data = get_report_cdr_per_switch(request.user, 'day', start_date, end_date, switch_id)

        for switch in daily_data[metric]["columns"]:
            daily_chartdata['x'] = daily_data[metric]["x_timestamp"]
            daily_chartdata['name' + str(switch)] = get_switch_ip_addr(switch)
            daily_chartdata['y' + str(switch)] = daily_data[metric]["values"][str(switch)]
            daily_chartdata['extra' + str(switch)] = extra_serie

        total_calls = daily_data["nbcalls"]["total"]
        total_duration = daily_data["duration"]["total"]
        total_billsec = daily_data["billsec"]["total"]
        total_buy_cost = daily_data["buy_cost"]["total"]
        total_sell_cost = daily_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    country_data = custom_sql_aggr_top_country(request.user, switch_id, 10, start_date, end_date)

    variables = {
        'action': action,
        'form': form,
        'display_chart': display_chart,
        'start_date': start_date,
        'end_date': end_date,
        'metric': metric,
        'hourly_chartdata': hourly_chartdata,
        'hourly_charttype': hourly_charttype,
        'hourly_chartcontainer': 'hourly_container',
        'hourly_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %y %H%p',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'daily_chartdata': daily_chartdata,
        'daily_charttype': daily_charttype,
        'daily_chartcontainer': 'daily_container',
        'daily_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
    }
    return render_to_response('cdr/overview.html', variables, context_instance=RequestContext(request))
Esempio n. 24
0
def cdr_country_report(request):
    """CDR country report

    **Attributes**:

        * ``template`` - cdr/country_report.html
        * ``form`` - CountryReportForm

    **Logic Description**:

        Retrieve call records from Postgresql for all countries
        and create reporting information for those countries
    """
    metric = 'nbcalls'
    tday = datetime.today()

    switch_id = 0
    hourly_charttype = "lineWithFocusChart"
    hourly_chartdata = {'x': []}
    country_id_list = []
    total_metric = 0

    # assign initial value in form fields
    form = CountryReportForm(request.POST or None,
                             initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                    'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                    'switch_id': switch_id})

    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')
        metric = getvar(request, 'metric')
        country_id = form.cleaned_data['country_id']
        # convert list value in int
        country_id_list = [int(row) for row in country_id]
        # handle 0 (All) selection
        if 0 in country_id_list:
            country_id_list = []

    # check metric is valid
    if metric not in ['nbcalls', 'duration', 'billsec', 'buy_cost', 'sell_cost']:
        metric = 'nbcalls'

    hourly_data = get_report_cdr_per_country(request.user, 'hour', start_date, end_date, switch_id, country_id_list)

    extra_serie = {
        "tooltip": {"y_start": "", "y_end": " " + metric},
        "date_format": "%d %b %y %H:%M%p"
    }
    for country in hourly_data[metric]["columns"]:
        hourly_chartdata['x'] = hourly_data[metric]["x_timestamp"]
        country_name = get_country_name(int(country)).encode('utf-8')
        hourly_chartdata['name' + str(country)] = country_name.decode('ascii', 'ignore').replace("'", " ")
        hourly_chartdata['y' + str(country)] = hourly_data[metric]["values"][str(country)]
        hourly_chartdata['extra' + str(country)] = extra_serie

    total_calls = hourly_data["nbcalls"]["total"]
    total_duration = hourly_data["duration"]["total"]
    total_billsec = hourly_data["billsec"]["total"]
    total_buy_cost = hourly_data["buy_cost"]["total"]
    total_sell_cost = hourly_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    top_country = 10
    country_data = custom_sql_aggr_top_country(request.user, switch_id, top_country, start_date, end_date)

    # Build pie chart data for last 24h calls per country
    (xdata, ydata) = ([], [])
    for country in country_data:
        xdata.append(get_country_name(country["country_id"]))
        ydata.append(percentage(country["nbcalls"], total_calls))

    color_list = ['#FFC36C', '#FFFF9D', '#BEEB9F', '#79BD8F', '#FFB391',
        '#58A6A6', '#86BF30', '#F2D022', '#D9AA1E', '#D98236']

    extra_serie = {"tooltip": {"y_start": "", "y_end": " %"}, "color_list": color_list}
    country_analytic_chartdata = {'x': xdata, 'y1': ydata, 'extra1': extra_serie}
    country_analytic_charttype = "pieChart"

    country_extra = {
        'x_is_date': False,
        'x_axis_format': '',
        'tag_script_js': True,
        'jquery_on_ready': True,
    }

    data = {
        'action': 'tabs-1',
        'total_metric': total_metric,
        'start_date': start_date,
        'end_date': end_date,
        'metric': metric,
        'form': form,
        'NUM_COUNTRY': settings.NUM_COUNTRY,
        'hourly_charttype': hourly_charttype,
        'hourly_chartdata': hourly_chartdata,
        'hourly_chartcontainer': 'hourly_container',
        'hourly_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': False,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,

        'country_analytic_charttype': country_analytic_charttype,
        'country_analytic_chartdata': country_analytic_chartdata,
        'country_chartcontainer': 'country_piechart_container',
        'country_extra': country_extra,
        'top_country': top_country,
    }
    return render_to_response('cdr/country_report.html', data, context_instance=RequestContext(request))
Esempio n. 25
0
def world_map_view(request):
    """CDR world report

    **Attributes**:

        * ``template`` - cdr/world_map.html
        * ``form`` - WorldForm
    """
    logging.debug('CDR world report view start')
    action = 'tabs-1'
    switch_id = 0
    tday = datetime.today()
    # Assign initial value in form fields
    form = WorldForm(request.POST or None,
                     initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                              'to_date': tday.strftime('%Y-%m-%d 23:55'),
                              'switch_id': switch_id})

    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')

    # Get top 10 of country calls
    top_country = 300
    country_data = custom_sql_aggr_top_country(request.user, switch_id, top_country, start_date, end_date)

    world_analytic_array = []
    max_nbcalls = 0
    for country in country_data:
        if not country["country_id"]:
            continue
        # append data to world_analytic_array with following order
        # country id|country name|call count|call duration|country_id|buy cost|sell cost
        country_data = {}
        country_data["country_id"] = int(country["country_id"])
        country_data["country_iso3"] = get_country_name(int(country["country_id"]), type='iso3').upper()
        country_data["country_name"] = get_country_name(int(country["country_id"]))
        country_data["nbcalls"] = int(country["nbcalls"])
        if country_data["nbcalls"] > max_nbcalls:
            max_nbcalls = country_data["nbcalls"]
        country_data["duration"] = int(country["duration"])
        country_data["billsec"] = int(country["billsec"])
        country_data["buy_cost"] = float(country["buy_cost"])
        country_data["sell_cost"] = float(country["sell_cost"])
        world_analytic_array.append(country_data)

    max_nbcalls = int(round(max_nbcalls, -3))

    call_crates = generate_crate(max_nbcalls)

    variables = {
        'form': form,
        'start_date': start_date,
        'end_date': end_date,
        'world_analytic_array': world_analytic_array,
        'action': action,
        'call_crates': call_crates,
    }
    return render_to_response('cdr/world_map.html',
                              variables, context_instance=RequestContext(request))
Esempio n. 26
0
def campaign_list(request):
    """List all campaigns for the logged in user

    **Attributes**:

        * ``template`` - dialer_campaign/campaign/list.html

    **Logic Description**:

        * List all campaigns belonging to the logged in user
    """
    form = CampaignSearchForm(request.user, request.POST or None)
    request.session['pagination_path'] = request.META['PATH_INFO'] + '?' + request.META['QUERY_STRING']
    sort_col_field_list = ['id', 'name', 'startingdate', 'status', 'totalcontact']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')
    phonebook_id = ''
    status = 'all'
    post_var_with_page = 0

    if form.is_valid():
        field_list = ['phonebook_id', 'status']
        unset_session_var(request, field_list)
        phonebook_id = getvar(request, 'phonebook_id', setsession=True)
        status = getvar(request, 'status', setsession=True)
        post_var_with_page = 1

    # This logic to retain searched result set while accessing pagination or sorting on column
    # post_var_with_page will check following thing
    # 1) if page has previously searched value, then post_var_with_page become 1
    # 2) if not then post_var_with_page remain 0 & flush the session variables' value
    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        phonebook_id = request.session.get('session_phonebook_id')
        status = request.session.get('session_status')
        form = CampaignSearchForm(request.user, initial={'status': status, 'phonebook_id': phonebook_id})

    if post_var_with_page == 0:
        # default / unset session var
        field_list = ['status', 'phonebook_id']
        unset_session_var(request, field_list)

    # Set search on user as default
    kwargs = {'user': request.user}
    if phonebook_id and phonebook_id != '0':
        kwargs['phonebook__id__in'] = [int(phonebook_id)]
    if status and status != 'all':
        kwargs['status'] = status

    all_campaign_list = Campaign.objects.filter(**kwargs).order_by(pag_vars['sort_order'])
    campaign_list = all_campaign_list[pag_vars['start_page']:pag_vars['end_page']]
    campaign_count = all_campaign_list.count()

    data = {
        'form': form,
        'all_campaign_list': all_campaign_list,
        'campaign_list': campaign_list,
        'total_campaign': campaign_count,
        'CAMPAIGN_COLUMN_NAME': CAMPAIGN_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'info_msg': request.session.get('info_msg'),
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    request.session['info_msg'] = ''
    return render_to_response('dialer_campaign/campaign/list.html', data, context_instance=RequestContext(request))
Esempio n. 27
0
def dnc_contact_list(request):
    """DNC Contact list for the logged in user

    **Attributes**:

        * ``template`` - dnc/dnc_contact/list.html
        * ``form`` - ContactSearchForm

    **Logic Description**:

        * List all dnc contacts from dnc lists belonging to the logged in user
    """
    sort_col_field_list = ["id", "dnc", "phone_number", "updated_date"]
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field="id")
    form = DNCContactSearchForm(request.user, request.POST or None)
    dnc_id_list = DNC.objects.values_list("id", flat=True).filter(user=request.user)
    phone_number = ""
    dnc = ""
    post_var_with_page = 0
    if form.is_valid():
        request.session["session_phone_number"] = ""
        request.session["session_dnc"] = ""
        post_var_with_page = 1
        phone_number = getvar(request, "phone_number", setsession=True)
        dnc = getvar(request, "dnc", setsession=True)

    if request.GET.get("page") or request.GET.get("sort_by"):
        post_var_with_page = 1
        phone_number = request.session.get("session_phone_number")
        dnc = request.session.get("session_dnc")
        form = DNCContactSearchForm(request.user, initial={"phone_number": phone_number, "dnc": dnc})

    if post_var_with_page == 0:
        # default
        # unset session var
        request.session["session_phone_number"] = ""
        request.session["session_dnc"] = ""

    kwargs = {"dnc__in": dnc_id_list}
    if dnc and dnc != "0":
        kwargs["dnc_id"] = dnc

    phone_number_type = "1"
    phone_number = source_desti_field_chk(phone_number, phone_number_type, "phone_number")
    for i in phone_number:
        kwargs[i] = phone_number[i]

    phone_number_list = []
    all_phone_number_list = []
    phone_number_count = 0

    if dnc_id_list:
        all_phone_number_list = (
            DNCContact.objects.values("id", "dnc__name", "phone_number", "updated_date")
            .filter(**kwargs)
            .order_by(pag_vars["sort_order"])
        )

        phone_number_list = all_phone_number_list[pag_vars["start_page"] : pag_vars["end_page"]]
        phone_number_count = all_phone_number_list.count()

    data = {
        "phone_number_list": phone_number_list,
        "all_phone_number_list": all_phone_number_list,
        "total_phone_numbers": phone_number_count,
        "DNC_CONTACT_COLUMN_NAME": DNC_CONTACT_COLUMN_NAME,
        "col_name_with_order": pag_vars["col_name_with_order"],
        "msg": request.session.get("msg"),
        "error_msg": request.session.get("error_msg"),
        "form": form,
    }
    request.session["msg"] = ""
    request.session["error_msg"] = ""
    return render_to_response("dnc/dnc_contact/list.html", data, context_instance=RequestContext(request))
Esempio n. 28
0
    def subscriber_report(self, request):
        """
        Get subscriber report

        **Attributes**:

            * ``form`` - SubscriberReportForm
            * ``template`` - admin/dialer_campaign/subscriber/subscriber_report.html
        """
        opts = Subscriber._meta
        tday = datetime.today()
        form = SubscriberReportForm(request.POST or None,
                                    initial={"from_date": tday.strftime("%Y-%m-%d"),
                                             "to_date": tday.strftime("%Y-%m-%d")})
        total_subscriber = 0
        total_pending = 0
        total_pause = 0
        total_abort = 0
        total_fail = 0
        total_sent = 0
        total_in_process = 0
        total_not_auth = 0
        total_completed = 0

        if form.is_valid():
            start_date = ''
            end_date = ''
            from_date = getvar(request, 'from_date')
            to_date = getvar(request, 'to_date')
            start_date = ceil_strdate(str(from_date), 'start')
            end_date = ceil_strdate(str(to_date), 'end')
            campaign_id = getvar(request, 'campaign_id')
            kwargs = {}
            if start_date and end_date:
                kwargs['updated_date__range'] = (start_date, end_date)
            if start_date and end_date == '':
                kwargs['updated_date__gte'] = start_date
            if start_date == '' and end_date:
                kwargs['updated_date__lte'] = end_date
            if campaign_id and campaign_id != '0':
                kwargs['campaign_id'] = campaign_id

            select_data = {"updated_date": "SUBSTR(CAST(updated_date as CHAR(30)),1,10)"}
            subscriber = Subscriber.objects.filter(**kwargs).extra(select=select_data)\
                .values('updated_date', 'status')\
                .annotate(Count('updated_date'))\
                .order_by('updated_date')

            for i in subscriber:
                total_subscriber += i['updated_date__count']
                if i['status'] == SUBSCRIBER_STATUS.PENDING:
                    total_pending += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.PAUSE:
                    total_pause += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.ABORT:
                    total_abort += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.FAIL:
                    total_fail += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.SENT:
                    total_sent += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.IN_PROCESS:
                    total_in_process += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.NOT_AUTHORIZED:
                    total_not_auth += i['updated_date__count']
                else:
                    # status COMPLETED
                    total_completed += i['updated_date__count']

        ctx = RequestContext(request, {
            'form': form,
            'opts': opts,
            'total_subscriber': total_subscriber,
            'total_pending': total_pending,
            'total_pause': total_pause,
            'total_abort': total_abort,
            'total_fail': total_fail,
            'total_sent': total_sent,
            'total_in_process': total_in_process,
            'total_not_auth': total_not_auth,
            'total_completed': total_completed,
            'SUBSCRIBER_STATUS_NAME': SUBSCRIBER_STATUS_NAME,
            'model_name': opts.object_name.lower(),
            'app_label': _('Dialer Campaign'),
            'title': _('subscriber report'),
        })

        return render_to_response('admin/dialer_campaign/subscriber/subscriber_report.html', context_instance=ctx)
Esempio n. 29
0
def voipcall_report(request):
    """VoIP Call Report

    **Attributes**:

        * ``form`` - VoipSearchForm
        * ``template`` - dialer_cdr/voipcall_report.html

    **Logic Description**:

        * Get VoIP call list according to search parameters for loggedin user

    **Important variable**:

        * ``request.session['voipcall_record_kwargs']`` - stores voipcall kwargs
    """
    sort_col_field_list = ['starting_date', 'leg_type', 'disposition', 'used_gateway', 'callerid',
                           'callid', 'phone_number', 'duration', 'billsec', 'amd_status']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='starting_date')
    action = 'tabs-1'
    form = VoipSearchForm(request.user, request.POST or None)
    if form.is_valid():
        # Valid form
        field_list = ['start_date', 'end_date', 'disposition', 'campaign_id', 'leg_type']
        unset_session_var(request, field_list)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        disposition = getvar(request, 'disposition', setsession=True)
        campaign_id = getvar(request, 'campaign_id', setsession=True)
        leg_type = getvar(request, 'leg_type', setsession=True)
        form = VoipSearchForm(request.user, initial={'from_date': start_date.strftime('%Y-%m-%d'),
                                                     'to_date': end_date.strftime('%Y-%m-%d'),
                                                     'disposition': disposition,
                                                     'campaign_id': campaign_id,
                                                     'leg_type': leg_type})

    elif request.GET.get('page') or request.GET.get('sort_by'):
        # Pagination / Sort
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(str(start_date), 'start')
        end_date = ceil_strdate(str(end_date), 'end')

        disposition = request.session.get('session_disposition')
        campaign_id = request.session.get('session_campaign_id')
        leg_type = request.session.get('session_leg_type')
        form = VoipSearchForm(request.user, initial={'from_date': start_date.strftime('%Y-%m-%d'),
                                                     'to_date': end_date.strftime('%Y-%m-%d'),
                                                     'disposition': disposition,
                                                     'campaign_id': campaign_id,
                                                     'leg_type': leg_type})
    else:
        # Default
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-%d')
        to_date = tday.strftime('%Y-%m-%d')
        start_date = datetime(tday.year, tday.month, tday.day, 0, 0, 0, 0).replace(tzinfo=utc)
        end_date = datetime(tday.year, tday.month, tday.day, 23, 59, 59, 999999).replace(tzinfo=utc)
        disposition = 'all'
        campaign_id = 0
        leg_type = ''
        form = VoipSearchForm(request.user, initial={'from_date': from_date,
                                                     'to_date': to_date,
                                                     'disposition': disposition,
                                                     'campaign_id': campaign_id,
                                                     'leg_type': leg_type})
        # unset session var
        request.session['session_start_date'] = start_date
        request.session['session_end_date'] = end_date
        request.session['session_disposition'] = disposition
        request.session['session_campaign_id'] = ''
        request.session['session_leg_type'] = ''

    kwargs = {}
    if start_date and end_date:
        kwargs['starting_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['starting_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['starting_date__lte'] = end_date

    if disposition and disposition != 'all':
        kwargs['disposition__exact'] = disposition

    if campaign_id and int(campaign_id) != 0:
        kwargs['callrequest__campaign_id'] = campaign_id

    if leg_type and leg_type != '':
        kwargs['leg_type__exact'] = leg_type

    if not request.user.is_superuser:
        kwargs['user_id'] = request.user.id

    voipcall_list = VoIPCall.objects.filter(**kwargs)
    all_voipcall_list = voipcall_list.values_list('id', flat=True)

    # Session variable is used to get record set with searched option
    # into export file
    request.session['voipcall_record_kwargs'] = kwargs

    if request.GET.get('page') or request.GET.get('sort_by'):
        daily_data = request.session['voipcall_daily_data']
    else:
        if not voipcall_list:
            request.session['voipcall_daily_data'] = ''
        daily_data = get_voipcall_daily_data(voipcall_list)
        request.session['voipcall_daily_data'] = daily_data

    voipcall_list = voipcall_list.order_by(pag_vars['sort_order'])[pag_vars['start_page']:pag_vars['end_page']]

    data = {
        'form': form,
        'total_data': daily_data['total_data'],
        'total_duration': daily_data['total_duration'],
        'total_calls': daily_data['total_calls'],
        'total_avg_duration': daily_data['total_avg_duration'],
        'max_duration': daily_data['max_duration'],
        'all_voipcall_list': all_voipcall_list,
        'voipcall_list': voipcall_list,
        'CDR_REPORT_COLUMN_NAME': CDR_REPORT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'start_date': start_date,
        'end_date': end_date,
        'action': action,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dialer_cdr/voipcall_report.html', data, context_instance=RequestContext(request))
Esempio n. 30
0
def cdr_daily_comparison(request):
    """
    Hourly CDR graph that compare with previous dates

    **Attributes**:

        * ``template`` - cdr/daily_comparison.html
        * ``form`` - CompareCallSearchForm

    **Logic Description**:

        get the call records aggregated from the CDR table
        using the materialized view and compare with other date records


    # hourly_charttype = "lineWithFocusChart"
    # daily_charttype = "lineWithFocusChart"
    # hourly_chartdata = {'x': []}
    # daily_chartdata = {'x': []}
    # metric = 'nbcalls'  # Default metric

    """
    # Default
    metric = 'nbcalls'
    switch_id = 0
    hourly_charttype = "multiBarChart"
    hourly_chartdata = {'x': []}
    compare_days = 2
    compare_type = COMPARE_WITH.previous_days
    today_date = datetime.today()
    form = CompareCallSearchForm(request.POST or None,
                                 initial={'from_date': today_date.strftime('%Y-%m-%d'),
                                          'compare_days': compare_days,
                                          'compare_type': compare_type,
                                          'switch_id': 0})

    today_date = datetime(today_date.year, today_date.month, today_date.day)
    current_date = today_date

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        current_date = ceil_strdate(str(from_date), 'start')
        # current_date = trunc_date_start(from_date)
        switch_id = getvar(request, 'switch_id')
        compare_days = int(getvar(request, 'compare_days'))
        metric = getvar(request, 'metric')

    kwargs = {}

    if switch_id and switch_id != '0':
        kwargs['switch_id'] = int(switch_id)

    xdata = [i for i in range(0, 24)]
    hourly_chartdata = {'x': xdata}

    y_count = 1
    for nday in range(1, compare_days + 1):
        start_date = current_date + relativedelta(days=-int(nday-1))
        start_date = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0, 0)
        end_date = current_date + relativedelta(days=-int(nday-1))
        end_date = datetime(end_date.year, end_date.month, end_date.day, 23, 59, 59, 999999)
        # Get hourly Data
        hourly_data = get_report_compare_cdr(request.user, 'hour', start_date, end_date, switch_id)

        extra_serie = {
            "tooltip": {"y_start": "", "y_end": " " + metric}
        }
        # We only need to set x axis once, so let's do it for nbcalls
        # hourly_chartdata['x'] = hourly_data["nbcalls"]["x_timestamp"]
        for switch in hourly_data[metric]["columns"]:
            serie = get_switch_ip_addr(switch) + "_day_" + str(nday)
            hourly_chartdata['name' + str(y_count)] = serie
            hourly_chartdata['y' + str(y_count)] = hourly_data[metric]["values"][str(switch)]
            hourly_chartdata['extra' + str(y_count)] = extra_serie
            y_count += 1

    variables = {
        'form': form,
        'from_date': current_date,
        'metric': metric,
        'compare_days': compare_days,
        'hourly_charttype': hourly_charttype,
        'hourly_chartdata': hourly_chartdata,
        'hourly_chartcontainer': 'hourly_chartcontainer',
        'hourly_extra': {
            'x_is_date': False,
            'x_axis_format': '',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
    }
    return render_to_response('cdr/daily_comparison.html', variables, context_instance=RequestContext(request))
Esempio n. 31
0
def billing_report(request):
    """CDR billing graph by daily basis

    **Attributes**:

        * ``template`` - voip_billing/billing_report.html
        * ``form`` - BillingReportForm

    **Logic Description**:

        Retrieve call records from PostgreSQL and build the
        daily billing analytics for given date range
    """
    switch_id = 0
    tday = datetime.today()
    total_data = []
    charttype = "lineWithFocusChart"
    hourly_chartdata = {"x": []}

    form = BillingReportForm(request.POST or None,
                             initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                    'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                    'switch_id': switch_id})
    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')

    metrics = ['buy_cost', 'sell_cost']

    hourly_data = get_report_cdr_per_switch(request.user, 'hour', start_date, end_date, switch_id)

    hourly_chartdata['x'] = hourly_data["nbcalls"]["x_timestamp"]

    i = 0
    for metric in metrics:
        extra_serie = {
            "tooltip": {"y_start": "", "y_end": " " + metric},
            "date_format": "%d %b %y %H:%M%p"
        }
        for switch in hourly_data[metric]["columns"]:
            i = i + 1
            hourly_chartdata['name' + str(i)] = get_switch_ip_addr(switch) + "_" + metric
            hourly_chartdata['y' + str(i)] = hourly_data[metric]["values"][str(switch)]
            hourly_chartdata['extra' + str(i)] = extra_serie

    total_calls = hourly_data["nbcalls"]["total"]
    total_duration = hourly_data["duration"]["total"]
    total_billsec = hourly_data["billsec"]["total"]
    total_buy_cost = hourly_data["buy_cost"]["total"]
    total_sell_cost = hourly_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    country_data = custom_sql_aggr_top_country(request.user, switch_id, 10, start_date, end_date)

    data = {
        'form': form,
        'total_data': total_data,
        'start_date': start_date,
        'end_date': end_date,
        'charttype': charttype,
        'chartdata': hourly_chartdata,
        'chartcontainer': 'chart_container',
        'extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
    }
    return render_to_response('voip_billing/billing_report.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 32
0
def cdr_overview(request):
    """CDR graph by hourly/daily/monthly basis

    **Attributes**:

        * ``template`` - cdr/overview.html
        * ``form`` - CdrOverviewForm

    **Logic Description**:

        Get Call records from Postgresql table and build
        all monthly, daily, hourly analytics
    """
    # initialize variables
    hourly_charttype = "lineWithFocusChart"
    daily_charttype = "lineWithFocusChart"
    hourly_chartdata = {'x': []}
    daily_chartdata = {'x': []}
    metric = 'nbcalls'  # Default metric

    action = 'tabs-1'
    tday = datetime.today()
    switch_id = 0
    # assign initial value in form fields
    form = CdrOverviewForm(request.POST or None,
                           initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                                    'to_date': tday.strftime('%Y-%m-%d 23:55'),
                                    'switch_id': switch_id})
    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)
    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')
        metric = getvar(request, 'metric')

    # get the number of hour that diff the date
    delta = end_date - start_date
    hour_diff = abs(divmod(delta.days * 86400 + delta.seconds, 60)[0]) / 60
    if hour_diff <= 72:
        display_chart = 'hourly'
    else:
        display_chart = 'daily'

    # check metric is valid
    if metric not in ['nbcalls', 'duration', 'billsec', 'buy_cost', 'sell_cost']:
        metric = 'nbcalls'

    extra_serie = {
        "tooltip": {"y_start": "", "y_end": " " + metric},
        "date_format": "%d %b %y %H:%M%p"
    }

    if display_chart == 'hourly':
        hourly_data = get_report_cdr_per_switch(request.user, 'hour', start_date, end_date, switch_id)

        for switch in hourly_data[metric]["columns"]:
            hourly_chartdata['x'] = hourly_data[metric]["x_timestamp"]
            hourly_chartdata['name' + str(switch)] = get_switch_ip_addr(switch)
            hourly_chartdata['y' + str(switch)] = hourly_data[metric]["values"][str(switch)]
            hourly_chartdata['extra' + str(switch)] = extra_serie

        total_calls = hourly_data["nbcalls"]["total"]
        total_duration = hourly_data["duration"]["total"]
        total_billsec = hourly_data["billsec"]["total"]
        total_buy_cost = hourly_data["buy_cost"]["total"]
        total_sell_cost = hourly_data["sell_cost"]["total"]

    elif display_chart == 'daily':
        daily_data = get_report_cdr_per_switch(request.user, 'day', start_date, end_date, switch_id)

        for switch in daily_data[metric]["columns"]:
            daily_chartdata['x'] = daily_data[metric]["x_timestamp"]
            daily_chartdata['name' + str(switch)] = get_switch_ip_addr(switch)
            daily_chartdata['y' + str(switch)] = daily_data[metric]["values"][str(switch)]
            daily_chartdata['extra' + str(switch)] = extra_serie

        total_calls = daily_data["nbcalls"]["total"]
        total_duration = daily_data["duration"]["total"]
        total_billsec = daily_data["billsec"]["total"]
        total_buy_cost = daily_data["buy_cost"]["total"]
        total_sell_cost = daily_data["sell_cost"]["total"]

    # Calculate the Average Time of Call
    metric_aggr = calculate_act_acd(total_calls, total_duration)

    # Get top 10 of country calls
    country_data = custom_sql_aggr_top_country(request.user, switch_id, 10, start_date, end_date)

    variables = {
        'action': action,
        'form': form,
        'display_chart': display_chart,
        'start_date': start_date,
        'end_date': end_date,
        'metric': metric,
        'hourly_chartdata': hourly_chartdata,
        'hourly_charttype': hourly_charttype,
        'hourly_chartcontainer': 'hourly_container',
        'hourly_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %y %H%p',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'daily_chartdata': daily_chartdata,
        'daily_charttype': daily_charttype,
        'daily_chartcontainer': 'daily_container',
        'daily_extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %Y',
            'tag_script_js': True,
            'jquery_on_ready': True,
        },
        'total_calls': total_calls,
        'total_duration': total_duration,
        'total_billsec': total_billsec,
        'total_buy_cost': total_buy_cost,
        'total_sell_cost': total_sell_cost,
        'metric_aggr': metric_aggr,
        'country_data': country_data,
    }
    return render_to_response('cdr/overview.html', variables, context_instance=RequestContext(request))
Esempio n. 33
0
def event_list(request):
    """Event list for the logged in user

    **Attributes**:

        * ``template`` - appointment/event/list.html

    **Logic Description**:

        * List all events which belong to the logged in user.
    """
    today = datetime.utcnow().replace(tzinfo=utc)
    form = EventSearchForm(request.user, request.POST or None, initial={"start": today.strftime("%Y-%m-%d %H:%M")})
    sort_col_field_list = ["id", "start", "end", "title", "calendar", "status", "created_on"]
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field="id")

    start_date = ""
    calendar_id = ""
    calendar_user_id = ""
    post_var_with_page = 0
    if form.is_valid():
        field_list = ["start_date", "calendar_id", "calendar_user_id"]
        unset_session_var(request, field_list)

        start_date = getvar(request, "start_date")
        start_date = ceil_strdate(str(start_date), "start")
        converted_start_date = start_date.strftime("%Y-%m-%d")
        request.session["session_start_date"] = converted_start_date

        calendar_id = getvar(request, "calendar_id", setsession=True)
        calendar_user_id = getvar(request, "calendar_user_id", setsession=True)
        post_var_with_page = 1

    if request.GET.get("page") or request.GET.get("sort_by"):
        post_var_with_page = 1
        start_date = request.session.get("session_start_date")
        start_date = ceil_strdate(start_date, "start")
        calendar_id = request.session.get("session_calendar_id")
        calendar_user_id = request.session.get("session_calendar_user_id")
        form = EventSearchForm(
            request.user,
            initial={
                "start_date": start_date.strftime("%Y-%m-%d %H:%M"),
                "calendar_id": calendar_id,
                "calendar_user_id": calendar_user_id,
            },
        )

    if post_var_with_page == 0:
        # default unset session var
        field_list = ["start_date", "calendar_id", "calendar_user_id"]
        unset_session_var(request, field_list)

    kwargs = {}
    calendar_user_id_list = get_calendar_user_id_list(request.user)
    kwargs["calendar__user_id__in"] = calendar_user_id_list
    if start_date:
        kwargs["start__gte"] = start_date

    if calendar_id and int(calendar_id) != 0:
        kwargs["calendar_id"] = calendar_id

    if calendar_user_id and int(calendar_user_id) != 0:
        kwargs["creator_id"] = calendar_user_id

    all_event_list = Event.objects.filter(**kwargs).order_by(pag_vars["sort_order"])
    event_list = all_event_list[pag_vars["start_page"] : pag_vars["end_page"]]
    data = {
        "form": form,
        "msg": request.session.get("msg"),
        "all_event_list": all_event_list,
        "event_list": event_list,
        "total_event": all_event_list.count(),
        "EVENT_COLUMN_NAME": EVENT_COLUMN_NAME,
        "col_name_with_order": pag_vars["col_name_with_order"],
    }
    request.session["msg"] = ""
    request.session["error_msg"] = ""
    return render_to_response("appointment/event/list.html", data, context_instance=RequestContext(request))
Esempio n. 34
0
def world_map_view(request):
    """CDR world report

    **Attributes**:

        * ``template`` - cdr/world_map.html
        * ``form`` - WorldForm
    """
    logging.debug('CDR world report view start')
    action = 'tabs-1'
    switch_id = 0
    tday = datetime.today()
    # Assign initial value in form fields
    form = WorldForm(request.POST or None,
                     initial={'from_date': tday.strftime('%Y-%m-%d 00:00'),
                              'to_date': tday.strftime('%Y-%m-%d 23:55'),
                              'switch_id': switch_id})

    start_date = trunc_date_start(tday)
    end_date = trunc_date_end(tday)

    if form.is_valid():
        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = trunc_date_start(from_date)
        end_date = trunc_date_end(to_date)
        switch_id = getvar(request, 'switch_id')

    # Get top 10 of country calls
    top_country = 300
    country_data = custom_sql_aggr_top_country(request.user, switch_id, top_country, start_date, end_date)

    world_analytic_array = []
    max_nbcalls = 0
    for country in country_data:
        if not country["country_id"]:
            continue
        # append data to world_analytic_array with following order
        # country id|country name|call count|call duration|country_id|buy cost|sell cost
        country_data = {}
        country_data["country_id"] = int(country["country_id"])
        country_data["country_iso3"] = get_country_name(int(country["country_id"]), type='iso3').upper()
        country_data["country_name"] = get_country_name(int(country["country_id"]))
        country_data["nbcalls"] = int(country["nbcalls"])
        if country_data["nbcalls"] > max_nbcalls:
            max_nbcalls = country_data["nbcalls"]
        country_data["duration"] = int(country["duration"])
        country_data["billsec"] = int(country["billsec"])
        country_data["buy_cost"] = float(country["buy_cost"])
        country_data["sell_cost"] = float(country["sell_cost"])
        world_analytic_array.append(country_data)

    max_nbcalls = int(round(max_nbcalls, -3))

    call_crates = generate_crate(max_nbcalls)

    variables = {
        'form': form,
        'start_date': start_date,
        'end_date': end_date,
        'world_analytic_array': world_analytic_array,
        'action': action,
        'call_crates': call_crates,
    }
    return render_to_response('cdr/world_map.html',
                              variables, context_instance=RequestContext(request))
Esempio n. 35
0
def event_list(request):
    """Event list for the logged in user

    **Attributes**:

        * ``template`` - appointment/event/list.html

    **Logic Description**:

        * List all events which belong to the logged in user.
    """
    today = datetime.utcnow().replace(tzinfo=utc)
    form = EventSearchForm(request.user,
                           request.POST or None,
                           initial={'start': today.strftime('%Y-%m-%d %H:%M')})
    sort_col_field_list = [
        'id', 'start', 'end', 'title', 'calendar', 'status', 'created_on'
    ]
    pag_vars = get_pagination_vars(request,
                                   sort_col_field_list,
                                   default_sort_field='id')

    start_date = ''
    calendar_id = ''
    calendar_user_id = ''
    post_var_with_page = 0
    if form.is_valid():
        field_list = ['start_date', 'calendar_id', 'calendar_user_id']
        unset_session_var(request, field_list)

        start_date = getvar(request, 'start_date')
        start_date = ceil_strdate(str(start_date), 'start')
        converted_start_date = start_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date

        calendar_id = getvar(request, 'calendar_id', setsession=True)
        calendar_user_id = getvar(request, 'calendar_user_id', setsession=True)
        post_var_with_page = 1

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        start_date = ceil_strdate(start_date, 'start')
        calendar_id = request.session.get('session_calendar_id')
        calendar_user_id = request.session.get('session_calendar_user_id')
        form = EventSearchForm(request.user,
                               initial={
                                   'start_date':
                                   start_date.strftime('%Y-%m-%d %H:%M'),
                                   'calendar_id':
                                   calendar_id,
                                   'calendar_user_id':
                                   calendar_user_id,
                               })

    if post_var_with_page == 0:
        # default unset session var
        field_list = ['start_date', 'calendar_id', 'calendar_user_id']
        unset_session_var(request, field_list)

    kwargs = {}
    calendar_user_id_list = get_calendar_user_id_list(request.user)
    kwargs['calendar__user_id__in'] = calendar_user_id_list
    if start_date:
        kwargs['start__gte'] = start_date

    if calendar_id and int(calendar_id) != 0:
        kwargs['calendar_id'] = calendar_id

    if calendar_user_id and int(calendar_user_id) != 0:
        kwargs['creator_id'] = calendar_user_id

    all_event_list = Event.objects.filter(**kwargs).order_by(
        pag_vars['sort_order'])
    event_list = all_event_list[pag_vars['start_page']:pag_vars['end_page']]
    data = {
        'form': form,
        'msg': request.session.get('msg'),
        'all_event_list': all_event_list,
        'event_list': event_list,
        'total_event': all_event_list.count(),
        'EVENT_COLUMN_NAME': EVENT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('appointment/event/list.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 36
0
    def changelist_view(self, request, extra_context=None):
        """
        Override changelist_view method of django-admin for search parameters

        **Attributes**:

            * ``form`` - AdminVoipSearchForm
            * ``template`` - admin/dialer_cdr/voipcall/change_list.html

        **Logic Description**:

            * VoIP report Record Listing with search option & Daily Call Report
              search Parameters: by date, by status and by billed.
        """
        opts = VoIPCall._meta
        query_string = ''
        form = AdminVoipSearchForm()
        if request.method == 'POST':
            # Session variable get record set with searched option into export file
            request.session['admin_voipcall_record_kwargs'] = voipcall_record_common_fun(request)

            query_string = voipcall_search_admin_form_fun(request)
            return HttpResponseRedirect("/admin/%s/%s/?%s" % (opts.app_label, opts.object_name.lower(), query_string))
        else:
            disposition = ''
            from_date = ''
            to_date = ''
            campaign_id = ''
            leg_type = ''

            from_date = getvar(request, 'starting_date__gte')
            to_date = getvar(request, 'starting_date__lte')[0:10]
            disposition = getvar(request, 'disposition__exact')
            campaign_id = getvar(request, 'callrequest__campaign_id')
            leg_type = getvar(request, 'leg_type__exact')

            form = AdminVoipSearchForm(initial={'disposition': disposition,
                                                'from_date': from_date,
                                                'to_date': to_date,
                                                'campaign_id': campaign_id,
                                                'leg_type': leg_type})

        ChangeList = self.get_changelist(request)
        try:
            cl = ChangeList(request, self.model, self.list_display,
                            self.list_display_links, self.list_filter, self.date_hierarchy,
                            self.search_fields, self.list_select_related,
                            self.list_per_page, self.list_max_show_all, self.list_editable,
                            self)
        except IncorrectLookupParameters:
            if ERROR_FLAG in request.GET.keys():
                return render_to_response('admin/invalid_setup.html', {'title': _('Database error')})
            return HttpResponseRedirect('%s?%s=1' % (request.path, ERROR_FLAG))

        if request.META['QUERY_STRING'] == '':
            # Default
            # Session variable get record set with searched option into export file
            request.session['admin_voipcall_record_kwargs'] = voipcall_record_common_fun(request)

            query_string = voipcall_search_admin_form_fun(request)
            return HttpResponseRedirect("/admin/%s/%s/?%s" % (opts.app_label, opts.object_name.lower(), query_string))

        cl.formset = None

        selection_note_all = ungettext('%(total_count)s selected', 'All %(total_count)s selected', cl.result_count)

        ctx = {
            'selection_note': _('0 of %(cnt)s selected') % {'cnt': len(cl.result_list)},
            'selection_note_all': selection_note_all % {'total_count': cl.result_count},
            'cl': cl,
            'form': form,
            'opts': opts,
            'model_name': opts.object_name.lower(),
            'app_label': APP_LABEL,
            'title': _('call report'),
        }
        return super(VoIPCallAdmin, self).changelist_view(request, extra_context=ctx)
Esempio n. 37
0
    def subscriber_report(self, request):
        """
        Get subscriber report

        **Attributes**:

            * ``form`` - SubscriberReportForm
            * ``template`` - admin/dialer_campaign/subscriber/subscriber_report.html
        """
        opts = Subscriber._meta
        tday = datetime.today()
        form = SubscriberReportForm(request.POST or None,
                                    initial={"from_date": tday.strftime("%Y-%m-%d"),
                                             "to_date": tday.strftime("%Y-%m-%d")})
        total_subscriber = 0
        total_pending = 0
        total_pause = 0
        total_abort = 0
        total_fail = 0
        total_sent = 0
        total_in_process = 0
        total_not_auth = 0
        total_completed = 0

        if form.is_valid():
            start_date = ''
            end_date = ''
            from_date = getvar(request, 'from_date')
            to_date = getvar(request, 'to_date')
            start_date = ceil_strdate(str(from_date), 'start')
            end_date = ceil_strdate(str(to_date), 'end')
            campaign_id = getvar(request, 'campaign_id')
            kwargs = {}
            if start_date and end_date:
                kwargs['updated_date__range'] = (start_date, end_date)
            if start_date and end_date == '':
                kwargs['updated_date__gte'] = start_date
            if start_date == '' and end_date:
                kwargs['updated_date__lte'] = end_date
            if campaign_id and campaign_id != '0':
                kwargs['campaign_id'] = campaign_id

            select_data = {"updated_date": "SUBSTR(CAST(updated_date as CHAR(30)),1,10)"}
            subscriber = Subscriber.objects.filter(**kwargs).extra(select=select_data)\
                .values('updated_date', 'status')\
                .annotate(Count('updated_date'))\
                .order_by('updated_date')

            for i in subscriber:
                total_subscriber += i['updated_date__count']
                if i['status'] == SUBSCRIBER_STATUS.PENDING:
                    total_pending += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.PAUSE:
                    total_pause += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.ABORT:
                    total_abort += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.FAIL:
                    total_fail += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.SENT:
                    total_sent += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.IN_PROCESS:
                    total_in_process += i['updated_date__count']
                elif i['status'] == SUBSCRIBER_STATUS.NOT_AUTHORIZED:
                    total_not_auth += i['updated_date__count']
                else:
                    #status COMPLETED
                    total_completed += i['updated_date__count']

        ctx = RequestContext(request, {
            'form': form,
            'opts': opts,
            'total_subscriber': total_subscriber,
            'total_pending': total_pending,
            'total_pause': total_pause,
            'total_abort': total_abort,
            'total_fail': total_fail,
            'total_sent': total_sent,
            'total_in_process': total_in_process,
            'total_not_auth': total_not_auth,
            'total_completed': total_completed,
            'SUBSCRIBER_STATUS_NAME': SUBSCRIBER_STATUS_NAME,
            'model_name': opts.object_name.lower(),
            'app_label': APP_LABEL,
            'title': _('subscriber report'),
        })

        return render_to_response('admin/dialer_campaign/subscriber/subscriber_report.html', context_instance=ctx)
Esempio n. 38
0
def cdr_concurrent_calls(request):
    """CDR view of concurrent calls

    **Attributes**:

        * ``template`` - cdr/graph_concurrent_calls.html
        * ``form`` - ConcurrentCallForm
        * ``mongodb_data_set`` - MONGO_CDRSTATS['CONC_CALL_AGG'] (map-reduce collection)

    **Logic Description**:

        get all concurrent call records from mongodb map-reduce collection for
        current date
    """
    logging.debug("CDR concurrent view start")
    now = datetime.today()
    from_date = now.strftime("%Y-%m-%d")
    start_date = datetime(now.year, now.month, now.day, 0, 0, 0, 0)
    end_date = datetime(now.year, now.month, now.day, 23, 59, 59, 0)

    query_var = {}
    switch_id = 0

    form = ConcurrentCallForm(request.POST or None, initial={"from_date": from_date})
    logging.debug("CDR concurrent view with search option")

    if form.is_valid():
        from_date = getvar(request, "from_date")
        switch_id = getvar(request, "switch_id")

        start_date = ceil_strdate(from_date, "start")
        end_date = ceil_strdate(from_date, "end")

        if switch_id and int(switch_id) != 0:
            query_var["switch_id"] = int(switch_id)

    query_var["date"] = {"$gte": start_date, "$lt": end_date}

    if not request.user.is_superuser:  # not superuser
        query_var["accountcode"] = request.user.userprofile.accountcode

    xdata = []
    charttype = "stackedAreaChart"
    call_count_res = defaultdict(list)

    if query_var:
        # calls_in_day = mongodb.conc_call_agg.find(query_var).sort([('date', 1)])
        calls_in_day = {}

        for d in calls_in_day:
            # convert date into timestamp value
            ts = time.mktime(d["date"].timetuple())
            tsint = int(ts * 1000)
            xdata.append(str(tsint))
            call_count_res[d["switch_id"]].append(d["numbercall"])

        int_count = 1
        chartdata = {"x": xdata}
        extra_serie = {"tooltip": {"y_start": "", "y_end": " concurrent calls"}, "date_format": "%d %b %Y %I:%M:%S %p"}
        for i in call_count_res:
            chartdata["name" + str(int_count)] = str(get_switch_ip_addr(i))
            chartdata["y" + str(int_count)] = call_count_res[i]
            chartdata["extra" + str(int_count)] = extra_serie
            int_count += 1

        logging.debug("CDR concurrent view end")
        data = {
            "form": form,
            "start_date": start_date,
            "chartdata": chartdata,
            "charttype": charttype,
            "chartcontainer": "stacked_area_container",
            "chart_extra": {
                "x_is_date": True,
                "x_axis_format": "%d %b %Y %H:%S",
                "tag_script_js": True,
                "jquery_on_ready": True,
            },
        }
    return render_to_response("cdr/graph_concurrent_calls.html", data, context_instance=RequestContext(request))
Esempio n. 39
0
def survey_report(request):
    """
    Survey detail report for the logged in user

    **Attributes**:

        * ``template`` - survey/survey_report.html
        * ``form`` - SurveyDetailReportForm

    **Logic Description**:

        * List all survey_report which belong to the logged in user.
    """
    tday = datetime.today()
    from_date = tday.strftime("%Y-%m-%d")
    to_date = tday.strftime("%Y-%m-%d")

    form = SurveyDetailReportForm(request.user, request.POST or None,
                                  initial={'from_date': from_date,
                                           'to_date': to_date})
    survey_result = ''

    survey_cdr_daily_data = {
        'total_data': '',
        'total_duration': '',
        'total_calls': '',
        'total_avg_duration': '',
        'max_duration': '',
    }

    sort_col_field_list = ['starting_date', 'phone_number', 'duration', 'disposition', 'id']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='starting_date')

    survey_id = ''
    action = 'tabs-1'
    campaign_obj = ''
    rows = []
    survey_id = ''
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        # set session var value
        request.session['session_surveycalls_kwargs'] = {}
        request.session['session_survey_cdr_daily_data'] = {}
        # set session var value
        field_list = ['from_date', 'to_date', 'survey_id']
        unset_session_var(request, field_list)

        from_date = getvar(request, 'from_date')
        to_date = getvar(request, 'to_date')
        start_date = ceil_strdate(str(from_date), 'start')
        end_date = ceil_strdate(str(to_date), 'end')

        converted_start_date = start_date.strftime('%Y-%m-%d')
        converted_end_date = end_date.strftime('%Y-%m-%d')
        request.session['session_start_date'] = converted_start_date
        request.session['session_end_date'] = converted_end_date

        survey_id = getvar(request, 'survey_id', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        start_date = request.session.get('session_start_date')
        end_date = request.session.get('session_end_date')
        start_date = ceil_strdate(start_date, 'start')
        end_date = ceil_strdate(end_date, 'end')
        survey_id = request.session.get('session_survey_id')

        form = SurveyDetailReportForm(request.user, initial={'from_date': start_date.strftime('%Y-%m-%d'),
                                                             'to_date': end_date.strftime('%Y-%m-%d'),
                                                             'survey_id': survey_id})
    if post_var_with_page == 0:
        # default
        # unset session var
        tday = datetime.utcnow().replace(tzinfo=utc)
        from_date = tday.strftime('%Y-%m-01')
        last_day = ((datetime(tday.year, tday.month, 1, 23, 59, 59, 999999).replace(tzinfo=utc) +
                     relativedelta(months=1)) -
                    relativedelta(days=1)).strftime('%d')
        to_date = tday.strftime('%Y-%m-' + last_day)
        start_date = ceil_strdate(from_date, 'start')
        end_date = ceil_strdate(to_date, 'end')

        # unset session var value
        request.session['session_from_date'] = from_date
        request.session['session_to_date'] = to_date
        request.session['session_survey_id'] = ''
        request.session['session_surveycalls_kwargs'] = ''

    kwargs = {}
    if not request.user.is_superuser:
        kwargs['user'] = request.user
    kwargs['disposition__exact'] = CALL_DISPOSITION.ANSWER

    survey_result_kwargs = {}

    if start_date and end_date:
        kwargs['starting_date__range'] = (start_date, end_date)
        survey_result_kwargs['created_date__range'] = (start_date, end_date)
    if start_date and end_date == '':
        kwargs['starting_date__gte'] = start_date
        survey_result_kwargs['created_date__gte'] = start_date
    if start_date == '' and end_date:
        kwargs['starting_date__lte'] = end_date
        survey_result_kwargs['created_date__lte'] = end_date

    all_call_list = []
    try:
        survey_result_kwargs['survey_id'] = survey_id
        survey_result = get_survey_result(survey_result_kwargs)

        campaign_obj = Survey.objects.get(id=int(survey_id)).campaign
        kwargs['callrequest__campaign'] = campaign_obj

        # List of Survey VoIP call report
        voipcall_list = VoIPCall.objects.filter(**kwargs)
        request.session['session_surveycalls_kwargs'] = kwargs
        all_call_list = voipcall_list.values_list('id', flat=True)

        # Get daily report from session while using pagination & sorting
        if request.GET.get('page') or request.GET.get('sort_by'):
            survey_cdr_daily_data = request.session['session_survey_cdr_daily_data']
            action = 'tabs-2'
        else:
            survey_cdr_daily_data = survey_cdr_daily_report(voipcall_list)
            request.session['session_survey_cdr_daily_data'] = survey_cdr_daily_data

        rows = voipcall_list.order_by(pag_vars['sort_order'])[pag_vars['start_page']:pag_vars['end_page']]
    except:
        rows = []
        if request.method == 'POST':
            request.session["err_msg"] = _('no campaign attached with survey.')

    data = {
        'rows': rows,
        'all_call_list': all_call_list,
        'call_count': all_call_list.count() if all_call_list else 0,
        'SURVEY_CALL_RESULT_NAME': SURVEY_CALL_RESULT_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'total_data': survey_cdr_daily_data['total_data'],
        'total_duration': survey_cdr_daily_data['total_duration'],
        'total_calls': survey_cdr_daily_data['total_calls'],
        'total_avg_duration': survey_cdr_daily_data['total_avg_duration'],
        'max_duration': survey_cdr_daily_data['max_duration'],
        'msg': request.session.get('msg'),
        'err_msg': request.session.get('err_msg'),
        'form': form,
        'survey_result': survey_result,
        'action': action,
        'start_date': start_date,
        'end_date': end_date,
        'campaign_obj': campaign_obj,
    }
    request.session['msg'] = ''
    request.session['err_msg'] = ''
    return render_to_response('survey/survey_report.html', data, context_instance=RequestContext(request))
Esempio n. 40
0
def contact_list(request):
    """Contact list for the logged in user

    **Attributes**:

        * ``template`` - dialer_contact/contact/list.html
        * ``form`` - ContactSearchForm

    **Logic Description**:

        * List all contacts from phonebooks belonging to the logged in user
    """
    sort_col_field_list = ['id', 'phonebook', 'contact', 'status', 'first_name', 'last_name', 'email', 'updated_date']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')
    form = ContactSearchForm(request.user, request.POST or None)
    phonebook_id_list = Phonebook.objects.values_list('id', flat=True).filter(user=request.user)

    contact_no = ''
    contact_name = ''
    phonebook = ''
    contact_status = STATUS_CHOICE.ALL
    post_var_with_page = 0
    if form.is_valid():
        field_list = ['contact_no', 'contact_name', 'contact_status', 'phonebook']
        unset_session_var(request, field_list)

        contact_no = getvar(request, 'contact_no', setsession=True)
        contact_name = getvar(request, 'contact_name', setsession=True)
        contact_status = getvar(request, 'contact_status', setsession=True)
        phonebook = getvar(request, 'phonebook', setsession=True)
        post_var_with_page = 1

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        contact_no = request.session.get('session_contact_no')
        contact_name = request.session.get('session_contact_name')
        contact_status = request.session.get('session_contact_status')
        phonebook = request.session.get('session_phonebook')
        form = ContactSearchForm(request.user,
                                 initial={'contact_no': contact_no,
                                          'contact_name': contact_name,
                                          'status': contact_status,
                                          'phonebook': phonebook})

    if post_var_with_page == 0:
        # default
        # unset session var
        field_list = ['contact_no', 'contact_name', 'contact_status', 'phonebook']
        unset_session_var(request, field_list)

    kwargs = {}
    if phonebook and phonebook != '0':
        kwargs['phonebook'] = phonebook

    if contact_status and int(contact_status) != STATUS_CHOICE.ALL:
        kwargs['status'] = contact_status

    contact_no_type = '1'
    contact_no = source_desti_field_chk(contact_no, contact_no_type, 'contact')
    for i in contact_no:
        kwargs[i] = contact_no[i]

    contact_list = []
    all_contact_list = []
    contact_count = 0

    if phonebook_id_list:
        contact_list = Contact.objects.values('id', 'phonebook__name', 'contact', 'last_name', 'first_name', 'email', 'status', 'updated_date')\
            .filter(phonebook__in=phonebook_id_list)

        if kwargs:
            contact_list = contact_list.filter(**kwargs)

        if contact_name:
            # Search on contact name
            contact_name_filter = (
                Q(last_name__icontains=contact_name) | Q(first_name__icontains=contact_name)
            )
            if contact_name_filter:
                contact_list = contact_list.filter(contact_name_filter)

        all_contact_list = contact_list.order_by(pag_vars['sort_order'])
        contact_list = all_contact_list[pag_vars['start_page']:pag_vars['end_page']]
        contact_count = all_contact_list.count()

    data = {
        'contact_list': contact_list,
        'all_contact_list': all_contact_list,
        'total_contacts': contact_count,
        'CONTACT_COLUMN_NAME': CONTACT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'form': form,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dialer_contact/contact/list.html', data, context_instance=RequestContext(request))
Esempio n. 41
0
def contact_list(request):
    """Contact list for the logged in user

    **Attributes**:

        * ``template`` - dialer_contact/contact/list.html
        * ``form`` - ContactSearchForm

    **Logic Description**:

        * List all contacts from phonebooks belonging to the logged in user
    """
    sort_col_field_list = [
        'id', 'phonebook', 'contact', 'status', 'first_name', 'last_name',
        'email', 'updated_date'
    ]
    pag_vars = get_pagination_vars(request,
                                   sort_col_field_list,
                                   default_sort_field='id')
    form = ContactSearchForm(request.user, request.POST or None)
    phonebook_id_list = Phonebook.objects.values_list(
        'id', flat=True).filter(user=request.user)

    contact_no = ''
    contact_name = ''
    phonebook = ''
    contact_status = STATUS_CHOICE.ALL
    post_var_with_page = 0
    if form.is_valid():
        field_list = [
            'contact_no', 'contact_name', 'contact_status', 'phonebook'
        ]
        unset_session_var(request, field_list)

        contact_no = getvar(request, 'contact_no', setsession=True)
        contact_name = getvar(request, 'contact_name', setsession=True)
        contact_status = getvar(request, 'contact_status', setsession=True)
        phonebook = getvar(request, 'phonebook', setsession=True)
        post_var_with_page = 1

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        contact_no = request.session.get('session_contact_no')
        contact_name = request.session.get('session_contact_name')
        contact_status = request.session.get('session_contact_status')
        phonebook = request.session.get('session_phonebook')
        form = ContactSearchForm(request.user,
                                 initial={
                                     'contact_no': contact_no,
                                     'contact_name': contact_name,
                                     'status': contact_status,
                                     'phonebook': phonebook
                                 })

    if post_var_with_page == 0:
        # default
        # unset session var
        field_list = [
            'contact_no', 'contact_name', 'contact_status', 'phonebook'
        ]
        unset_session_var(request, field_list)

    kwargs = {}
    if phonebook and phonebook != '0':
        kwargs['phonebook'] = phonebook

    if contact_status and int(contact_status) != STATUS_CHOICE.ALL:
        kwargs['status'] = contact_status

    contact_no_type = '1'
    contact_no = source_desti_field_chk(contact_no, contact_no_type, 'contact')
    for i in contact_no:
        kwargs[i] = contact_no[i]

    contact_list = []
    all_contact_list = []
    contact_count = 0

    if phonebook_id_list:
        contact_list = Contact.objects\
            .values('id', 'phonebook__name', 'contact', 'last_name', 'first_name', 'email', 'status', 'updated_date')\
            .filter(phonebook__in=phonebook_id_list)

        if kwargs:
            contact_list = contact_list.filter(**kwargs)

        if contact_name:
            # Search on contact name
            contact_name_filter = (Q(last_name__icontains=contact_name)
                                   | Q(first_name__icontains=contact_name))
            if contact_name_filter:
                contact_list = contact_list.filter(contact_name_filter)

        all_contact_list = contact_list.order_by(pag_vars['sort_order'])
        contact_list = all_contact_list[
            pag_vars['start_page']:pag_vars['end_page']]
        contact_count = all_contact_list.count()

    data = {
        'contact_list': contact_list,
        'all_contact_list': all_contact_list,
        'total_contacts': contact_count,
        'CONTACT_COLUMN_NAME': CONTACT_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'form': form,
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    return render_to_response('dialer_contact/contact/list.html',
                              data,
                              context_instance=RequestContext(request))
Esempio n. 42
0
def sms_campaign_list(request):
    """List all sms campaigns for the logged in user

    **Attributes**:

        * ``template`` - mod_sms/list.html

    **Logic Description**:

        * List all sms campaigns belonging to the logged in user
    """
    form = SMSCampaignSearchForm(request.user, request.POST or None)
    sort_col_field_list = ['id', 'name', 'startingdate', 'status', 'totalcontact']
    pag_vars = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')

    phonebook_id = ''
    status = 'all'
    post_var_with_page = 0
    if form.is_valid():
        field_list = ['phonebook_id', 'status']
        unset_session_var(request, field_list)
        post_var_with_page = 1
        phonebook_id = getvar(request, 'phonebook_id', setsession=True)
        status = getvar(request, 'status', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        phonebook_id = request.session.get('session_phonebook_id')
        status = request.session.get('session_status')
        form = SMSCampaignSearchForm(request.user, initial={'status': status,
                                                            'phonebook_id': phonebook_id})

    if post_var_with_page == 0:
        # default
        # unset session var
        field_list = ['status', 'phonebook_id']
        unset_session_var(request, field_list)

    kwargs = {}
    if phonebook_id and phonebook_id != '0':
        kwargs['phonebook__id__in'] = [int(phonebook_id)]

    if status and status != 'all':
        kwargs['status'] = status

    smscampaign_list = SMSCampaign.objects.filter(user=request.user).order_by(pag_vars['sort_order'])
    smscampaign_count = smscampaign_list.count()
    if kwargs:
        all_smscampaign_list = smscampaign_list.filter(**kwargs).order_by(pag_vars['sort_order'])
        smscampaign_list = all_smscampaign_list[pag_vars['start_page']:pag_vars['end_page']]
        smscampaign_count = all_smscampaign_list.count()

    data = {
        'form': form,
        'smscampaign_list': smscampaign_list,
        'total_campaign': smscampaign_count,
        'SMS_CAMPAIGN_COLUMN_NAME': SMS_CAMPAIGN_COLUMN_NAME,
        'col_name_with_order': pag_vars['col_name_with_order'],
        'msg': request.session.get('msg'),
        'error_msg': request.session.get('error_msg'),
        'info_msg': request.session.get('info_msg'),
    }
    request.session['msg'] = ''
    request.session['error_msg'] = ''
    request.session['info_msg'] = ''
    return render_to_response('mod_sms/list.html', data, context_instance=RequestContext(request))
Esempio n. 43
0
def alert_report(request):
    """
    To get alarm report for logged in user

    **Attributes**:

        * ``form`` - AlarmReportForm
        * ``template`` - cdr_alert/alarm_report.html
    """
    form = AlarmReportForm(request.user, request.POST or None)
    sort_col_field_list = ['id', 'alarm', 'calculatedvalue', 'status', 'daterun']
    page_data = get_pagination_vars(request, sort_col_field_list, default_sort_field='id')

    alarm_id = 0
    action = 'tabs-1'
    post_var_with_page = 0
    if form.is_valid():
        post_var_with_page = 1
        request.session['session_alarm_id'] = ''
        alarm_id = getvar(request, 'alarm_id', setsession=True)

    if request.GET.get('page') or request.GET.get('sort_by'):
        post_var_with_page = 1
        alarm_id = request.session.get('session_alarm_id')
        form = AlarmReportForm(request.user, initial={'alarm_id': alarm_id})

    if post_var_with_page == 0:
        # unset session var
        request.session['session_alarm_id'] = ''

    kwargs = {}
    if alarm_id and int(alarm_id) != 0:
        kwargs['alarm_id'] = int(alarm_id)
    kwargs['alarm__user'] = request.user

    alarm_report_list = AlarmReport.objects.filter(**kwargs)
    all_alarm_list = alarm_report_list.order_by(page_data['sort_order'])
    alarm_list = all_alarm_list[page_data['start_page']:page_data['end_page']]
    contact_alarm = all_alarm_list.count()

    days_report = last_seven_days_report(request, kwargs)

    data = {
        'form': form,
        'action': action,
        'total_data': days_report['total_data'],
        'start_date': days_report['start_date'],
        'end_date': days_report['end_date'],
        'all_alarm_list': all_alarm_list,
        'rows': alarm_list,
        'total_count': contact_alarm,
        'ALARM_REPORT_COLUMN_NAME': ALARM_REPORT_COLUMN_NAME,
        'col_name_with_order': page_data['col_name_with_order'],
        'charttype': days_report['charttype'],
        'chartdata': days_report['chartdata'],
        'chartcontainer': 'chartcontainer',
        'extra': {
            'x_is_date': True,
            'x_axis_format': '%d %b %y',
            'tag_script_js': False,
            'jquery_on_ready': True,
        },
    }
    return render_to_response('cdr_alert/alarm_report.html', data, context_instance=RequestContext(request))