Skip to content

KPI: Open Exceptions (Custom Text)

An accounts payable team works invoice exceptions in its own ERP exception queue, outside KnowledgeLake. The team lead wants the open count, and how many have aged past five days, at the top of the AP dashboard in Insight, so nobody has to open a second system to see the backlog.

At a glance

  • Extension point Custom Insight widget, Custom Text, fed by a Web Request source.
  • You need An Azure Function app with the endpoint skeleton (InsightHelpers and Validate), app settings InsightBearerToken and SqlConnectionString, and a SQL table dbo.InvoiceExceptions with Status ('Open' for open items) and CreatedUtc (UTC). Connections Edit Configuration and Insight Create Dashboards.
  • Teaches The smallest complete endpoint: token check, one query, the customtext envelope, and Markdown output.

Set it up

  1. Deploy the function app with the skeleton files and the function below. Set the app settings InsightBearerToken (a long random value) and SqlConnectionString.
  2. In KnowledgeLake, open Connections > Sources > Add a Source. Set Source Type to Web Request and Source Name to AP Insight Endpoint.
  3. Enter Endpoint URL https://{function-app}.azurewebsites.net/api/insight, Bearer Token (the same value as InsightBearerToken) and Timeout (seconds) 30. Click Test Connection, then SAVE.
  4. Open Insight > Dashboards and open the AP dashboard (or Actions > New Dashboard). Switch to Edit Mode.
  5. Drag Custom Text from the Custom group onto the dashboard and open Edit Widget.
  6. In Custom Insight Settings, set Title to AP Exceptions, WebRequest Connector to AP Insight Endpoint, and API Relative Path to open-exceptions.
  7. Set Render Mode to Markdown. Click Save on the dashboard ribbon.

The function

OpenExceptions.cs
using System.Globalization;
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 OpenExceptions
{
    private const string Query = @"
SELECT COUNT(*) AS OpenCount,
       COALESCE(SUM(CASE WHEN CreatedUtc < DATEADD(day, -5, SYSUTCDATETIME()) THEN 1 ELSE 0 END), 0) AS AgedCount
FROM dbo.InvoiceExceptions
WHERE Status = 'Open';";

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

        int openCount;
        int agedCount;
        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();
            await reader.ReadAsync();
            openCount = reader.GetInt32(0);
            agedCount = reader.GetInt32(1);
        }

        return InsightHelpers.Json(BuildResponse(openCount, agedCount, DateTime.UtcNow));
    }

    // Pure: builds the Custom Text payload. Unit test this without a database.
    public static JsonObject BuildResponse(int openCount, int agedCount, DateTime nowUtc)
    {
        string open = openCount.ToString("N0", CultureInfo.InvariantCulture);
        string aged = agedCount.ToString("N0", CultureInfo.InvariantCulture);
        string text = $"## {open} open exceptions\n\n{aged} are older than 5 days.\n\nUpdated {nowUtc:HH:mm} UTC";

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

const QUERY = `
SELECT COUNT(*) AS OpenCount,
       COALESCE(SUM(CASE WHEN CreatedUtc < DATEADD(day, -5, SYSUTCDATETIME()) THEN 1 ELSE 0 END), 0) AS AgedCount
FROM dbo.InvoiceExceptions
WHERE Status = 'Open';`;

// Pure: builds the Custom Text payload. Unit test this without a database.
function buildResponse(openCount, agedCount, now) {
    const fmt = new Intl.NumberFormat('en-US');
    const text = '## ' + fmt.format(openCount) + ' open exceptions\n\n' +
        fmt.format(agedCount) + ' are older than 5 days.\n\n' +
        'Updated ' + now.toISOString().slice(11, 16) + ' UTC';
    return envelope('customtext', { values: [{ date: isoUtc(now), str: text }] }, 300);
}

app.http('OpenExceptions', {
    methods: ['GET'],
    authLevel: 'anonymous',
    route: 'insight/open-exceptions',
    handler: async function (request) {
        if (!isAuthorized(request)) {
            return { status: 401 };
        }
        const pool = await getPool();
        const result = await pool.request().query(QUERY);
        const row = result.recordset[0];
        return { status: 200, jsonBody: buildResponse(row.OpenCount, row.AgedCount, new Date()) };
    }
});

module.exports = { buildResponse };

How it works

  • The route insight/open-exceptions sits under the function app's api prefix, so it answers {Endpoint URL}/open-exceptions. The skeleton's Validate function answers {Endpoint URL}/validate.
  • The token check runs first. A wrong or missing token gets 401 and no query runs.
  • One query returns both numbers. COALESCE turns the empty-table NULL into 0, so the widget never shows a blank.
  • The Markdown string carries the formatting: a heading for the count, a line for the aged items, and the time of the reading. The widget renders it because Render Mode is Markdown.
  • values holds exactly one item. Custom Text shows the newest item, and an empty array leaves the widget on Loading….
  • browserCacheTTL is 300, so each viewer's browser reuses the result for five minutes before it asks again.

Test it

  1. Run the function locally (func start) and call it:
curl -i http://localhost:7071/api/insight/validate -H "Authorization: Bearer $INSIGHT_TOKEN"
curl -s http://localhost:7071/api/insight/open-exceptions -H "Authorization: Bearer $INSIGHT_TOKEN"

The first call returns HTTP/1.1 200 OK. Without the header it returns 401. 2. Compare the second response with View Example JSON in the widget settings, or validate it against https://{tenant}/api/CustomInsightExample/CustomInsightSchema. 3. Deploy, then click Test Connection on the source. KnowledgeLake cannot reach localhost. 4. Save the dashboard and reload it.

The widget titled AP Exceptions shows a heading such as 1,284 open exceptions, the line "37 are older than 5 days.", and "Updated 14:05 UTC". The "Showing Mock Data Until Save" overlay is gone.

What can go wrong

Watch out

  • The endpoint rejected the bearer token (401/403). on Test Connection: the source token and InsightBearerToken differ. Paste the value again; watch for a trailing space or line break.
  • The custom insight endpoint could not be reached. in the widget: the function returned 500 (read its log; usually the connection string or a firewall rule on the database), or it took longer than the Timeout.
  • The widget shows ## 1,284 open exceptions with the hash marks. Render Mode is Plain Text. Switch it to Markdown.
  • The count is stale. The browser cache holds the result for browserCacheTTL seconds. Lower it while you test.

Variations

  • Color by threshold Markdown cannot set colors, so put the urgency in words ("Over target: 37 aged items") or set the widget's Text Color for the whole widget.
  • Per-viewer scope Read the Viewer-Token header, map it to the queues that person owns, and count only those. Keep the mapping in your system.