Skip to content

Exceptions by Vendor or Queue (Custom Categorical)

An AP supervisor wants two pie charts on the Insight dashboard: open invoice exceptions by vendor, to spot a supplier that sends bad invoices, and the same exceptions by work queue, to see which team is behind. Both come from the same exception table in the ERP. One endpoint serves both widgets; the grouping comes from each widget's API Relative Path.

At a glance

  • Extension point Custom Insight widget, Custom Categorical, fed by a Web Request source.
  • You need A function app with the endpoint skeleton, a Web Request source that points at it (set up in KPI: Open Exceptions, steps 1 to 3), and a SQL table dbo.InvoiceExceptions with Status, VendorName, QueueName and ExceptionReason. Insight Create Dashboards.
  • Teaches Parameters in the API Relative Path, an allow-list for anything that reaches SQL text, and top N plus an "Other" slice.

Set it up

  1. Add the function below to the function app and deploy it.
  2. Open Insight > Dashboards, open the dashboard, and switch to Edit Mode.
  3. Drag Custom Categorical from the Custom group onto the dashboard. Open Edit Widget.
  4. In Custom Insight Settings, set Title to Exceptions by Vendor, WebRequest Connector to your source, and API Relative Path to exceptions-breakdown?groupBy=vendor&top=8. Choose Pie Chart.
  5. Add a second Custom Categorical widget. Set Title to Exceptions by Queue and API Relative Path to exceptions-breakdown?groupBy=queue. Choose Table if the queue names are long.
  6. Click Save on the dashboard ribbon.

The function

ExceptionsBreakdown.cs
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Data.SqlClient;

namespace InsightWidgets;

public class ExceptionsBreakdown
{
    // groupBy value from the widget's API Relative Path -> the column to group on.
    // Only these columns can reach the SQL text.
    private static readonly Dictionary<string, string> Columns = new(StringComparer.OrdinalIgnoreCase)
    {
        ["vendor"] = "VendorName",
        ["queue"] = "QueueName",
        ["reason"] = "ExceptionReason"
    };

    [Function("ExceptionsBreakdown")]
    public async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "insight/exceptions-breakdown")] HttpRequest req)
    {
        if (!InsightHelpers.IsAuthorized(req))
        {
            return new UnauthorizedResult();
        }

        string groupBy = req.Query["groupBy"].ToString();
        if (!Columns.TryGetValue(groupBy, out string? column))
        {
            return new BadRequestObjectResult("groupBy must be vendor, queue or reason.");
        }
        int top = int.TryParse(req.Query["top"].ToString(), out int t) ? Math.Clamp(t, 1, 20) : 8;

        string query = $@"
SELECT COALESCE({column}, '(none)') AS Title, COUNT(*) AS Amount
FROM dbo.InvoiceExceptions
WHERE Status = 'Open'
GROUP BY COALESCE({column}, '(none)')
ORDER BY Amount DESC;";

        var rows = new List<(string Title, int Amount)>();
        await using (var conn = new SqlConnection(Environment.GetEnvironmentVariable("SqlConnectionString")))
        {
            await conn.OpenAsync();
            await using var cmd = new SqlCommand(query, conn);
            await using var reader = await cmd.ExecuteReaderAsync();
            while (await reader.ReadAsync())
            {
                rows.Add((reader.GetString(0), reader.GetInt32(1)));
            }
        }

        return InsightHelpers.Json(BuildResponse(rows, top, DateTime.UtcNow));
    }

    // Pure: the largest `top` groups, then one "Other" slice for the rest.
    public static JsonObject BuildResponse(IList<(string Title, int Amount)> rows, int top, DateTime nowUtc)
    {
        var datapoints = new JsonArray();
        foreach (var row in rows.OrderByDescending(r => r.Amount).Take(top))
        {
            datapoints.Add(new JsonObject { ["title"] = row.Title, ["amount"] = row.Amount });
        }
        int other = rows.OrderByDescending(r => r.Amount).Skip(top).Sum(r => r.Amount);
        if (other > 0)
        {
            datapoints.Add(new JsonObject { ["title"] = "Other", ["amount"] = other });
        }

        var data = new JsonObject
        {
            ["values"] = new JsonArray(new JsonObject
            {
                ["date"] = InsightHelpers.IsoUtc(nowUtc),
                ["datapoints"] = datapoints
            })
        };
        return InsightHelpers.Envelope("customcategorical", data, 300);
    }
}
src/functions/exceptionsBreakdown.js
const { app } = require('@azure/functions');
const { isAuthorized, envelope, isoUtc, getPool } = require('../insight');

// groupBy value from the widget's API Relative Path -> the column to group on.
// Only these columns can reach the SQL text.
const COLUMNS = { vendor: 'VendorName', queue: 'QueueName', reason: 'ExceptionReason' };

// Pure: the largest `top` groups, then one "Other" slice for the rest.
function buildResponse(rows, top, now) {
    const sorted = rows.slice().sort(function (a, b) { return b.Amount - a.Amount; });
    const datapoints = sorted.slice(0, top).map(function (r) {
        return { title: r.Title, amount: r.Amount };
    });
    const other = sorted.slice(top).reduce(function (sum, r) { return sum + r.Amount; }, 0);
    if (other > 0) {
        datapoints.push({ title: 'Other', amount: other });
    }
    return envelope('customcategorical', { values: [{ date: isoUtc(now), datapoints: datapoints }] }, 300);
}

app.http('ExceptionsBreakdown', {
    methods: ['GET'],
    authLevel: 'anonymous',
    route: 'insight/exceptions-breakdown',
    handler: async function (request) {
        if (!isAuthorized(request)) {
            return { status: 401 };
        }
        const column = COLUMNS[(request.query.get('groupBy') || '').toLowerCase()];
        if (!column) {
            return { status: 400, body: 'groupBy must be vendor, queue or reason.' };
        }
        const requested = parseInt(request.query.get('top') || '8', 10);
        const top = Number.isNaN(requested) ? 8 : Math.min(Math.max(requested, 1), 20);

        const query =
            'SELECT COALESCE(' + column + ", '(none)') AS Title, COUNT(*) AS Amount " +
            "FROM dbo.InvoiceExceptions WHERE Status = 'Open' " +
            'GROUP BY COALESCE(' + column + ", '(none)') ORDER BY Amount DESC;";

        const pool = await getPool();
        const result = await pool.request().query(query);
        return { status: 200, jsonBody: buildResponse(result.recordset, top, new Date()) };
    }
});

module.exports = { buildResponse };

How it works

  • KnowledgeLake keeps the query string of the API Relative Path, so exceptions-breakdown?groupBy=vendor&top=8 reaches the function as two query parameters. Each widget sends its own.
  • groupBy never reaches SQL as typed. It selects a column name from a fixed map; anything else gets 400. Any dashboard author can type a relative path, so treat it as untrusted input.
  • COALESCE(..., '(none)') gives rows with no vendor or queue a label. A null title fails the schema.
  • BuildResponse keeps the largest top groups and sums the rest into one "Other" slice. A pie with 40 thin slices is unreadable.
  • values holds one dataset dated now. Custom Categorical shows only the dataset with the newest date, so there is no point in sending history.

Test it

  1. Call both variants:
curl -s "https://{function-app}.azurewebsites.net/api/insight/exceptions-breakdown?groupBy=vendor&top=3" \
  -H "Authorization: Bearer $INSIGHT_TOKEN"
curl -i "https://{function-app}.azurewebsites.net/api/insight/exceptions-breakdown?groupBy=amount" \
  -H "Authorization: Bearer $INSIGHT_TOKEN"

The first returns at most four datapoints (three vendors and "Other"). The second returns 400. 2. Save the dashboard with both widgets and reload it.

Exceptions by Vendor

shows a pie with up to eight vendors and an "Other" slice. Exceptions by Queue shows one row per queue with the Category and Value columns. The totals of both widgets match the open count in KPI: Open Exceptions.

What can go wrong

Watch out

  • The custom insight endpoint could not be reached. after you change the path: the function returned 400 for an unknown groupBy, or 404 because the route name differs in case or spelling. Call the URL with curl to see the status.
  • Custom insight json does not match schema: ... about title: a group label came back null. Keep the COALESCE.
  • The pie shows yesterday's numbers. You sent several datasets and an older one had a later date, or the browser cache still holds the last result. Send one dataset dated now.
  • The widgets disagree with the KPI. They filter on different Status values. Use the same filter in all three queries.

Variations

  • Only the viewer's queues Read Viewer-Token, look up the queues that user owns in your system, and add them to the WHERE clause as parameters.
  • Amount at risk Replace COUNT(*) with SUM(InvoiceTotal), so the slices show money instead of item counts.