Skip to content

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.LineItems whose first row holds the column names, including Description, Amount and optionally Detail; document field Index.InvoiceTotal; fields LineCount, LineTotal and LargestLine on the content type; permission to edit the workflow.
  • Teaches ConvertTableFieldToTableArray, finding columns by header name, changing cells, removing a column, and ConvertTableArrayToTableField.

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

  1. In the Workflow designer, add a Custom Step after extraction or after an indexing task. Name it "Line Items".
  2. Paste the script below into the JavaScript Block.
  3. Add LineCount, LineTotal and LargestLine to the document's content type if the approver should see them.
  4. 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
// 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

  • ConvertTableFieldToTableArray returns an array of rows. Each row is an array of cell strings. Row 0 is the header.
  • columnIndex finds 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 Detail column 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.TotalsMatch compares the line total with the invoice total to the cent. Route on it, or show it to the approver.

Test it

  1. Upload an invoice whose table has an Amount cell S1,250.00, a Detail column, and lines that add up to the invoice total.
  2. Upload a second invoice whose lines do not add up.
  3. 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.5O becomes 12.5. The cleanup removes letters, so an OCR O for 0 is lost. Replace O with 0 first 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:

Variation: MM/DD/YYYY to ISO
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.