Loop Through Documents and Total the Work Item¶
An accounts payable team scans a stack of invoices as one work item. Before approval, the workflow needs these values on the work item: the invoice count, the total, the average, the highest and lowest amount, and how many invoices are overdue. It also needs to know, on each invoice, whether its amount could be read. Most Custom Steps have this shape: one loop over the documents, a result per document, and a summary on the work item.
At a glance
- Extension point Custom Step
- You need Document fields
Index.InvoiceTotalandIndex.DueDate(an ISO date such as2026-10-31); permission to edit the workflow. - Teaches The loop, safe number parsing, per-document results, work-item summaries, and totals per category.
Set it up¶
- In the Workflow designer, add a Custom Step after extraction or indexing. Name it "Invoice Totals".
- Paste the script below into the JavaScript Block.
- Save the step and the workflow.
Script¶
The script writes document General.AmountStatus (OK or Missing) and work item General.InvoiceCount, General.MissingAmountCount, General.TotalAmount, General.AverageAmount, General.HighestAmount, General.LowestAmount and General.OverdueCount.
// Custom Step "Invoice Totals". After extraction or indexing.
// Reads: Index.InvoiceTotal, Index.DueDate (each document).
// Writes: General.AmountStatus (each document); General.InvoiceCount, MissingAmountCount,
// TotalAmount, AverageAmount, HighestAmount, LowestAmount, OverdueCount (work item).
function readIndex(doc, key) {
return (doc.Metadata["Index"] || {})[key] || "";
}
function toNumber(text) {
var n = parseFloat(String(text).replace(/[^0-9.\-]/g, ""));
return isNaN(n) ? null : n;
}
var count = 0;
var missing = 0;
var total = 0;
var highest = null;
var lowest = null;
var overdue = 0;
var today = new Date();
today.setHours(0, 0, 0, 0);
for (var i = 0; i < batch.Documents.length; i++) {
var doc = batch.Documents[i];
var amount = toNumber(readIndex(doc, "InvoiceTotal"));
if (amount === null) {
missing++;
builder.SetDocumentMetadata(doc.DocumentId, "General", "AmountStatus", "Missing");
continue;
}
count++;
total += amount;
if (highest === null || amount > highest) { highest = amount; }
if (lowest === null || amount < lowest) { lowest = amount; }
var due = new Date(readIndex(doc, "DueDate"));
if (!isNaN(due.getTime()) && due < today) {
overdue++;
}
builder.SetDocumentMetadata(doc.DocumentId, "General", "AmountStatus", "OK");
}
// Work-item values last. Routes read this level.
builder.SetBatchMetadata("General", "InvoiceCount", String(count));
builder.SetBatchMetadata("General", "MissingAmountCount", String(missing));
builder.SetBatchMetadata("General", "TotalAmount", total.toFixed(2));
builder.SetBatchMetadata("General", "AverageAmount", count > 0 ? (total / count).toFixed(2) : "0.00");
builder.SetBatchMetadata("General", "HighestAmount", highest === null ? "" : highest.toFixed(2));
builder.SetBatchMetadata("General", "LowestAmount", lowest === null ? "" : lowest.toFixed(2));
builder.SetBatchMetadata("General", "OverdueCount", String(overdue));
How it works¶
batch.Documentsis a plain array, in work item order. Aforloop orforEachboth work.readIndexguards the bucket, so a document with noIndexbucket reads as empty instead of throwing.- Every value is a string.
toNumberstrips currency symbols and thousands separators before it parses, and returnsnullfor text with no number. - The writes are queued. They apply when the script ends, so
readIndexstill returns the old values in this run. - The sum is rounded once, at the end, with
toFixed(2), so floating-point error does not show.
Test it¶
- Upload a work item with three invoices with known totals, one with a past due date, and a fourth with no total.
- Open the work item in Monitor or Insight. Check the seven work-item values, then
General.AmountStatuson each document.
You should see
General.InvoiceCount = 3, General.MissingAmountCount = 1, General.OverdueCount = 1, the right General.TotalAmount, and General.AmountStatus = Missing only on the fourth document.
What can go wrong¶
Watch out
- All amounts are missing. The key is spelled differently, for example
Invoice Totalwith a space. Copy the exact key from the content type. - The values do not appear. An older example wrote them to the
Systembucket. The engine skips writes toSystem. UseGeneral. OverdueCountis always 0.DueDateis not a date thatnew Date()can read, such as31/10/2026. Store ISO dates, or parse the parts yourself.- A total like
1.234,56parses wrong. The value uses a comma as the decimal mark. Normalize it before you parse.
Variations¶
Totals per category. To total by a category field (for example Index.Department), keep an object of running totals, then write one key per category and one JSON summary:
var byDepartment = {};
for (var i = 0; i < batch.Documents.length; i++) {
var index = batch.Documents[i].Metadata["Index"] || {};
var dept = index["Department"] || "Unassigned";
var amount = parseFloat(String(index["InvoiceTotal"] || "").replace(/[^0-9.\-]/g, "")) || 0;
byDepartment[dept] = (byDepartment[dept] || 0) + amount;
}
for (var dept in byDepartment) {
builder.SetBatchMetadata("General", "Total_" + dept.replace(/\W/g, ""), byDepartment[dept].toFixed(2));
}
builder.SetBatchMetadata("General", "DepartmentTotals", JSON.stringify(byDepartment));
Delete or move documents in a loop. Queued writes do not change batch.Documents during the run, so a loop that queues deletes is safe. The array changes only when builder.ApplyChanges() reloads batch. If you need ApplyChanges(), collect the ids first, act second, and call it once:
var toDelete = [];
for (var i = 0; i < batch.Documents.length; i++) {
if (batch.Documents[i].Pages.length === 0) {
toDelete.push(batch.Documents[i].DocumentId);
}
}
for (var j = 0; j < toDelete.length; j++) {
builder.DeleteDocument(toDelete[j]);
}
Related¶
- Custom Step Reference
- Set a Routing Value from Metadata
- Work With Line-Item Tables
- Invoice Approved Milestone Event: send the totals to your own dashboard.