Daily Invoice Volume (Custom Time Series)¶
An AP manager wants to see, on the Insight dashboard, how many invoices the ERP received each day, how many it posted, and how many it put on hold. The numbers live in the ERP's invoice table. KnowledgeLake's own widgets count work items, not ERP postings, so the trend has to come from the ERP side.
At a glance
- Extension point Custom Insight widget, Custom Time Series, 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.ApInvoiceswithReceivedUtc(UTC) andStatus('Posted','OnHold', or another value). Insight Create Dashboards. - Teaches The
Days-To-Includeheader, one row per UTC day with zeros for empty days, several series in one row, and theSeries-Queryprobe.
Set it up¶
- Add the function below to the function app and deploy it.
- Open Insight > Dashboards, open the dashboard, and switch to Edit Mode.
- Drag Custom Time Series from the Custom group onto the dashboard. Open Edit Widget.
- In Custom Insight Settings, set Title to
Invoice Volume, WebRequest Connector to your source (for exampleAP Insight Endpoint), and API Relative Path toinvoice-volume. - Click Get Available Series. The list fills with
Received,PostedandOn Hold, and the first two are selected. AddOn Holdto Visible Series, or clear the list to show all three. - Set Time Range to Last 30 Days and Display Mode to Line Chart. Optional: turn on Use a single shared y-axis for all series and set the axis title
Invoices. - Click Save on the dashboard ribbon.
The function¶
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 InvoiceVolume
{
private static readonly string[] SeriesNames = { "Received", "Posted", "On Hold" };
private const string Query = @"
SELECT CAST(ReceivedUtc AS date) AS Day,
COUNT(*) AS Received,
SUM(CASE WHEN Status = 'Posted' THEN 1 ELSE 0 END) AS Posted,
SUM(CASE WHEN Status = 'OnHold' THEN 1 ELSE 0 END) AS OnHold
FROM dbo.ApInvoices
WHERE ReceivedUtc >= @fromUtc
GROUP BY CAST(ReceivedUtc AS date);";
[Function("InvoiceVolume")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "insight/invoice-volume")] HttpRequest req)
{
if (!InsightHelpers.IsAuthorized(req))
{
return new UnauthorizedResult();
}
// "Get Available Series" in the widget settings sends Series-Query: true.
// Answer with the series names only. Do not query the database.
if (string.Equals(req.Headers["Series-Query"].ToString(), "true", StringComparison.OrdinalIgnoreCase))
{
return InsightHelpers.Json(BuildResponse(new Dictionary<DateTime, int[]>(), DateTime.UtcNow.Date, 0));
}
int days = 30;
if (int.TryParse(req.Headers["Days-To-Include"].ToString(), out int requested))
{
days = Math.Clamp(requested, 1, 90);
}
DateTime today = DateTime.UtcNow.Date;
DateTime fromUtc = today.AddDays(-(days - 1));
var counts = new Dictionary<DateTime, int[]>();
await using (var conn = new SqlConnection(Environment.GetEnvironmentVariable("SqlConnectionString")))
{
await conn.OpenAsync();
await using var cmd = new SqlCommand(Query, conn);
cmd.Parameters.AddWithValue("@fromUtc", fromUtc);
await using var reader = await cmd.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
counts[reader.GetDateTime(0).Date] = new[] { reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3) };
}
}
return InsightHelpers.Json(BuildResponse(counts, today, days));
}
// Pure: one row per UTC day, oldest first, zero when a day has no invoices.
public static JsonObject BuildResponse(IDictionary<DateTime, int[]> counts, DateTime todayUtc, int days)
{
var values = new JsonArray();
for (int i = days - 1; i >= 0; i--)
{
DateTime day = todayUtc.AddDays(-i);
int[] c = counts.TryGetValue(day, out int[]? found) ? found : new[] { 0, 0, 0 };
var row = new JsonObject { ["date"] = InsightHelpers.IsoUtc(day) };
for (int s = 0; s < SeriesNames.Length; s++)
{
row[SeriesNames[s]] = c[s];
}
values.Add(row);
}
var series = new JsonArray();
foreach (string name in SeriesNames)
{
series.Add(name);
}
var data = new JsonObject { ["series"] = series, ["values"] = values };
return InsightHelpers.Envelope("customtimeseries", data, 600);
}
}
const { app } = require('@azure/functions');
const { isAuthorized, envelope, getPool, sql } = require('../insight');
const SERIES = ['Received', 'Posted', 'On Hold'];
const QUERY = `
SELECT CONVERT(char(10), CAST(ReceivedUtc AS date), 23) AS Day,
COUNT(*) AS Received,
SUM(CASE WHEN Status = 'Posted' THEN 1 ELSE 0 END) AS Posted,
SUM(CASE WHEN Status = 'OnHold' THEN 1 ELSE 0 END) AS OnHold
FROM dbo.ApInvoices
WHERE ReceivedUtc >= @fromUtc
GROUP BY CAST(ReceivedUtc AS date);`;
// Pure: one row per UTC day, oldest first, zero when a day has no invoices.
// counts maps "YYYY-MM-DD" to [received, posted, onHold].
function buildResponse(counts, todayUtc, days) {
const values = [];
for (let i = days - 1; i >= 0; i--) {
const key = new Date(todayUtc.getTime() - i * 86400000).toISOString().slice(0, 10);
const c = counts[key] || [0, 0, 0];
const row = { date: key + 'T00:00:00Z' };
SERIES.forEach(function (name, s) { row[name] = c[s]; });
values.push(row);
}
return envelope('customtimeseries', { series: SERIES, values: values }, 600);
}
function utcMidnight(date) {
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
}
app.http('InvoiceVolume', {
methods: ['GET'],
authLevel: 'anonymous',
route: 'insight/invoice-volume',
handler: async function (request) {
if (!isAuthorized(request)) {
return { status: 401 };
}
const today = utcMidnight(new Date());
// "Get Available Series" in the widget settings sends Series-Query: true.
// Answer with the series names only. Do not query the database.
if ((request.headers.get('series-query') || '').toLowerCase() === 'true') {
return { status: 200, jsonBody: buildResponse({}, today, 0) };
}
const requested = parseInt(request.headers.get('days-to-include') || '30', 10);
const days = Number.isNaN(requested) ? 30 : Math.min(Math.max(requested, 1), 90);
const fromUtc = new Date(today.getTime() - (days - 1) * 86400000);
const pool = await getPool();
const result = await pool.request()
.input('fromUtc', sql.DateTime2, fromUtc)
.query(QUERY);
const counts = {};
result.recordset.forEach(function (r) {
counts[r.Day] = [r.Received, r.Posted, r.OnHold];
});
return { status: 200, jsonBody: buildResponse(counts, today, days) };
}
});
module.exports = { buildResponse };
How it works¶
Days-To-Includecarries the widget's Time Range (7, 14, 30, 60 or 90). The function clamps it and falls back to 30, so a missing or odd value never breaks the query.- The SQL groups by UTC calendar day, so each day appears once. The widget keeps only the last row it sees for a day; it never adds two rows together.
BuildResponsewrites a row for every day in the window, oldest first, with zeros where the ERP had nothing. The chart then shows a real zero, whatever the Missing Days setting.- Each row holds all three series as numbers, keyed by the exact series name.
On Holdhas a space;JsonObjectand plain JavaScript objects keep it as written. - On
Series-Query: truethe function returnsdata.serieswith an emptyvaluesarray. Get Available Series needs only the names, so the database is not touched. browserCacheTTLis 600: a daily trend does not need to refresh more than every ten minutes.
Test it¶
- Call the function with a short window:
curl -s https://{function-app}.azurewebsites.net/api/insight/invoice-volume \
-H "Authorization: Bearer $INSIGHT_TOKEN" -H "Days-To-Include: 7"
Check for 7 rows, each dated T00:00:00Z, the last one today in UTC.
2. Call it again with -H "Series-Query: true". Check that values is [] and series lists three names.
3. In the widget settings, click Get Available Series, then save the dashboard.
4. Switch Time Grouping to Weekly and check the weekly totals against your ERP.
The Invoice Volume widget draws three lines over the last 30 days. Table mode shows one row per day with Received, Posted and On Hold columns. Changing Time Range to Last 7 Days and saving shows a 7-day chart.
What can go wrong¶
Watch out
Custom insight json does not match schema: ...names a row and a type error: a series value was a string ornull. Send numbers only; SQLSUMover no rows returnsNULL, so group only days that have rows and fill the rest in code, as above.- Only two lines show. Get Available Series selects the first two series. Edit Visible Series.
- Spikes on one day, gaps on its neighbors. The query grouped by local time while the widget matches UTC days. Group on a UTC column, or convert first.
- Weekly numbers look too high. The series held running totals or rates. Weekly, Monthly and Cumulative add daily values; send per-day counts.
- The newest day is missing for some viewers. The widget builds its day range from the viewer's local midnight converted to UTC. For viewers ahead of UTC, the last bucket is the previous UTC day, so today's row appears only on the next day.
Variations¶
- Money instead of counts Replace
COUNT(*)withSUM(InvoiceTotal)and name the seriesReceived Amount. Turn on the shared y-axis only when the series share a unit. - Gaps instead of zeros Skip the fill loop and return only the days with data. The widget's Missing Days setting (Zero-fill, Gap, Hold or Average) then decides how the chart draws empty days.
Related¶
- Web Request Source Reference: the
customtimeseriescontract andDays-To-Include - Exceptions by Vendor or Queue: one endpoint, several widgets
- Debugging Insight Widgets: schema errors and missing series