Work With Line-Item Tables¶
Extraction fills a line-item table on each invoice, but the table is not ready for export: an OCR mistake reads $ as S, amounts carry stray characters, and a second description column should be merged into the first. The approver also needs to know whether the lines add up to the invoice total. One Custom Step cleans the table, writes it back, and summarizes it.
At a glance
- Extension point Custom Step
- You need A document table field
Index.LineItemswhose first row holds the column names, includingDescription,Amountand optionallyDetail; document fieldIndex.InvoiceTotal; fieldsLineCount,LineTotalandLargestLineon the content type; permission to edit the workflow. - Teaches
ConvertTableFieldToTableArray, finding columns by header name, changing cells, removing a column, andConvertTableArrayToTableField.
A table field's value is CSV text. builder.ConvertTableFieldToTableArray turns it into rows of cells, and builder.ConvertTableArrayToTableField turns rows back into CSV. Both run at once; they are not queued.
Set it up¶
- In the Workflow designer, add a Custom Step after extraction or after an indexing task. Name it "Line Items".
- Paste the script below into the JavaScript Block.
- Add
LineCount,LineTotalandLargestLineto the document's content type if the approver should see them. - Save the step and the workflow.
Script¶
The script rewrites document Index.LineItems, and writes document Index.LineCount, Index.LineTotal, Index.LargestLine and General.TotalsMatch (Yes or No).
// Custom Step "Line Items". After extraction.
// Reads: Index.LineItems (table, header row), Index.InvoiceTotal (each document).
// Writes: Index.LineItems (cleaned), Index.LineCount, Index.LineTotal, Index.LargestLine,
// General.TotalsMatch (each document).
var TABLE_KEY = "LineItems";
function columnIndex(header, name) {
for (var c = 0; c < header.length; c++) {
if (String(header[c]).trim().toLowerCase() === name.toLowerCase()) { return c; }
}
return -1;
}
function toNumber(text) {
var n = parseFloat(String(text || "").replace(/[^0-9.\-]/g, ""));
return isNaN(n) ? 0 : n;
}
for (var i = 0; i < batch.Documents.length; i++) {
var doc = batch.Documents[i];
var index = doc.Metadata["Index"] || {};
var raw = index[TABLE_KEY];
if (!raw) {
builder.SetDocumentMetadata(doc.DocumentId, "Index", "LineCount", "0");
continue;
}
var rows = builder.ConvertTableFieldToTableArray(raw);
var header = rows[0] || [];
var colAmount = columnIndex(header, "Amount");
var colDescription = columnIndex(header, "Description");
var colDetail = columnIndex(header, "Detail");
if (colAmount < 0) {
throw new Error("Table " + TABLE_KEY + " on document " + doc.DocumentId + " has no Amount column");
}
var count = 0;
var lineTotal = 0;
var largest = { text: "", amount: 0 };
for (var r = 1; r < rows.length; r++) {
var row = rows[r];
if (row.length === 1 && row[0] === "") { continue; } // empty last row
// 1. Clean the amount: an OCR "S" in front of a number becomes "$",
// then keep only digits, currency symbol, separators and minus.
var amountText = String(row[colAmount] || "");
if (/^\s*S\s*\d[\d,]*(\.\d+)?\s*$/.test(amountText)) {
amountText = amountText.replace("S", "$");
}
row[colAmount] = amountText.replace(/[^0-9$.,\-]/g, "");
// 2. Merge Detail into Description.
if (colDescription >= 0 && colDetail >= 0) {
var detail = String(row[colDetail] || "").trim();
if (detail) {
row[colDescription] = String(row[colDescription] || "").trim() + " " + detail;
}
}
// 3. Summarize.
var amount = toNumber(row[colAmount]);
count++;
lineTotal += amount;
if (amount > largest.amount) {
largest = { text: colDescription >= 0 ? row[colDescription] : "Row " + r, amount: amount };
}
}
// Remove the merged column from every row, header included.
if (colDescription >= 0 && colDetail >= 0) {
for (var k = 0; k < rows.length; k++) {
rows[k].splice(colDetail, 1);
}
}
var matches = Math.abs(lineTotal - toNumber(index["InvoiceTotal"])) < 0.01;
builder.SetDocumentMetadata(doc.DocumentId, "Index", TABLE_KEY, builder.ConvertTableArrayToTableField(rows));
builder.SetDocumentMetadata(doc.DocumentId, "Index", "LineCount", String(count));
builder.SetDocumentMetadata(doc.DocumentId, "Index", "LineTotal", lineTotal.toFixed(2));
builder.SetDocumentMetadata(doc.DocumentId, "Index", "LargestLine", largest.text + " (" + largest.amount.toFixed(2) + ")");
builder.SetDocumentMetadata(doc.DocumentId, "General", "TotalsMatch", matches ? "Yes" : "No");
}
How it works¶
ConvertTableFieldToTableArrayreturns an array of rows. Each row is an array of cell strings. Row 0 is the header.columnIndexfinds columns by header name, ignoring case and spaces, so the script still works when the column order changes.- Each cleanup is its own numbered block. Delete the ones you do not need.
- The
Detailcolumn is removed after the loop, from every row, so the header and the cells stay aligned. - The table is written back once per document with
SetDocumentMetadata, together with the summary values. General.TotalsMatchcompares the line total with the invoice total to the cent. Route on it, or show it to the approver.
Test it¶
- Upload an invoice whose table has an
AmountcellS1,250.00, aDetailcolumn, and lines that add up to the invoice total. - Upload a second invoice whose lines do not add up.
- Open the work item in Monitor or Insight and check each document.
You should see
the first document's table with $1,250.00 in the amount cell, no Detail column, the detail text appended to Description, and General.TotalsMatch = Yes. The second document has General.TotalsMatch = No and its own Index.LineTotal.
What can go wrong¶
Watch out
- "has no Amount column". The header text differs, for example
Line Amount. Write the header row into a metadata value once (JSON.stringify(rows[0])) to see the real names. - The step fails with "failed to parse value into TableArray". The field holds text that is not CSV.
- The count is one too high. The table had an empty last row. Keep the empty-row check.
- A column is missing after the step. The merge removed
Detail. If the content type still expects that column, clear its cells instead of removing it. - A value like
12O.5Obecomes12.5. The cleanup removes letters, so an OCROfor0is lost. ReplaceOwith0first if your documents show that error. - Nothing changes. The table is on the work item, not the documents, or the key differs. Read and write the same level.
Variations¶
Normalize a date column. Convert MM/DD/YYYY cells to ISO dates inside the row loop:
function toIsoDate(text) {
var m = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(String(text).trim());
if (!m) { return text; }
return m[3] + "-" + (m[1].length === 1 ? "0" + m[1] : m[1]) + "-" + (m[2].length === 1 ? "0" + m[2] : m[2]);
}
Header objects instead of positions. For read-only work, Papa.parse(raw, { header: true, skipEmptyLines: true }).data gives one object per row, keyed by column name.