Пример #1
0
def get_unique_users_registrations(request):
    """
    Unique users registered per month
    """

    data_source = dict()
    CHART["caption"] = "Unique user registrations"
    data_source['chart'] = CHART

    columns = ['id', 'created_at']
    data = pd.DataFrame(list(User.objects.all().values_list(*columns)),
                        columns=columns)
    data['month'] = data['created_at'].apply(lambda date: '{y}-{m}'.format(
        y=date.year, m=get_month_format(date.month)))
    data.drop('created_at', inplace=True, axis=1)

    gp = pd.groupby(data, by='month').aggregate({'id': 'count'})
    data = pd.DataFrame(gp)
    data.sort_index(inplace=True)

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({'label': idx, 'value': str(row['id'])})

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #2
0
def myFirstChart1(request):
    dataSource = OrderedDict()
    chartData = OrderedDict()
    chartConfig = OrderedDict()
    chartConfig["caption"] = "Objects & Accounts"
    chartConfig["formatnumberscale"] = "2"
    chartConfig["drawcrossline"] = "2"
    chartConfig["theme"] = "gammel"
    chartConfig["palettecolors"] = "add8e6,90ee90"
    chartData["Licences"] = 2000
    chartData["Licenced End Users"] = 2000
    chartData["People Who Have Access to Valult"] = 4000
    chartData["Sales"] = 3000
    dataSource["chart"] = chartConfig
    dataSource["data"] = []

    for key, value in chartData.items():
        data = {}
        data["label"] = key
        data["value"] = value
        dataSource["data"].append(data)
    column2D1 = FusionCharts("column2d", "myFirstChart1", "350", "400",
                             "myFirstchart-container1", "json", dataSource)

    return render(request, 'index1.html', {'output1': column2D1.render()})
def chart(request):
    # Create an object for the pie3d chart using the FusionCharts class constructor
    pie3d = FusionCharts(
        "pie3d",
        "ex2",
        "100%",
        "400",
        "chart-1",
        "json",
        # The data is passed as a string in the `dataSource` as parameter.
        """{ 
            "chart": {
            "caption": "Age profile of website visitors",
            "subcaption": "Last Year",
            "startingangle": "120",
            "showlabels": "0",
            "showlegend": "1",
            "enablemultislicing": "0",
            "slicingdistance": "15",
            "showpercentvalues": "1",
            "showpercentintooltip": "0",
            "plottooltext": "Age group : $label Total visit : $datavalue",
            "theme": "ocean"
            },
            "data": [
                {"label": "Teenage", "value": "1250400"},
                {"label": "Adult", "value": "1463300"},
                {"label": "Mid-age", "value": "1050700"},
                {"label": "Senior", "value": "491000"}
            ]
    }""")

    # returning complete JavaScript and HTML code, which is used to generate chart in the browsers.
    return render(request, 'index.html', {'output': pie3d.render()})
Пример #4
0
def StO2(request):

    #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs.
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Tissue Oxygenation Visualization",
        "xAxisName": "Time",
        "labeldisplay": "rotate",
        "yAxisName": "StO2(units)",
        "theme": "fusion",
        "showvalues": "0",
        "drawAnchors": "0"
    }
    dataSource['data'] = []

    #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.
    for key in MessageModel.objects.all():
        if key.StO2 != "N/A":
            data = {}
            data["label"] = key.date
            data["value"] = key.StO2
            dataSource["data"].append(data)

# Create an object for the column 2D chart using the FusionCharts class constructor
# The chart data is passed to the `dataSource` parameter.
    PPG_line = FusionCharts("line", "PPGChart", "1000", "800",
                            "StO2-container", "json", dataSource)
    return render(request, 'index1.html', {'output_StO2': PPG_line.render()})
Пример #5
0
def recommended_candidates(request):
    """
    Recommended
    """

    data_source = dict()
    CHART["caption"] = "Recommended candidates"
    data_source['chart'] = CHART

    columns = ['id', 'created_at']
    data = pd.DataFrame(list(
        Candidate.objects.filter(state__code__in=['GTJ', 'STC'],
                                 removed=False).values_list(*columns)),
                        columns=columns)
    data['month'] = data['created_at'].apply(lambda date: '{y}-{m}'.format(
        y=date.year, m=get_month_format(date.month)))
    data.drop('created_at', inplace=True, axis=1)

    gp = pd.groupby(data, by='month').aggregate({'id': 'count'})
    data = pd.DataFrame(gp)
    data.sort_index(inplace=True)

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({'label': idx, 'value': str(row['id'])})

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #6
0
def chart(request):
    if request.method == "POST":
        date = request.POST.get('date')
        dataSource = {}
        dataSource['chart'] = {
            "caption": "Slot Booking",
            "subCaption": "Bar Graph",
            "xAxisName": "Slot",
            "yAxisName": "No.of students",
            "theme": "fusion"
        }
        dataSource['data'] = []
        for key in range(1, 5):
            data = {}
            p = Booking.objects.get(date=date)
            s = 's' + str(key)
            data['label'] = s
            if s == "s1":
                data['value'] = p.s1
            elif s == "s2":
                data['value'] = p.s2
            elif s == "s3":
                data['value'] = p.s3
            else:
                data['value'] = p.s4

            dataSource['data'].append(data)

        # Create an object for the Column 2D chart using the FusionCharts class constructor
        column2D = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                                "json", dataSource)
        return render(request, 'students/index.html',
                      {'output': column2D.render()})
    return render(request, "students/graph.html", {})
Пример #7
0
def campaign_count(request):
    # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs.
    data_source = dict()
    CHART["caption"] = "Total campaign registrations"
    data_source['chart'] = CHART

    data_source['data'] = []

    my_campaigns = [c for c in Campaign.objects.filter(removed=False)]

    data = pd.DataFrame()
    data['id'] = [c.pk for c in my_campaigns]
    data['created_at'] = [c.created_at for c in my_campaigns]
    data['month'] = data['created_at'].apply(lambda date: '{y}-{m}'.format(
        y=date.year, m=get_month_format(date.month)))
    data.sort_values(by=['month'], inplace=True)

    gp = pd.groupby(data, by='month').aggregate({'id': 'count'})
    gp = pd.DataFrame(gp)

    for idx, row in gp.iterrows():
        data = dict()
        data['label'] = idx
        data['value'] = str(row['id'])
        data_source['data'].append(data)

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #8
0
def chart(request):
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Patients by specialization",
        "subCaption": "MedApp Clinic",
        "xAxisName": "Month",
        "yAxisName": "Number of patients",
        "theme": "zune"
    }

    dataSource['data'] = []

    number_patient = Consultation.objects.all().values(
        'specialization').annotate(
            total=Count('specialization')).order_by('total')

    for members in number_patient:
        data = {}
        specilization = Specialization.objects.get(
            pk=members['specialization'])
        data['label'] = specilization.name

        data['value'] = members['total']
        dataSource['data'].append(data)

    column2D = FusionCharts("column2D", "ex1", "500", "300", "chart-1", "json",
                            dataSource)

    return render(request, 'charts.html', {'output': column2D.render()})
Пример #9
0
def index(request):
    cursor1 = connection.cursor()
    cursor1.execute(
        """select job, count(job) from volunteer_vol_info GROUP BY job""")
    data = cursor1.fetchall()

    # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs.
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Volunteer Rank",
        "subCaption": "See how your department compares!",
        "xAxisName": "Department",
        "yAxisName": "Volunteers",
        "theme": "fint"
    }

    dataSource['data'] = []
    for i in data:
        data = {}
        data['label'] = i[0]
        data['value'] = i[1]
        dataSource['data'].append(data)
    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column2D = FusionCharts("column2D", "ex1", "600", "350", "chart-1", "json",
                            dataSource)
    return render(request, 'index.html', {'output': column2D.render()})
Пример #10
0
def home(request):
    jobs = Job.objects
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Monthly revenue for last year",
        "subCaption": "Harry's SuperMart",
        "xAxisName": "Month",
        "yAxisName": "Revenues",
        # "numberPrefix": "Rs",
        "theme": "zune"
    }
    dataSource['data'] = []
    # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list.
    for key in Revenue.objects.all():
        data = {}
        data['label'] = key.Month
        data['value'] = key.MonthlyRevenue
        dataSource['data'].append(data)

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column2D = FusionCharts("column2D", "ex1", "600", "350", "home-container",
                            "json", dataSource)
    return render(request, 'jobs/home.html', {
        'jobs': jobs,
        'output': column2D.render()
    })
Пример #11
0
def chart(request):
    # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs.
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Monthly revenue for last year",
        "subCaption": "Harry's SuperMart",
        "xAxisName": "Month",
        "yAxisName": "Revenues (In USD)",
        "numberPrefix": "$",
        "theme": "zune"
    }

    # The data for the chart should be in an array where each element of the array is a JSON object
    # having the `label` and `value` as key value pair.

    dataSource['data'] = []
    # Iterate through the data in `Revenue` model and insert in to the `dataSource['data']` list.
    for key in Revenue.objects.all():
        data = {}
        data['label'] = key.Month
        data['value'] = key.MonthlyRevenue
        dataSource['data'].append(data)

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column2D = FusionCharts("column2D", "ex1", "600", "350", "chart-1", "json",
                            dataSource)
    return render(request, 'index.html', {'output': column2D.render()})
Пример #12
0
def candidates_from_old_users(request):
    """
    select date_trunc('month', created_at) m,
      count(*) new_candidates
    from candidates
    where id not in (select min(id) first_candidate_id
                       from candidates
                       where not removed
                       and state_id!=11
                       group by user_id)
    and state_id!=11
    and not removed
    group by m
    order by m;
    """

    data_source = dict()
    CHART["caption"] = "Candidates from old user"
    data_source['chart'] = CHART

    data = get_number_of_second_candidates()

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({
            'label': idx,
            'value': str(round(row['id']))
        })

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #13
0
def compare(request):

    with open(path + "/stocks.json") as f:
        data = json.load(f)

    if (request.GET.get('reset', None)):
        data['Compare'] = []

    if (request.GET.get('reset_company', None)):
        answer = request.GET.get('reset_company', None)
        data['Compare'].remove(answer)

    companies = deepcopy(data['Compare'])
    companies.append(data['Company'])

    companies = list(set(companies))

    if (request.GET.get('duration', None)):
        data['duration'] = int(request.GET.get('duration', None))

    cat, labelstep = get_x_compare(data['duration'], companies[0])
    series_data = get_series(data['duration'], companies)
    table = get_compare_table(companies)
    info_table = get_compare_info_table(companies)

    chartObj = FusionCharts(
        'msline', 'ex1', '1000', '400', 'chart-1', 'json', """{
  "chart": {
    "caption": "Comparison Analysis",
    "yaxisname": "Return",
    "showhovereffect": "1",
    "numbersuffix": "%",
    "drawcrossline": "1",
    "plottooltext": "<b>$dataValue</b> % return for $seriesName",
    "theme": "fusion",
    "drawAnchors": "0",
    "labelStep":""" + str(labelstep) + """},
  "categories": [
    {
      "category":""" + cat + """}
  ],
  "dataset": """ + series_data + """}""")

    with open(path + "/stocks.json", 'w') as f:
        json.dump(data, f)

    content = {
        'company_list_body': get_compare_list(data['Compare']),
        'compare_graph': chartObj.render(),
        "compare_table": table,
        "info_table": info_table,
        'duration_placeholder': chart_type_palceholder(data["duration"])
    }

    return render(request, 'compare.html', content)
Пример #14
0
def chart(article_info):

    # Initialize list for counting articles of different percentage
    tmp = [0, 0, 0, 0, 0]
    for element in article_info:
        if element[1] > 0.9:
            tmp[0] += 1
        if element[1] > 0.8 and element[1] <= 0.9:
            tmp[1] += 1
        if element[1] > 0.7 and element[1] <= 0.8:
            tmp[2] += 1
        if element[1] > 0.6 and element[1] <= 0.7:
            tmp[3] += 1
        if element[1] > 0.5 and element[1] <= 0.6:
            tmp[4] += 1

# Create an object for the column2d chart using the
# FusionCharts class constructor
    column2d = FusionCharts("column2d", "ex1", "600", "400", "chart-1", "json",
                            # The data is passed as a
                            # string in the `dataSource` as parameter.
                            {
                                "chart": {
                                    "caption": "Similarity Score distribution",
                                    "xAxisname": "percentage (%)",
                                    "yAxisName": "No. of articles",
                                    "theme": "carbon"
                                },
                                "data": [
                                    {
                                        "label": "91-100",
                                        "value": tmp[0]
                                    },
                                    {
                                        "label": "81-90",
                                        "value": tmp[1]
                                    },
                                    {
                                        "label": "71-80",
                                        "value": tmp[2]
                                    },
                                    {
                                        "label": "61-70",
                                        "value": tmp[3]
                                    },
                                    {
                                        "label": "51-60",
                                        "value": tmp[4]
                                    }
                                ]
                            })

    # returning complete JavaScript and HTML code, which is used to
    # generate chart in the browsers.
    return column2d.render()
Пример #15
0
def homepage(request):
    year_data = Record.objects.values_list('record_year',
                                           flat=True).order_by('record_year')
    if request.method == "POST" and request.POST.get('data_year') is not '':
        year_to_display = request.POST.get('data_year')
        chart_data = OrderedDict()
        chart_data[
            "caption"] = "Student Count at North Carolina State University for the Year {}".format(
                year_to_display)
        chart_data["subCaption"] = ""
        chart_data["xAxisName"] = "Student Category"
        chart_data["yAxisName"] = "Count"
        chart_data["numberSuffix"] = ""
        chart_data["theme"] = "carbon"

        data_source = OrderedDict()
        data_source["chart"] = chart_data
        data_source["data"] = []

        keys_to_exclude = ["id", "record_year"]

        # Create JSON Data to pass into Fusioncharts.
        for record in Record.objects.filter(record_year=year_to_display):
            for field, val in record:
                if field not in keys_to_exclude:
                    data = {}
                    data["label"] = category_list[field]
                    data["value"] = val
                    # print(field, val)
                    data_source["data"].append(data)

        # Create an object for the bar chart using the FusionCharts class constructor
        # The chart data is passed to the data_source parameter.
        bar_chart = FusionCharts("column2d", "chart_work", "600", "400",
                                 "chart_work-container", "json", data_source)

        # Data filtering for Dropdown

        return render(
            request, 'jobs/home.html', {
                'output': bar_chart.render(),
                'year_data': year_data,
                'update_flag': True,
            })
    else:
        return render(request, 'jobs/home.html', {
            'year_data': year_data,
            'update_flag': False,
        })
Пример #16
0
def chart(request):

    #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs.
    dataSource = OrderedDict()

    # The `chartConfig` dict contains key-value pairs of data for chart attribute
    chartConfig = OrderedDict()
    chartConfig["caption"] = "Countries With Most Oil Reserves [2017-18]"
    chartConfig["subCaption"] = "In MMbbl = One Million barrels"
    chartConfig["xAxisName"] = "Country"
    chartConfig["yAxisName"] = "Reserves (MMbbl)"
    chartConfig["numberSuffix"] = "K"
    chartConfig["theme"] = "fusion"

    # The `chartData` dict contains key-value pairs of data
    chartData = OrderedDict()
    chartData["Venezuela"] = 290
    chartData["Saudi"] = 260
    chartData["Canada"] = 180
    chartData["Iran"] = 140
    chartData["Russia"] = 115
    chartData["UAE"] = 100
    chartData["US"] = 30
    chartData["China"] = 30

    dataSource["chart"] = chartConfig
    dataSource["data"] = []

    # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
    #The data for the chart should be in an array wherein each element of the array
    #is a JSON object# having the `label` and `value` as keys.

    #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.
    for key, value in chartData.items():
        dataSource["data"].append({'label': key, 'value': value})

    # print the datasource to see what will be rendered
    pprint(dataSource)

    # Create an object for the column 2D chart using the FusionCharts class constructor
    # The chart data is passed to the `dataSource` parameter.
    column2D = FusionCharts("column2d", "Oil_Reserves", "600", "400",
                            "Oil_Reserves-container", "json", dataSource)

    context = {
        'output': column2D.render(),
    }

    return render(request, 'chart.html', context)
Пример #17
0
def stuck_candidates(request):
    """
    People don't want to do the tests, how many are there?
    select date_trunc('month', c.created_at) m,
           cast(count(distinct case when s.code in ('BL', 'P') then c.id end) as float) / cast(count(distinct c.id) as float)
    from candidates c inner join states s on s.id = c.state_id where not removed
    group by m order by m;
    """

    data_source = dict()
    CHART["caption"] = "Candidates in backlog or prospect"
    data_source['chart'] = CHART

    columns = ['id', 'state__code', 'created_at']
    data = pd.DataFrame(list(
        Candidate.objects.filter(removed=False).values_list(*columns)),
                        columns=columns)
    data['month'] = data['created_at'].apply(lambda date: '{y}-{m}'.format(
        y=date.year, m=get_month_format(date.month)))
    data.drop('created_at', inplace=True, axis=1)

    data['stuck'] = data['state__code'].apply(lambda x: int(x in ['BL', 'P']))

    gp = pd.groupby(data, by='month').aggregate({
        'id': 'count',
        'stuck': 'sum'
    })
    data = pd.DataFrame(gp)
    data.sort_index(inplace=True)

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({
            'label':
            idx,
            'value':
            str(round(row['stuck'] / row['id'], 2))
        })

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #18
0
def studentAnalysis(request):
    try:
        request_context = RequestContext(request)
        dataSource = OrderedDict()
        chartConfig = OrderedDict()
        chartConfig["caption"] = "Student Marks"
        chartConfig["subCaption"] = "Unit test Marks"
        chartConfig["xAxisName"] = "Subject"
        chartConfig["yAxisName"] = "Marks"
        chartConfig["numberSuffix"] = ""
        chartConfig["theme"] = "fusion"
        chartConfig["exportEnabled"] = 1

        # The `chartData` dict contains key-value pairs of data
        chartData = OrderedDict()
        chartData["Math"] = 95
        chartData["Marathi"] = 80
        chartData["Hindi"] = 88
        chartData["English"] = 89
        chartData["Science"] = 91
        chartData["History"] = 75

        dataSource["chart"] = chartConfig
        dataSource["data"] = []

        for key, value in chartData.items():
            data = {}
            data["label"] = key
            data["value"] = value
            dataSource["data"].append(data)

    # Create an object for the column 2D chart using the FusionCharts class constructor
    # The chart data is passed to the `dataSource` parameter.
        column2D = FusionCharts("column2d", "myFirstChart", "600", "400",
                                "myFirstchart-container", "json", dataSource)

        return render(request, 'common/studentAnalysis.html',
                      {'output': column2D.render()})
    except Exception as e:
        messages.info(request, e)
        return render(request, 'common/studentAnalysis.html')
Пример #19
0
def render_forecast(request, graph_type):

    data_source = dict()
    CHART["caption"] = graph_type + "forecasts"
    data_source['chart'] = CHART

    if graph_type == 'all':
        events = [
            e for e in StateEvent.objects.filter(use_machine_learning=True)
        ]
    elif graph_type == 'positive':
        events = [
            e for e in StateEvent.objects.filter(use_machine_learning=True,
                                                 forecast=True)
        ]
    elif graph_type == 'negative':
        events = [
            e for e in StateEvent.objects.filter(use_machine_learning=True,
                                                 forecast=False)
        ]
    else:
        raise NotImplementedError('abraço apertado')

    data = pd.DataFrame()
    data['id'] = [c.pk for c in events]
    data['created_at'] = [c.created_at for c in events]
    data['month'] = data['created_at'].apply(lambda date: '{y}-{m}'.format(
        y=date.year, m=get_month_format(date.month)))
    data.sort_values(by=['month'], inplace=True)

    gp = pd.groupby(data, by='month').aggregate({'id': 'count'})
    gp = pd.DataFrame(gp)

    data_source['data'] = []
    for idx, row in gp.iterrows():
        data_source['data'].append({'label': idx, 'value': str(row['id'])})

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #20
0
def chart(request):
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Total value in category",
        "subCaption": request.user.username,
        "xAxisName": "Categories",
        "yAxisName": "Value (In PLN)",
        "numberPrefix": "PLN",
        "paletteColors": "#0075c2",
        "bgColor": "#ffffff",
        "borderAlpha": "0",
        "canvasBorderAlpha": "0",
        "usePlotGradientColor": "0",
        "plotBorderAlpha": "10",
        "placevaluesInside": "1",
        "rotatevalues": "1",
        "valueFontColor": "#ffffff",
        "showXAxisLine": "1",
        "xAxisLineColor": "#999999",
        "divlineColor": "#999999",
        "divLineIsDashed": "1",
        "showAlternateHGridColor": "0",
        "subcaptionFontBold": "0",
        "subcaptionFontSize": "14"
    }

    dataSource['data'] = []

    #TODO?
    total_value_in_category = Finance.objects\
        .values('category__name').annotate(category_value=Sum('value')).filter(user=request.user).order_by('-category_value')

    for key in total_value_in_category:
        data = {}
        data['label'] = key.get('category__name')
        data['value'] = key.get('category_value')
        dataSource['data'].append(data)

    column2D = FusionCharts("column2D", "ex1", "600", "350", "chart-1", "json",
                            dataSource)
    return render(request, 'chart.html', {'output': column2D.render()})
Пример #21
0
def makeChart(request):
    conn = Singleton.dbase()
    cursor = conn.getCursor()
    cursor.execute("select distinct FoodName, FoodPrice from FoodItem")
    row = cursor.fetchall()
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Food and Price",
        "subCaption": "DUClub",
        "xAxisName": "Item",
        "yAxisName": "Price (In Taka)",
        "numberPrefix": "Taka",
        "theme": "carbon"
    }
    dataSource['data'] = []
    for key in row:
        data = {}
        data['label'] = key[0]
        data['value'] = key[1]
        dataSource['data'].append(data)
        column2D = FusionCharts("column2D", "ex1", "800", "500", "chart-1",
                                "json", dataSource)
    return render(request, 'chart.html', {'output': column2D.render()})
Пример #22
0
def chart(request):
    # Create an object for the column2d chart using the FusionCharts class constructor
  column2d = FusionCharts("column2d", "ex1" , "600", "400", "chart-1", "json", 
        # The data is passed as a string in the `dataSource` as parameter.
    """{  
          "chart":{  
            "caption":"Harry\'s SuperMart",
            "subCaption":"Top 5 stores in last month by revenue",
            "numberPrefix":"$",
            "theme":"ocean"
          },
          "data":[  
            {  
               "label":"Bakersfield Central",
               "value":"880000"
            },
            {  
               "label":"Garden Groove harbour",
               "value":"730000"
            },
            {  
               "label":"Los Angeles Topanga",
               "value":"590000"
            },
            {  
               "label":"Compton-Rancho Dom",
               "value":"520000"
            },
            {  
               "label":"Daly City Serramonte",
               "value":"330000"
            }
          ]
      }""")

    # returning complete JavaScript and HTML code, which is used to generate chart in the browsers. 
  return render(request, 'region2.html', {'output' : column2d.render()})
Пример #23
0
def candidates_per_user(request):
    """
    This is equivalent to this SQL:
    select s.m, cast(s.candidate_count as float) / cast(s.user_count as float) from
        (select date_trunc('month', u.created_at) as m,
                count(distinct u.id) user_count,
                count(distinct c.id) candidate_count
                from candidates c
                inner join users u on c.user_id = u.id
                where not removed and c.state_id != 11
                and u.created_at > '2018-01-01'
                group by m order by m) as s;
    :param request:
    :return:
    """

    data_source = dict()
    CHART["caption"] = "Second candidates vs new Users"
    data_source['chart'] = CHART

    data = get_number_of_second_candidates()
    users = get_number_of_unique_users()
    data = data.join(users)

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({
            'label':
            idx,
            'value':
            str(round(row['id'] / row['user_id'], 2))
        })

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #24
0
def work_area_segment_match(request):
    """
    Get the percentage of match between workAreaSegments by month

    Checks if the candidate and its campaign have a match

    select date_trunc('month', c.created_at) as m,
      count(distinct (case when w.segment_id = wcam.segment_id then c.id end)),
      count(*) as all,
      cast(count(distinct (case when w.segment_id = wcam.segment_id then c.id end)) as float) / count(*)
    from candidates c
    inner join users u on u.id = c.user_id
    inner join work_areas w on w.id = u.work_area_id
    inner join campaigns cam on cam.id = c.campaign_id
    inner join work_areas wcam on wcam.id = cam.work_area_id
      where not cam.removed
    group by m order by m;
    """

    data_source = dict()
    CHART["caption"] = "WorkAreaSegment match percentage"
    data_source['chart'] = CHART

    columns = [
        'id', 'created_at', 'campaign__work_area__segment_id',
        'user__work_area__segment_id'
    ]
    df = pd.DataFrame(list(
        Candidate.objects.filter(removed=False).values_list(*columns)),
                      columns=columns)
    df['month'] = df['created_at'].apply(lambda date: '{y}-{m}'.format(
        y=date.year, m=get_month_format(date.month)))
    df.drop('created_at', inplace=True, axis=1)

    #df['match'] = df.apply(lambda row: )

    #gb = df.groupby('month').agg({'percentage': })
    #df = pd.DataFrame(gb)

    automatic_columns = ['automatic_id', 'created_at']
    automatic = pd.DataFrame(list(
        Candidate.objects.filter(
            removed=False,
            state_events__in=StateEvent.objects.filter(
                use_machine_learning=True, forecast=True,
                to_state__code='STC')).values_list(*columns)),
                             columns=automatic_columns)
    automatic.drop('created_at', inplace=True, axis=1)
    # lambda x: x.nunique()
    data = df.join(automatic, how='left')

    gp = pd.groupby(data, by='month').aggregate({'id': 'count'})
    data = pd.DataFrame(gp)
    data.sort_index(inplace=True)

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({'label': idx, 'value': str(row['id'])})

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #25
0
def myFirstChart2(request):
    dataSource = OrderedDict()
    chartData = OrderedDict()
    chartConfig = OrderedDict()
    chartConfig["caption"] = "Windows & Domain Admins"
    chartConfig["palettecolors"] = "add8e6,90ee90"
    chartConfig["formatnumberscale"] = "2"
    chartConfig["drawcrossline"] = "2"
    chartConfig["theme"] = "gammel"
    chartData["Domain Admin Total"] = 2000
    chartData["Domain Admins Valulted"] = 2000
    chartData["Server Admins Total"] = 3300
    chartData["Server Admins Valulted"] = 2700
    chartData["Workstation Admins Total"] = 1500
    chartData["Workstation Admins Valulted"] = 1400
    chartData["Total Admins Access"] = 3300
    chartData["Total Admins Valulted"] = 2700

    dataSource["chart"] = chartConfig
    dataSource["data"] = []

    for key, value in chartData.items():
        data = {}
        data["label"] = key
        data["value"] = value
        dataSource["data"].append(data)
    column2D2 = FusionCharts("column2d", "myFirstChart2", "500", "400",
                             "myFirstchart-container2", "json", dataSource)

    return render(request, 'index2.html', {'output2': column2D2.render()})


# from django.shortcuts import render
# from django.http import HttpResponse
# from collections import OrderedDict

# # Include the `fusioncharts.py` file that contains functions to embed the charts.
# from fusioncharts import FusionCharts

# # def chart1(request):
# #     #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs.
# #     dataSource = OrderedDict()

# #     # The `chartConfig` dict contains key-value pairs of data for chart attribute
# #     chartConfig = OrderedDict()
# #     chartConfig["caption"] = "Objects & Accounts"
# #     # chartConfig["subCaption"] = "In MMbbl = One Million barrels"
# #     # chartConfig["xAxisName"] = "Country"
# #     # chartConfig["yAxisName"] = "Reserves (MMbbl)"
# #     chartConfig["numberSuffix"] = "K"
# #     chartConfig["theme"] = "gammel"

# #     # The `chartData` dict contains key-value pairs of data
# #     chartData = OrderedDict()
# #     # chartData["Total Accessed Accounts"] = 60
# #     chartData["Undefined Accounts"] = 50
# #     chartData["Total Accessed Accounts"] = 60

# #     dataSource["chart"] = chartConfig
# #     dataSource["data"] = []

# #     # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
# #     #The data for the chart should be in an array wherein each element of the array
# #     #is a JSON object# having the `label` and `value` as keys.

# #     #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.

# #     for key, value in chartData.items():
# #         data = {}
# #         data["label"] = key
# #         data["value"] = value
# #         dataSource["data"].append(data)
# #     print("-----Hello----------------------",dataSource)

# #     # Create an object for the column 2D chart using the FusionCharts class constructor
# #     # The chart data is passed to the `dataSource` parameter.
# #     column2D1 = FusionCharts("column2d", "myFirstChart", "400", "400", "myFirstchart-container", "json", dataSource)
# #     return render(request, 'index.html', {
# #         'output': column2D1.render()
# #     })

# def myFirstChart(request):
#     #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs.
#     dataSource = OrderedDict()

#     # The `chartConfig` dict contains key-value pairs of data for chart attribute
#     chartConfig = OrderedDict()
#     chartConfig["caption"] = "Objects & Accounts"
#     # chartConfig["subCaption"] = "In MMbbl = One Million barrels"
#     # chartConfig["xAxisName"] = "Country"
#     # chartConfig["yAxisName"] = "Reserves (MMbbl)"
#     chartConfig["numberSuffix"] = "K"
#     chartConfig["theme"] = "gammel"

#     # The `chartData` dict contains key-value pairs of data
#     chartData = OrderedDict()
#     # chartData["Total Accessed Accounts"] = 60
#     chartData["Undefined Accounts"] = 30
#     chartData["Total Accessed Accounts"] = 100

#     dataSource["chart"] = chartConfig
#     dataSource["data"] = []

#     # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
#     #The data for the chart should be in an array wherein each element of the array
#     #is a JSON object# having the `label` and `value` as keys.

#     #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.

#     for key, value in chartData.items():
#         data = {}
#         data["label"] = key
#         data["value"] = value
#         dataSource["data"].append(data)
#     print("-----Hello----------------------",dataSource)

#     # Create an object for the column 2D chart using the FusionCharts class constructor
#     # The chart data is passed to the `dataSource` parameter.
#     column2D1 = FusionCharts("column2d", "myFirstChart1", "400", "400", "myFirstchart-container1", "json", dataSource)
#     #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs.
#     dataSource = OrderedDict()

#     # The `chartConfig` dict contains key-value pairs of data for chart attribute
#     chartConfig = OrderedDict()
#     chartConfig["caption"] = "Objects & Accounts"
#     # chartConfig["subCaption"] = "In MMbbl = One Million barrels"
#     # chartConfig["xAxisName"] = "Country"
#     # chartConfig["yAxisName"] = "Reserves (MMbbl)"
#     chartConfig["numberSuffix"] = "K"
#     chartConfig["theme"] = "gammel"

#     # The `chartData` dict contains key-value pairs of data
#     chartData = OrderedDict()
#     # chartData["Total Accessed Accounts"] = 60
#     chartData["paletecolors"] = 50
#     chartData["Undefined Accounts"] = 50
#     chartData["Total Accessed Accounts"] = 60

#     dataSource["chart"] = chartConfig
#     dataSource["data"] = []

#     # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
#     #The data for the chart should be in an array wherein each element of the array
#     #is a JSON object# having the `label` and `value` as keys.

#     #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.

#     for key, value in chartData.items():
#         data = {}
#         data["label"] = key
#         data["value"] = value
#         dataSource["data"].append(data)
#     print("-----Hello----------------------",dataSource)

# # Create an object for the column 2D chart using the FusionCharts class constructor
# # The chart data is passed to the `dataSource` parameter.
#     column2D = FusionCharts("column3d", "myFirstChart", "400", "400", "myFirstchart-container", "json", dataSource)
#     # chart1(request)
#     return render(request, 'index.html', {
#         'output': column2D.render(),
#         'output1':column2D1.render()
#     })

# # from django.shortcuts import render
# # from django.http import HttpResponse
# # from fusioncharts import FusionCharts

# # def chart(request):
# #    chartObj = FusionCharts( 'mscolumn2d', 'ex1', '600', '400', 'chart-1', 'json', """{
# #   "chart": {
# #     "caption": "App Publishing Trend",
# #     "subcaption": "2012-2016",
# #     "xaxisname": "Years",
# #     "yaxisname": "Total number of apps in store",
# #     "formatnumberscale": "1",
# #     "plottooltext": "<b>$dataValue</b> apps were available on <b>$seriesName</b> in $label",
# #     "theme": "fusion",
# #     "drawcrossline": "1"
# #   },
# #   "categories": [
# #     {
# #       "category": [
# #         {
# #           "label": "2012"
# #         },
# #         {
# #           "label": "2013"
# #         },
# #         {
# #           "label": "2014"
# #         },
# #         {
# #           "label": "2015"
# #         },
# #         {
# #           "label": "2016"
# #         }
# #       ]
# #     }
# #   ],
# #   "dataset": [
# #     {
# #       "seriesname": "iOS App Store",
# #       "data": [
# #         {
# #           "value": "125000"
# #         },
# #         {
# #           "value": "300000"
# #         },
# #         {
# #           "value": "480000"
# #         },
# #         {
# #           "value": "800000"
# #         },
# #         {
# #           "value": "1100000"
# #         }
# #       ]
# #     },
# #     {
# #       "seriesname": "Google Play Store",
# #       "data": [
# #         {
# #           "value": "70000"
# #         },
# #         {
# #           "value": "150000"
# #         },
# #         {
# #           "value": "350000"
# #         },
# #         {
# #           "value": "600000"
# #         },
# #         {
# #           "value": "1400000"
# #         }
# #       ]
# #     },
# #     {
# #       "seriesname": "Amazon AppStore",
# #       "data": [
# #         {
# #           "value": "10000"
# #         },
# #         {
# #           "value": "100000"
# #         },
# #         {
# #           "value": "300000"
# #         },
# #         {
# #           "value": "600000"
# #         },
# #         {
# #           "value": "900000"
# #         }
# #       ]
# #     }
# #   ]
# # }""")
# #    return render(request, 'index.html', {'output': chartObj.render()})

# # def myFirstChart1(request):

# #     #Chart data is passed to the `dataSource` parameter, like a dictionary in the form of key-value pairs.
# #     dataSource = OrderedDict()

# #     # The `chartConfig` dict contains key-value pairs of data for chart attribute
# #     chartConfig = OrderedDict()
# #     chartConfig["caption"] = "Objects & Accounts"
# #     # chartConfig["subCaption"] = "In MMbbl = One Million barrels"
# #     # chartConfig["xAxisName"] = "Country"
# #     # chartConfig["yAxisName"] = "Reserves (MMbbl)"
# #     chartConfig["numberSuffix"] = "K"
# #     # chartConfig["theme"] = "fusion"

# #     # The `chartData` dict contains key-value pairs of data
# #     chartData = OrderedDict()
# #     # chartData["Total Accessed Accounts"] = 60
# #     chartData["Undefined Accounts"] = 60
# #     chartData["Total Accessed Accounts"] = 60

# #     dataSource["chart"] = chartConfig
# #     dataSource["data"] = []

# #     # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
# #     #The data for the chart should be in an array wherein each element of the array
# #     #is a JSON object# having the `label` and `value` as keys.

# #     #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.
# #     for key, value in chartData.items():
# #         data = {}
# #     data["label"] = key
# #     data["value"] = value
# #     dataSource["data"].append(data)

# # # Create an object for the column 2D chart using the FusionCharts class constructor
# # # The chart data is passed to the `dataSource` parameter.
# #     column2D = FusionCharts("column2d", "myFirstChart", "100", "400", "myFirstchart-container", "json", dataSource)

# #     return render(request, 'index1.html', {
# #         'output': column2D.render()
# #     })
Пример #26
0
def ml_automation_percentage(request):
    """
    # What percentage of recommended have been automatic?
    select m,
      cast(count(distinct automatic.id) as float) / cast(count(distinct my_all.id) as float)
      from (select date_trunc('month', c.created_at) m, c.id id
            from candidates c
              inner join states s on s.id = c.state_id
            where s.code in ('STC', 'GTJ')
              and c.created_at > '2018-10-01') my_all
    left join
      (select c.id id
       from candidates c
          inner join candidates_state_events ce on ce.candidate_id = c.id
          inner join state_events e on e.id = ce.stateevent_id
          inner join states s on s.id = e.to_state_id
       where e.use_machine_learning
          and e.forecast
          and s.code='STC'
          and c.created_at > '2018-10-01') automatic
    on my_all.id = automatic.id
    group by m
    order by m;
    """

    data_source = dict()
    CHART["caption"] = "Recommended candidates"
    data_source['chart'] = CHART

    columns = ['id', 'created_at']
    recommended = pd.DataFrame(list(
        Candidate.objects.filter(state__code__in=['GTJ', 'STC'],
                                 removed=False).values_list(*columns)),
                               columns=columns)
    recommended['month'] = recommended['created_at'].apply(
        lambda date: '{y}-{m}'.format(y=date.year,
                                      m=get_month_format(date.month)))
    recommended.drop('created_at', inplace=True, axis=1)

    automatic_columns = ['automatic_id', 'created_at']
    automatic = pd.DataFrame(list(
        Candidate.objects.filter(
            removed=False,
            state_events__in=StateEvent.objects.filter(
                use_machine_learning=True, forecast=True,
                to_state__code='STC')).values_list(*columns)),
                             columns=automatic_columns)
    automatic.drop('created_at', inplace=True, axis=1)
    #lambda x: x.nunique()
    data = recommended.join(automatic, how='left')

    gp = pd.groupby(data, by='month').aggregate({'id': 'count'})
    data = pd.DataFrame(gp)
    data.sort_index(inplace=True)

    data_source['data'] = []
    for idx, row in data.iterrows():
        data_source['data'].append({'label': idx, 'value': str(row['id'])})

    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column_2d = FusionCharts("column2D", "ex1", "600", "350", "chart-1",
                             "json", data_source)
    return render(request, cts.STATS_INDEX, {'output': column_2d.render()})
Пример #27
0
def myFirstChart(request):
    dataSource = OrderedDict()
    chartConfig = OrderedDict()

    chartConfig["formatnumberscale"] = "2"
    chartConfig["drawcrossline"] = "2"
    chartConfig["theme"] = "gammel"
    chartConfig["palettecolors"] = "add8e6,90ee90"
    chartData = OrderedDict()
    chartData["Total Accessed Accounts"] = 60000
    chartData["Undefined Accounts"] = 120000

    dataSource["chart"] = chartConfig
    dataSource["data"] = []
    for key, value in chartData.items():
        data = {}
        data["label"] = key
        data["value"] = value
        dataSource["data"].append(data)
    column2D = FusionCharts("column2d", "myFirstChart", "300", "500",
                            "myFirstchart-container", "json", dataSource)

    #111111111111
    dataSource = OrderedDict()
    chartData = OrderedDict()
    chartConfig = OrderedDict()
    chartConfig["caption"] = "Objects & Accounts"
    chartConfig["formatnumberscale"] = "2"
    chartConfig["drawcrossline"] = "2"
    chartConfig["theme"] = "gammel"
    chartConfig["palettecolors"] = "add8e6,90ee90"
    chartData["Licences"] = 2000
    chartData["Licenced End Users"] = 2000
    chartData["People Who Have Access to Valult"] = 4000
    chartData["Sales"] = 3000
    dataSource["chart"] = chartConfig
    dataSource["data"] = []

    for key, value in chartData.items():
        data = {}
        data["label"] = key
        data["value"] = value
        dataSource["data"].append(data)
    column2D1 = FusionCharts("column2d", "myFirstChart1", "400", "500",
                             "myFirstchart-container1", "json", dataSource)

    dataSource = OrderedDict()
    chartData = OrderedDict()
    chartConfig = OrderedDict()
    chartConfig["caption"] = "Windows & Domain Admins"
    chartConfig["palettecolors"] = "add8e6,90ee90"
    chartConfig["formatnumberscale"] = "2"
    chartConfig["drawcrossline"] = "2"
    chartConfig["theme"] = "gammel"
    chartData["Domain Admin Total"] = 2000
    chartData["Domain Admins Valulted"] = 2000
    chartData["Server Admins Total"] = 3300
    chartData["Server Admins Valulted"] = 2700
    chartData["Workstation Admins Total"] = 1500
    chartData["Workstation Admins Valulted"] = 1400
    chartData["Total Admins Access"] = 3300
    chartData["Total Admins Valulted"] = 2700

    dataSource["chart"] = chartConfig
    dataSource["data"] = []

    for key, value in chartData.items():
        data = {}
        data["label"] = key
        data["value"] = value
        dataSource["data"].append(data)
    column2D2 = FusionCharts("column2d", "myFirstChart2", "500", "500",
                             "myFirstchart-container2", "json", dataSource)

    return render(
        request, 'index.html', {
            'output': column2D.render(),
            'output1': column2D1.render(),
            'output2': column2D2.render(),
        })
Пример #28
0
def dashboard(request):
    if not request.user.is_authenticated():
        return HttpResponseRedirect('/')

    # Chart data is passed to the `dataSource` parameter, as dict, in the form of key-value pairs.
    dataSource = {}
    # setting chart cosmetics
    dataSource['chart'] = {
        "caption": "User Performance",
        "numberPrefix": "",
        "theme": "zune"
    }

    is_logged_in = request.user.is_authenticated
    if request.user.is_authenticated():
        user = request.user

    dataSource['categories'] = []
    dataSource['dataset'] = []
    data = {}
    data['category'] = []

    # The data for the chart should be in an array wherein each element of the array is a JSON object as
    # `label` and `value` keys.
    # Iterate through the data in `Country` model and insert in to the `dataSource['data']` list.
    for key in USER.objects.all():
        some = {}
        some['label'] = key.NAME
        data['category'].append(some)
        dataSource['categories'].append(data)

    data = {}
    data['data'] = []
    data['seriesname'] = "Questions Asked"
    for key in USER.objects.all():
        some = {}
        some['value'] = key.NUM_QUESTION_ASKED
        data['data'].append(some)
    dataSource['dataset'].append(data)

    data = {}
    data['data'] = []
    data['seriesname'] = "Total Guide Votes"
    for key in USER.objects.all():
        some = {}
        some['value'] = key.GUIDE_UPVOTE
        data['data'].append(some)
    dataSource['dataset'].append(data)

    data = {}
    data['data'] = []
    data['seriesname'] = "Total Answer Votes"
    for key in USER.objects.all():
        some = {}
        some['value'] = key.ANSWER_UPVOTE
        data['data'].append(some)
    dataSource['dataset'].append(data)

    data = {}
    data['data'] = []
    data['seriesname'] = "Total Experience Votes"
    for key in USER.objects.all():
        some = {}
        some['value'] = key.EXPERIENCE_UPVOTE
        data['data'].append(some)
    dataSource['dataset'].append(data)

    b = USER.objects.get(USER_REF=user)
    b1 = b.BADGE1
    b2 = b.BADGE2
    b3 = b.BADGE3
    b4 = b.BADGE4
    b5 = b.BADGE5

    created_events = get_created_events(user.username)
    # Create an object for the Column 2D chart using the FusionCharts class constructor
    column2D = FusionCharts("mscolumn2d", "ex1", "600", "400", "chart-1",
                            "json", dataSource)
    # returning complete JavaScript and HTML code, which is used to generate chart in the browsers.
    return render(
        request, 'dashboard.html', {
            'output': column2D.render(),
            'B': b,
            'B1': b1,
            'B2': b2,
            'B3': b3,
            'B4': b4,
            'B5': b5,
            'inbox': get_all_inbox(user.username),
            'user': b,
            'created_events': created_events,
            'username': user.username,
            'is_logged_in': is_logged_in,
            'num_of_questions': get_number_of_questions(user.username)
        })
def stats(request):

    stats_page = "active"

    # Get current year
    yearInt = int(datetime.today().strftime('%Y'))

    # Get current month as Int
    monthInt = int(datetime.today().strftime('%m'))

    # Set previous month as Int, keeping in mind if month is Jan to revert to month 12
    if monthInt == 1:
        prevMonth = 12
    else:
        prevMonth = monthInt - 1

    # Get year date of previous month
    if prevMonth == 12:
        prevMonthYear = yearInt - 1
    else:
        prevMonthYear = yearInt

    prevMonthName = calendar.month_name[prevMonth]

    # Total number of days in previous month
    daysInPreviousMonth = monthrange(prevMonthYear, prevMonth)[1]

    # Chart 1 - Feature by upvotes
    dataSource = {}
    dataSource['chart'] = {
        "caption": "Votes per Open Feature",
        "xAxisName": "Feature Name",
        "yAxisName": "Upvotes",
        "theme": "candy",
    }

    dataSource['data'] = []

    for key in Features.objects.all():

        if key.status == True:
            data = {}
            data['label'] = key.featurename
            data['value'] = key.upvotes
            dataSource['data'].append(data)

    # Chart 2 - Ticket Dates Test

    ticketsDatesSource = {}
    ticketsDatesSource['chart'] = {
        "caption": "Tickets Closed",
        "subcaption": "Per Day",
        "xAxisName": "Day of Month",
        "yAxisName": "Tickets Closed",
        "theme": "candy",
    }

    ticketsDatesSource['data'] = []

    # Stats for month in year
    daysInMonth = monthrange(prevMonthYear, prevMonth)

    for i in range(1, daysInMonth[1] + 1):

        data = {}
        data['label'] = str(i)
        data['value'] = 0
        # ticketsDatesSource['data'].append(data)

        for key in Ticket.objects.all():
            time2 = key.closed_date

            if time2:
                yearClosed = int(time2.strftime("%Y"))
                monthClosed = int(time2.strftime("%m"))
                dayClosed = int(time2.strftime("%d"))
                strDayClosed = str(dayClosed)

                if yearClosed == prevMonthYear and monthClosed == prevMonth:
                    if data['label'] == strDayClosed:
                        value = data['value']
                        value += 1
                        data['value'] = value

        ticketsDatesSource['data'].append(data)

    # Calculate average tickets closed per day, week and month
    closed_tickets_for_previous_month = 0

    # Tickets closed in previous month
    for key in Ticket.objects.all():
        timeClosed = key.closed_date

        if timeClosed:
            ticketMonth = int(timeClosed.strftime('%m'))
            ticketYear = int(timeClosed.strftime('%Y'))

            if ticketMonth == prevMonth and ticketYear == yearInt:
                closed_tickets_for_previous_month += 1

    # Average Tickets closed per day
    averageTicketsPerDay = round(
        (closed_tickets_for_previous_month / daysInPreviousMonth), 2)

    # Average Tickets per week
    averageTicketsPerWeek = round((closed_tickets_for_previous_month / 4.345),
                                  2)

    # Charting and rendering of all charts
    column2D = FusionCharts("column2D", "ex1", "800", "350", "chart-1", "json",
                            dataSource)
    ticketChart = FusionCharts("column2D", "ex2", "800", "350", "chart-2",
                               "json", ticketsDatesSource)

    #Highest upvotes for features if there any open features, else template will show message that no open features with votes
    try:
        most_voted_id = Features.objects.values('id').exclude(
            status='False').order_by('-upvotes').first()
        most_votes_name = Features.objects.values('featurename').exclude(
            status='False').order_by('-upvotes').first()
        most_votes = Features.objects.values('upvotes').exclude(
            status='False').order_by('-upvotes').first()
        votes_name = most_votes_name['featurename']
        votes_total = int(most_votes['upvotes'])
        votes_id = int(most_voted_id['id'])
    except:
        votes_id = False
        votes_name = False
        votes_total = False

    return render(
        request, 'stats.html', {
            'output': column2D.render(),
            'output2': ticketChart.render(),
            'votes_id': votes_id,
            'votes_name': votes_name,
            'votes_total': votes_total,
            'averageTicketsPerDay': averageTicketsPerDay,
            'averageTicketsPerWeek': averageTicketsPerWeek,
            'closed_tickets_for_previous_month':
            closed_tickets_for_previous_month,
            'stats_page': stats_page,
            'prevMonthName': prevMonthName,
            'prevMonthYear': prevMonthYear
        })
Пример #30
0
def test(request):
    dataSource = OrderedDict()

    # The `chartConfig` dict contains key-value pairs of data for chart attribute
    chartConfig = OrderedDict()
    chartConfig["caption"] = "No.of Users/Day"
    chartConfig["subCaption"] = ""
    chartConfig["xAxisName"] = "Date"
    chartConfig["yAxisName"] = "No.of Users"
    chartConfig["numberSuffix"] = ""
    chartConfig["theme"] = "fusion"

    # The `chartData` dict contains key-value pairs of data
    chartData = OrderedDict()
    chartData["2018-09-22"] = 2
    chartData["2018-09-23"] = 0
    chartData["2018-09-24"] = 0
    chartData["2018-09-25"] = 0
    chartData["2018-09-26"] = 0
    chartData["2018-09-27"] = 0
    chartData["2018-09-28"] = 0
    chartData["2018-09-29"] = 1
    chartData["2018-09-30"] = 0
    chartData["2018-10-01"] = 0
    chartData["2018-10-02"] = 0
    chartData["2018-10-03"] = 0

    dataSource["chart"] = chartConfig
    dataSource["data"] = []

    # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
    #The data for the chart should be in an array wherein each element of the array
    #is a JSON object# having the `label` and `value` as keys.

    #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.
    for key, value in chartData.items():
        data = {}
        data["label"] = key
        data["value"] = value
        dataSource["data"].append(data)

    column2D = FusionCharts("column2d", "myFirstChart", "600", "400",
                            "myFirstchart-container", "json", dataSource)

    # Create an object for the column 2D chart using the FusionCharts class constructor
    # The chart data is passed to the `dataSource` parameter.

    tes = User.objects.count()
    tes99 = User.objects.all()
    tes1 = Transaction.objects.count()
    tes12 = Transaction.objects.all()
    tes123 = Transaction.objects.annotate(Sum('Amount'))
    tes2 = Transaction.objects.filter(Description__contains='Cashing').count()
    tes44 = Transaction.objects.filter(Description__contains='Cashing')
    tes3 = Transaction.objects.filter(Description__contains='Bill').count()
    tes32 = Transaction.objects.filter(Description__contains='Bill')
    tes4 = Transaction.objects.filter(Description__contains='Friend').count()
    tes45 = Transaction.objects.filter(Description__contains='Friend')
    tes5 = Transaction.objects.filter(Description__contains='Purchase').count()
    tes56 = Transaction.objects.filter(Description__contains='Purchase')

    dataSource2 = OrderedDict()

    # The `chartConfig` dict contains key-value pairs of data for chart attribute
    chartConfig1 = OrderedDict()
    chartConfig1["caption"] = "No.of Active Users/Day"
    chartConfig1["subCaption"] = ""
    chartConfig1["xAxisName"] = "Date"
    chartConfig1["yAxisName"] = "No.of Active User"
    chartConfig1["numberSuffix"] = ""
    chartConfig1["theme"] = "fusion"

    # The `chartData` dict contains key-value pairs of data
    chartData1 = OrderedDict()
    chartData1["2018-09-22"] = 2
    chartData1["2018-09-23"] = 0
    chartData1["2018-09-24"] = 0
    chartData1["2018-09-25"] = 1
    chartData1["2018-09-26"] = 0
    chartData1["2018-09-27"] = 0
    chartData1["2018-09-28"] = 0
    chartData1["2018-09-29"] = 0
    chartData1["2018-09-30"] = 0
    chartData1["2018-10-01"] = 0
    chartData1["2018-10-02"] = 0
    chartData1["2018-10-03"] = 0

    dataSource2["chart"] = chartConfig1
    dataSource2["data"] = []

    # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
    #The data for the chart should be in an array wherein each element of the array
    #is a JSON object# having the `label` and `value` as keys.

    #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.
    for key, value in chartData1.items():
        data1 = {}
        data1["label"] = key
        data1["value"] = value
        dataSource2["data"].append(data1)

    colum2D = FusionCharts("column2d", "myFirstChart1", "600", "400",
                           "myFirstchart-container2", "json", dataSource2)

    dataSource3 = OrderedDict()

    # The `chartConfig` dict contains key-value pairs of data for chart attribute
    chartConfig3 = OrderedDict()
    chartConfig3["caption"] = "No.of Transactions/Day"
    chartConfig3["subCaption"] = ""
    chartConfig3["xAxisName"] = "Date"
    chartConfig3["yAxisName"] = "No.of Transactions"
    chartConfig3["numberSuffix"] = ""
    chartConfig3["theme"] = "fusion"

    # The `chartData` dict contains key-value pairs of data
    chartData3 = OrderedDict()
    chartData3["2018-09-22"] = 6
    chartData3["2018-09-23"] = 0
    chartData3["2018-09-24"] = 0
    chartData3["2018-09-25"] = 1
    chartData3["2018-09-26"] = 0
    chartData3["2018-09-27"] = 0
    chartData3["2018-09-28"] = 0
    chartData3["2018-09-29"] = 0
    chartData3["2018-09-30"] = 0
    chartData3["2018-10-01"] = 0
    chartData3["2018-10-02"] = 0
    chartData3["2018-10-03"] = 0

    dataSource3["chart"] = chartConfig3
    dataSource3["data"] = []

    # Convert the data in the `chartData`array into a format that can be consumed by FusionCharts.
    #The data for the chart should be in an array wherein each element of the array
    #is a JSON object# having the `label` and `value` as keys.

    #Iterate through the data in `chartData` and insert into the `dataSource['data']` list.
    for key, value in chartData3.items():
        data3 = {}
        data3["label"] = key
        data3["value"] = value
        dataSource3["data"].append(data3)

    colun2D = FusionCharts("column2d", "myFirstChart3", "600", "400",
                           "myFirstchart-container3", "json", dataSource3)

    context = {
        'tes': tes,
        'tes123': tes123,
        'tes99': tes99,
        'tes1': tes1,
        'tes2': tes2,
        'tes3': tes3,
        'tes4': tes4,
        'tes5': tes5,
        'tes32': tes32,
        'tes44': tes44,
        'tes45': tes45,
        'tes56': tes56,
        'tes12': tes12,
        'output': column2D.render(),
        'output1': colum2D.render(),
        'output2': colun2D.render(),
    }

    return render(request, 'pay/index2.html', context)