Validate Invoices and Send Exceptions to Review¶
Invoices are matched to purchase orders in an ERP later in the workflow. An invoice with no PO number, a total that is not a number, or a duplicate invoice number fails there and stops the work item. Catch it early: check every invoice against a set of rules, record each problem on the document, and send the work item to an exception review task when anything is wrong.
At a glance
- Extension point Custom Step with a route
- You need Document fields
Index.InvoiceNumber,Index.InvoiceDate(ISO date),Index.InvoiceTotal,Index.PONumber,Index.VendorTaxId; global variablesPoPattern(Text) andMaxInvoiceTotal(Decimal, optional); a review task; permission to edit the workflow. - Teaches Errors versus warnings, a regular expression from a global variable, duplicates inside a work item, and an exception route.
Set it up¶
- In the Workflow app, open Global Variables. Add
PoPattern(Generic Value, Text) with a regular expression for a valid PO number, for example^PO-?\d{6}$. Optionally addMaxInvoiceTotal(Decimal), for example250000. - In the Workflow designer, add a Custom Step after extraction and before the ERP steps. Name it "Validate Invoices". Paste the script below.
- From "Validate Invoices", draw a route to the review task with this Javascript condition:
(workItem.Metadata["General"] || {})["ValidationStatus"] === "Invalid" - Make the route to the ERP steps the default route. From the review task, route back to "Validate Invoices", so a corrected invoice is checked again.
- To show the problems to the reviewer, add a field
ValidationErrorsto the content type the task uses, and change the script's last document write fromGeneraltoIndex.
Script¶
The script writes document General.ValidationStatus (Valid, Warning or Invalid) and General.ValidationErrors, rewrites a valid Index.PONumber in a clean form, and writes work item General.ValidationStatus and General.InvalidCount.
// Custom Step "Validate Invoices". After extraction, before the ERP steps.
// Reads: Index.InvoiceNumber, InvoiceDate, InvoiceTotal, PONumber, VendorTaxId (each document);
// global variables PoPattern (required) and MaxInvoiceTotal (optional).
// Writes: General.ValidationStatus, General.ValidationErrors, cleaned Index.PONumber (each document);
// General.ValidationStatus, General.InvalidCount (work item).
(function () {
var poPattern;
try {
poPattern = new RegExp(GlobalVariables.Get("PoPattern"), "i");
} catch (e) {
throw new Error("Global variable PoPattern is missing or is not a valid regular expression");
}
var maxTotal = 1000000;
try {
maxTotal = parseFloat(GlobalVariables.Get("MaxInvoiceTotal")) || maxTotal;
} catch (e) {
// Optional variable: keep the default.
}
// Values people type when there is no PO.
var noPo = ["", "N/A", "NA", "NONE", "NO PO", "TBD", "0"];
function toNumber(text) {
var n = parseFloat(String(text || "").replace(/[^0-9.\-]/g, ""));
return isNaN(n) ? null : n;
}
var seenNumbers = {};
var invalidCount = 0;
var warningCount = 0;
for (var i = 0; i < batch.Documents.length; i++) {
var doc = batch.Documents[i];
var f = doc.Metadata["Index"] || {};
var errors = [];
var warnings = [];
// 1. Required fields
if (!f["InvoiceNumber"]) { errors.push("InvoiceNumber is required"); }
if (!f["InvoiceTotal"]) { errors.push("InvoiceTotal is required"); }
// 2. PO number: present, and in the expected format
var rawPo = String(f["PONumber"] || "");
var po = rawPo.trim().toUpperCase().replace(/\s+/g, " ");
if (noPo.indexOf(po) >= 0) {
errors.push("PO number is required");
} else if (!poPattern.test(po)) {
errors.push("PO number '" + rawPo + "' does not match the expected format");
} else if (po !== rawPo) {
// Store the cleaned value so the ERP lookup gets one format.
builder.SetDocumentMetadata(doc.DocumentId, "Index", "PONumber", po);
}
// 3. Formats
var date = new Date(f["InvoiceDate"]);
if (f["InvoiceDate"] && isNaN(date.getTime())) {
errors.push("InvoiceDate '" + f["InvoiceDate"] + "' is not a date");
}
if (f["VendorTaxId"] && !/^\d{2}-\d{7}$/.test(f["VendorTaxId"])) {
warnings.push("VendorTaxId is not in the form 12-3456789");
}
// 4. Ranges
var total = toNumber(f["InvoiceTotal"]);
if (f["InvoiceTotal"] && total === null) { errors.push("InvoiceTotal is not a number"); }
if (total !== null && total <= 0) { errors.push("InvoiceTotal must be above 0"); }
if (total !== null && total > maxTotal) { warnings.push("InvoiceTotal is over " + maxTotal); }
if (!isNaN(date.getTime()) && date > new Date()) { warnings.push("InvoiceDate is in the future"); }
// 5. Duplicates inside this work item
var number = String(f["InvoiceNumber"] || "").trim().toUpperCase();
if (number) {
if (seenNumbers[number]) {
errors.push("InvoiceNumber duplicates document " + seenNumbers[number]);
} else {
seenNumbers[number] = i + 1;
}
}
var status = errors.length > 0 ? "Invalid" : (warnings.length > 0 ? "Warning" : "Valid");
if (status === "Invalid") { invalidCount++; }
if (status === "Warning") { warningCount++; }
builder.SetDocumentMetadata(doc.DocumentId, "General", "ValidationStatus", status);
builder.SetDocumentMetadata(doc.DocumentId, "General", "ValidationErrors", errors.concat(warnings).join("; "));
}
var overall = invalidCount > 0 ? "Invalid" : (warningCount > 0 ? "Warning" : "Valid");
builder.SetBatchMetadata("General", "ValidationStatus", overall);
builder.SetBatchMetadata("General", "InvalidCount", String(invalidCount));
})();
How it works¶
PoPatternis required, so a missing or broken pattern fails the step with a clear message.MaxInvoiceTotalis optional: thetry/catchkeeps a default when it does not exist.- The PO check catches the placeholders people type when there is no PO, then tests the format. A valid PO is stored in one clean form for the ERP lookup.
- Errors make a document
Invalidand send the work item to review. Warnings are recorded but do not stop the work item. Keep new or strict rules as warnings until you have seen real data. seenNumbersremembers each invoice number and its position, so a duplicate names the document it repeats.- The route reads one work-item value,
General.ValidationStatus. A work item with only warnings takes the default route.
Test it¶
- Upload a work item with four invoices: one clean (
PO-123456), one with PON/A, one with no total, and one with the same invoice number as the first. - Open the work item in Monitor or Insight, and check each document's
General.ValidationStatusandGeneral.ValidationErrors. - Upload one clean invoice on its own.
You should see
the first work item in the review task with General.InvalidCount = 3, and messages such as PO number is required and InvoiceNumber duplicates document 1 on the right documents. The clean work item takes the default route with General.ValidationStatus = Valid.
What can go wrong¶
Watch out
- Valid POs go to review.
PoPatternis too strict. Test it against a list of real PO numbers first. - The step fails at
new RegExp.PoPatternis missing, or the pattern has an error such as an unclosed bracket. - Valid invoices are flagged. A format rule is stricter than real data, for example a tax id with no dash. Move it to
warnings. - Duplicates across work items are not caught. The script sees one work item only. Check duplicates in the destination system, or in your own endpoint.
- The ERP lookup still fails for a valid-looking PO. The PO exists in a different format in the ERP, or not at all. This step checks format only. Handle the ERP's "not found" result after the lookup too.
Variations¶
- Alert on exceptions outside KnowledgeLake. Put a Custom Event step on the route to the review task. See Validation Exception Event.
- Different rules per content type. Read
General.ContentTypeIdon each document and keep a rule set per id in a JSON global variable.