Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Task 2 A: Reports: KPIs and JavaScript charts

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

75 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The league table on match day

After every match, the league table changes. Nobody adds up the points by hand. A computer counts wins, draws and goals, and a chart shows who is rising.

Netheret's manager needs the same for the help desk. How many requests are open? How fast are they fixed? Is Tier 1 solving enough?

Key words

WordWhat it meansExample
KPIKey performance indicator: a number that shows how well something is going.
QueryA question you ask the stored data.
AverageThe total shared out equally.average hours to resolve
JavaScriptThe language that runs inside the browser.
CanvasAn HTML element JavaScript can draw on.
FunctionA named block of code that does one job.

The cells students fill in are left blank in this preview.

By the end of this lesson

Note

I can work out KPIs from the stored data and show them as charts.

Starter: what you already know

Have a go

Starter: what you already know

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Sprint 4, step 12: the goal and stories

PartFor this step
Sprint (a short block of work)Sprint 4: reports, accessibility (use by everyone) and security.
E5.1As a manager, I want KPI reports, so that I can see how the help desk is doing.
E5.2As a manager, I want charts of the numbers, so that I can spot changes quickly.

The cells students fill in are left blank in this preview.

One small function for each KPI

reports.py has one function for each question, and each asks one query. You can read them one at a time.

open_by_priority counts open requests, grouped by priority. A priority with none still shows, as 0.

The average time to resolve takes each resolved request, finds the hours from raised to resolved, and averages them per priority. It only works because step 7 kept resolved_at right.

Step 12: two KPI functions

Code: python
# helpdesk/reports.py (part)
OPEN_STATUSES = ["new", "open", "waiting"]


def open_by_priority():
    """How many requests are still open at each priority."""
    rows = db.session.execute(
        db.select(Ticket.priority, func.count(Ticket.id))
        .where(Ticket.status.in_(OPEN_STATUSES))
        .group_by(Ticket.priority)
    ).all()
    counts = dict(rows)
    # Every priority in the usual order, with 0 for any that have none.
    return [(priority, counts.get(priority, 0)) for priority in PRIORITIES]


def hours_to_resolve_by_priority():
    """The average time from raised to resolved, in hours, per priority."""
    # julianday() is SQLite's way to turn a date into a number of days, so
    # subtracting two of them and multiplying by 24 gives hours.
    hours = (func.julianday(Ticket.resolved_at) - func.julianday(Ticket.created_at)) * 24
    rows = db.session.execute(
        db.select(Ticket.priority, func.avg(hours))
        .where(Ticket.resolved_at.is_not(None))
        .group_by(Ticket.priority)
    ).all()

Make a free account to save your work and track your progress.

Check: KPI queries

Have a go

Check: KPI queries

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

A percentage that never divides by zero

First-contact resolution is the share of finished requests that Tier 1 fixed without escalating. It is a percentage.

If nothing is finished yet, dividing by zero would crash the page. So the function checks first and reports 0.

Check a KPI by working it out by hand from the sample data, then comparing it with the page. The test log does this.

Worked example: first-contact resolution

StepValue
Finished requests8
Of those, still at Tier 16
6 out of 8 is the same as75 out of 100
So the KPI is75%
If there are no finished requestsShow 0%, do not divide

The cells students fill in are left blank in this preview.

Step 12: first-contact resolution

Code: python
# helpdesk/reports.py (part)
def first_contact_resolution():
    """The percentage of finished requests that Tier 1 fixed without escalating."""
    finished = db.session.scalar(
        db.select(func.count(Ticket.id)).where(Ticket.status.in_(FINISHED_STATUSES))
    )
    at_tier_one = db.session.scalar(
        db.select(func.count(Ticket.id))
        .where(Ticket.status.in_(FINISHED_STATUSES), Ticket.tier == 1)
    )
    if not finished:
        return 0
    return round(100 * at_tier_one / finished)

Make a free account to save your work and track your progress.

Your turn: fix the percentage

This is first-contact resolution in plain Python. An AI coding assistant wrote the first version. Run it. It crashes when nothing is finished, and 2 of 3 gives 66, not 67. Fix it: report 0 when the list is empty, and round to the nearest whole number. Then work out 6 of 8 by hand and check your function agrees.

Code: python
def percent_at_tier_one(tiers):
    # tiers holds the tier of each finished request, such as [1, 1, 3].
    # Give back the percentage fixed at Tier 1, as a whole number.
    # An AI coding assistant wrote this first version. Run it, then fix it.
    at_one = 0
    for tier in tiers:
        if tier == 1:
            at_one = at_one + 1
    return at_one * 100 // len(tiers)


print(percent_at_tier_one([1, 1, 3]))   # 2 of 3: should be 67
# Then try: print(percent_at_tier_one([]))   (no finished requests yet)

Make a free account to save your work, or press Start lab to work through the whole lesson.

JavaScript draws the chart from the table

The page shows each KPI as a normal HTML table. Then charts.js, in JavaScript, reads each table with the class chart and draws a bar chart above it on a canvas.

This is the second language of the app. Python works out the numbers on the server; JavaScript draws them in the browser.

The table stays, so a screen reader reads the numbers. The chart is marked hidden from screen readers.

Try it: a chart from a table

Code: web
<table class="chart">
  <caption>Open requests by priority</caption>
  <thead><tr><th scope="col">Priority</th><th scope="col">Open requests</th></tr></thead>
  <tbody>
    <tr><th scope="row">Low</th><td>2</td></tr>
    <tr><th scope="row">Medium</th><td>1</td></tr>
    <tr><th scope="row">High</th><td>3</td></tr>
    <tr><th scope="row">Critical</th><td>1</td></tr>
  </tbody>
</table>
<!-- Try it: press Edit, change High from 3 to 6, and watch the chart. -->

Make a free account to save your work and track your progress.

A common mistake

Warning

Many students think a chart can replace the table. A blind manager cannot see a chart, and anyone may want the exact numbers. Keep the data as a table with a caption and headings. Draw the chart from it, so both always agree.

Check: charts

Have a go

Check: charts

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Match each KPI to its data

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Build it yourself: step 12

Build step 12. 1. Write reports.py with one function per KPI from your Task 1 proposal, and a manager-only page. 2. Show each KPI in a table with a caption and headings. 3. Add charts.js to draw a bar chart from every table with the class chart. 4. Test by hand: work out two KPIs from your sample data with a calculator and compare them with the page. Open the page as Tier 1 and check it is refused. 5. Commit and write the change log row.

A teacher marks this in a college. Nothing you write here is kept: it goes when you leave the page.

Make a free account to save your work, or press Start lab to work through the whole lesson.

Compare with the step 12 code

Tip

Compare yours with the step 12 code on GitHub. The real charts.js also reads the page's colours from the CSS and draws sharp text on any screen.

Change log entry for step 12

DateVersion and filesWhat changedWhy
18 Marchstep-12: reports.py, static/js/charts.js, reports.html, base.htmlA manager-only reports page with KPIs from queries, and bar charts drawn from the tables in JavaScriptThe client wants data about how systems and teams are performing

The cells students fill in are left blank in this preview.

Next: accessibility settings

In step 13 every user can choose larger text and high contrast. The choice is saved on their account, so it follows them to any computer.

Exit quiz

Have a go

Exit quiz

5 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.