{ "name": "easybits Reconciliation Workflow v2 (PDF invoice upload included)", "nodes": [ { "parameters": { "formTitle": "SOA & Invoice Reconciliation Audit", "formDescription": "Upload the Customer Statement of Account (SOA) and your internal Invoice Overview. The system will cross-reference invoice IDs, AED amounts, and LPO numbers to verify billing accuracy.", "formFields": { "values": [ { "fieldLabel": "Customer Statement of Account (SOA)", "fieldType": "file", "fieldName": "soa_file", "acceptFileTypes": ".xlsx", "requiredField": true }, { "fieldLabel": "Invoice Overview / Register", "fieldType": "file", "fieldName": "invoice_file", "acceptFileTypes": ".xlsx, .csv, .pdf", "requiredField": true } ] }, "responseMode": "lastNode", "options": { "path": "reconciliation" } }, "type": "n8n-nodes-base.formTrigger", "typeVersion": 2.5, "position": [ -416, 112 ], "id": "40bd5578-28cf-4485-af24-4c2d2b4d33f0", "name": "Form: Reconciliation Intake" }, { "parameters": { "operation": "completion", "respondWith": "showText", "responseText": "={{ $('Code: Match & Build Report').item.json.html }}" }, "type": "n8n-nodes-base.form", "typeVersion": 2.5, "position": [ 1200, 112 ], "id": "bb81739d-ecda-405e-b148-378556487abc", "name": "Form: Show Summary Report" }, { "parameters": { "jsCode": "// 1. Fetch data safely from all extraction branches\nlet rawSoaItems = [];\ntry { \n rawSoaItems = $('Extract: Bank Statement').all().map(item => item.json); \n} catch (e) { \n rawSoaItems = []; \n}\n\nlet rawExcelInvoices = [];\ntry { \n rawExcelInvoices = $('Extract: Open Invoices').all().map(item => item.json); \n} catch (e) { \n rawExcelInvoices = []; \n}\n\n// Gather all PDF extraction runs across loop iterations\nlet rawPdfInvoices = [];\n\n// Method A: Check the 'Done' branch of the Loop node\ntry {\n const loopDoneItems = $('Loop Over PDF Invoices').all(1);\n if (loopDoneItems && loopDoneItems.length > 0) {\n rawPdfInvoices.push(...loopDoneItems.map(item => item.json));\n }\n} catch (e) {}\n\n// Method B: Collect across all sequential loop executions of the extractor\nif (rawPdfInvoices.length === 0) {\n try {\n let run = 0;\n while (true) {\n try {\n const batch = $('Extract: Open Invoices PDF').all(0, run);\n if (!batch || batch.length === 0) break;\n rawPdfInvoices.push(...batch.map(item => item.json));\n run++;\n } catch (err) {\n break;\n }\n }\n } catch (e) {}\n}\n\n// Method C: Fallback to direct .all() or legacy node names\nif (rawPdfInvoices.length === 0) {\n try {\n rawPdfInvoices = $('Extract: Open Invoices PDF').all().map(item => item.json);\n } catch (e1) {\n try {\n rawPdfInvoices = $('Extract a document').all().map(item => item.json);\n } catch (e2) {\n rawPdfInvoices = [];\n }\n }\n}\n\nconst allRawInvItems = [...rawExcelInvoices, ...rawPdfInvoices];\n\n// 2. Parse the non-standard SOA Layout (handles headers at row 5 and skips bank footers)\nconst soaRecords = [];\nfor (const item of rawSoaItems) {\n let invNo = null, amt = null, date = null, lpo = null;\n\n for (const [key, val] of Object.entries(item)) {\n if (val === null || val === undefined) continue;\n const k = String(key).toLowerCase().trim(), v = String(val).trim();\n if (k.includes('invoice') && v && !v.toLowerCase().includes('invoice number')) invNo = v;\n else if ((k.includes('amount') || k.includes('aed')) && (typeof val === 'number' || !isNaN(parseFloat(v)))) amt = typeof val === 'number' ? val : parseFloat(v);\n else if (k.includes('date') && !k.includes('lpo') && v && !v.toLowerCase().includes('date')) date = v;\n else if (k.includes('lpo') && v && !v.toLowerCase().includes('lpo no')) lpo = v;\n }\n\n if (!invNo) {\n for (const val of Object.values(item)) {\n if (val === null || val === undefined) continue;\n const v = String(val).trim();\n if (/^INV[-_\\s]?\\d+/i.test(v)) invNo = v;\n else if (typeof val === 'number' && val > 0 && amt === null) amt = val;\n else if (/^(LPO|PO)[-_\\s\\/#]?/i.test(v)) lpo = v;\n else if (/\\b(202\\d|Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\\b/i.test(v) && !date && !v.toLowerCase().includes('lpo')) date = v;\n }\n }\n\n if (invNo && !invNo.toLowerCase().includes('invoice') && !invNo.toLowerCase().includes('account') && !invNo.toLowerCase().includes('bank')) {\n soaRecords.push({ \n invoiceNumber: invNo, \n date: date || 'N/A', \n amount: amt !== null && !isNaN(amt) ? Number(amt) : 0.0, \n lpo: lpo || 'N/A' \n });\n }\n}\n\n// 3. Normalize Invoice Records (Unpacks flat Excel headers and EasyBits .data wrappers)\nconst invoiceRecords = [];\nfor (const item of allRawInvItems) {\n const row = item.data || item.extracted_data || item.output || item;\n\n const invNo = row['Invoice Number'] || row['invoice_number'] || row['Invoice ID'] || row['invoice_id'] || row['invoiceNumber'];\n if (!invNo) continue;\n\n const amtRaw = row['Amount in AED'] || row['Amount AED'] || row['amount_aed'] || row['Total Amount Due'] || row['amount'] || row['Total'] || 0;\n const cleanAmt = typeof amtRaw === 'number' ? amtRaw : parseFloat(String(amtRaw).replace(/[^0-9.-]+/g, '')) || 0;\n\n invoiceRecords.push({\n invoiceNumber: String(invNo).trim(),\n date: row['Date'] || row['invoice_date'] || row['Invoice Date'] || row['date'] || 'N/A',\n customer: row['Customer'] || row['Customer Name'] || row['customer_name'] || row['customer'] || 'N/A',\n lpo: row['LPO No'] || row['LPO No and Date'] || row['lpo_number'] || row['lpo'] || row['LPO Reference'] || 'N/A',\n amount: cleanAmt,\n status: row['Status'] || row['status'] || 'Sent'\n });\n}\n\n// 4. Two-Way Reconciliation Logic\nconst exactMatches = [], partialMatches = [], soaOnly = [], unbilled = [];\nconst regMap = new Map(invoiceRecords.map(r => [r.invoiceNumber.toUpperCase(), r]));\nconst soaMap = new Map(soaRecords.map(s => [s.invoiceNumber.toUpperCase(), s]));\n\nfor (const s of soaRecords) {\n const key = s.invoiceNumber.toUpperCase();\n if (regMap.has(key)) {\n const reg = regMap.get(key);\n const diff = s.amount - reg.amount;\n if (Math.abs(diff) < 0.01) exactMatches.push({ soa: s, reg, status: 'Matched' });\n else partialMatches.push({ soa: s, reg, status: 'Amount Discrepancy', discrepancy: diff });\n } else {\n soaOnly.push({ soa: s, status: 'SOA Only (Unregistered)' });\n }\n}\n\nfor (const r of invoiceRecords) {\n const key = r.invoiceNumber.toUpperCase();\n if (!soaMap.has(key)) unbilled.push({ reg: r, status: 'Unbilled (Missing from SOA)' });\n}\n\n// 5. Generate Reconciled CSV (Native Excel Format)\nconst escapeCsv = (str) => '\"' + String(str || '').replace(/\"/g, '\"\"') + '\"';\nconst csvRows = [[\"Invoice Number\", \"Date\", \"Customer\", \"LPO Reference\", \"SOA Amount (AED)\", \"Ledger Amount (AED)\", \"Discrepancy (AED)\", \"Reconciliation Status\", \"Action Required\"].join(\",\")];\n\nexactMatches.forEach(m => {\n const lpoRef = (m.soa.lpo && m.soa.lpo !== 'N/A') ? m.soa.lpo : (m.reg.lpo || 'N/A');\n csvRows.push([\n escapeCsv(m.soa.invoiceNumber), escapeCsv(m.soa.date), escapeCsv(m.reg.customer), escapeCsv(lpoRef),\n m.soa.amount.toFixed(2), m.reg.amount.toFixed(2), \"0.00\",\n escapeCsv(\"Matched\"), escapeCsv(\"None (Verified)\")\n ].join(\",\"));\n});\n\npartialMatches.forEach(m => {\n const lpoRef = (m.soa.lpo && m.soa.lpo !== 'N/A') ? m.soa.lpo : (m.reg.lpo || 'N/A');\n csvRows.push([\n escapeCsv(m.soa.invoiceNumber), escapeCsv(m.soa.date), escapeCsv(m.reg.customer), escapeCsv(lpoRef),\n m.soa.amount.toFixed(2), m.reg.amount.toFixed(2), m.discrepancy.toFixed(2),\n escapeCsv(\"Amount Discrepancy\"), escapeCsv(\"Review Invoice PDF vs Statement\")\n ].join(\",\"));\n});\n\nsoaOnly.forEach(m => {\n csvRows.push([\n escapeCsv(m.soa.invoiceNumber), escapeCsv(m.soa.date), escapeCsv(\"N/A\"), escapeCsv(m.soa.lpo),\n m.soa.amount.toFixed(2), \"0.00\", m.soa.amount.toFixed(2),\n escapeCsv(\"SOA Only (Unregistered)\"), escapeCsv(\"Verify missing invoice / adjust SOA\")\n ].join(\",\"));\n});\n\nunbilled.forEach(m => {\n csvRows.push([\n escapeCsv(m.reg.invoiceNumber), escapeCsv(m.reg.date), escapeCsv(m.reg.customer), escapeCsv(m.reg.lpo),\n \"0.00\", m.reg.amount.toFixed(2), (-m.reg.amount).toFixed(2),\n escapeCsv(\"Unbilled (Missing from SOA)\"), escapeCsv(\"Add invoice to Statement of Account\")\n ].join(\",\"));\n});\n\nconst csvContent = csvRows.join(\"\\n\");\nconst encodedCsvUri = \"data:text/csv;charset=utf-8,\" + encodeURIComponent(csvContent);\n\n// 6. Minimal HTML Download Card for the n8n Form Completion Screen\nconst html = `\n
\n
\n
\n ✓\n
\n

Reconciliation Complete

\n

\n Audited ${soaRecords.length} SOA items against ${invoiceRecords.length} invoice records.\n

\n \n 📥 Download Reconciliation File (Excel / CSV)\n \n
\n
\n`;\n\nreturn {\n json: {\n html: html,\n csvContent: csvContent\n }\n};" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 992, 112 ], "id": "d8f55786-3ed1-4131-8440-9f30cf217765", "name": "Code: Match & Build Report" }, { "parameters": { "numberInputs": 3 }, "type": "n8n-nodes-base.merge", "typeVersion": 3.2, "position": [ 784, 96 ], "id": "8d0712f4-ca95-48f5-a5bd-13e959f3e259", "name": "Merge: Invoices & Bank Data" }, { "parameters": { "operation": "xlsx", "binaryPropertyName": "soa_file", "options": {} }, "type": "n8n-nodes-base.extractFromFile", "typeVersion": 1.1, "position": [ 512, 416 ], "id": "c88edd3c-972c-4ebb-b813-2d84fed1cb2d", "name": "Extract: Bank Statement" }, { "parameters": { "operation": "xlsx", "binaryPropertyName": "invoice_file", "options": {} }, "type": "n8n-nodes-base.extractFromFile", "typeVersion": 1.1, "position": [ 512, -96 ], "id": "28682348-7b6d-4ed6-8476-5395f08bbfad", "name": "Extract: Open Invoices" }, { "parameters": { "rules": { "values": [ { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "leftValue": "={{ $binary.invoice_file.mimeType }}", "rightValue": "sheet", "operator": { "type": "string", "operation": "contains" }, "id": "537a2a2a-a599-4790-b657-a74b709eefc3" } ], "combinator": "and" }, "renameOutput": true, "outputKey": "sheets" }, { "conditions": { "options": { "caseSensitive": true, "leftValue": "", "typeValidation": "strict", "version": 3 }, "conditions": [ { "id": "e3ed61ca-d75b-4050-af9e-221fb5f7ef80", "leftValue": "={{ $binary.invoice_file.mimeType }}", "rightValue": "pdf", "operator": { "type": "string", "operation": "contains" } } ], "combinator": "and" }, "renameOutput": true, "outputKey": "pdfs" } ] }, "options": {} }, "type": "n8n-nodes-base.switch", "typeVersion": 3.4, "position": [ 0, 112 ], "id": "d434e7ae-216e-4ca7-a7ee-2f757c0ecfba", "name": "Switch" }, { "parameters": { "jsCode": "const items = [];\nconst binary = $input.first().binary || {};\n\nconst keys = Object.keys(binary).filter(k => k.startsWith('invoice_file'));\n\nfor (const key of keys) {\n items.push({\n json: {\n fileName: binary[key].fileName,\n mimeType: binary[key].mimeType,\n fileExtension: binary[key].fileExtension\n },\n binary: {\n data: binary[key], // Required by EasyBits Extractor\n invoice_file: binary[key] // Required by Excel Extractor\n }\n });\n}\n\nreturn items.length > 0 ? items : [{ json: { error: 'No invoice files found' } }];" }, "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ -208, 112 ], "id": "efd3734f-dbad-47b5-a4b6-4ae97b542b37", "name": "Code: Split Invoices" }, { "parameters": {}, "type": "@easybits/n8n-nodes-extractor.easybitsExtractor", "typeVersion": 2, "position": [ 512, 112 ], "id": "37d37ac4-f6c1-4ff1-baa2-ca8f9cb7074a", "name": "Extract: Open Invoices PDF" }, { "parameters": { "options": {} }, "type": "n8n-nodes-base.splitInBatches", "typeVersion": 3, "position": [ 240, 112 ], "id": "73eb69a8-ef7a-4eac-bf73-eb7ffa4df4f9", "name": "Loop Over PDF Invoices" }, { "parameters": { "content": "## Reconciliation Automation\npowered by easybits\n\nCross-references a customer Statement of Account against your own invoice register and returns a downloadable audit file.\n\nUpload the SOA (.xlsx) and your invoice register (.xlsx, .csv, or .pdf). The workflow matches on invoice number, compares amounts, and classifies every record as **Matched**, **Amount Discrepancy**, **SOA Only** (customer claims an invoice you never issued), or **Unbilled** (you issued an invoice missing from the statement).\n\nOutput: a CSV download on the completion screen.\n\n## Setup\n\n**1. Install the easybits Extractor node**\nIn n8n, go to Settings, then Community Nodes, and install\n`@easybits/n8n-nodes-extractor`. On n8n Cloud it installs directly.\n\n**2. Create the Extractor credential**\nSign up at extractor.easybits.tech, create an extraction pipeline for invoices, and copy the pipeline ID and the API key. In n8n, add a new **easybits Extractor** credential with the ID and the key, then select it on the **Extract: Open Invoices PDF** node.\n\n**3. Define your extraction schema**\nIn your easybits project, set up the fields the Extractor should pull\nfrom each invoice PDF: invoice number, invoice date, customer name, LPO reference, and total amount. The field names you choose here must be listed in the key lookups inside **Code: Match & Build Report**, so either match the names below or add yours to the list: `Invoice Number`, `Date`, `Customer`, `LPO No`, `Amount in AED`.\n\n**4. Check your column headers**\nIf your invoice register uses headers not in the lookup lists, either\nrename the columns in your file or add your spellings to the `invNo`, `amtRaw`, and `lpo` lookups in **Code: Match & Build Report**.\n\n**6. Activate and grab the form URL**\nActivate the workflow, then open **Form: Reconciliation Intake** and copy the Production URL. That is the link you or your finance team use to run an audit.\n\n**7. Test run**\nUpload a small SOA and a two-invoice register first. Check that the record counts on the completion screen match what you uploaded. A count of zero on either side usually means a header spelling mismatch, not a broken extraction.\n\n## Optional\n\n- The CSV is embedded in the completion page as a data URI, so nothing is stored. To keep a copy, add a Gmail, Drive, or S3 node after **Code: Match & Build Report** using the `csvContent` field.\n- Amounts are compared but never used for matching, so a typo'd invoice number appears twice: once as SOA Only, once as Unbilled.", "height": 1200, "width": 496 }, "type": "n8n-nodes-base.stickyNote", "position": [ -1008, -400 ], "typeVersion": 1, "id": "54350af6-911d-40e8-a189-a244b2ce2a7d", "name": "Sticky Note" }, { "parameters": { "content": "### 1. Intake & Routing\nForm collects both uploads, splits multi-file invoice uploads into single items, and routes each one by file type.", "height": 320, "width": 656, "color": 4 }, "type": "n8n-nodes-base.stickyNote", "position": [ -496, -16 ], "typeVersion": 1, "id": "2aa3d141-9480-43ad-9887-5380dc0aa94a", "name": "Sticky Note1" }, { "parameters": { "content": "### 2. Invoice Extraction\nSpreadsheets are read natively. PDFs go through the easybits Extractor.", "height": 496, "width": 512, "color": 2 }, "type": "n8n-nodes-base.stickyNote", "position": [ 176, -208 ], "typeVersion": 1, "id": "7d9c1a21-e435-4654-a24b-14bc0ff8687f", "name": "Sticky Note2" }, { "parameters": { "content": "### 3. SOA Extraction\nReads the customer statement as raw rows. Column mapping happens in the reconciliation step, since statements rarely start at row 1.", "height": 288, "width": 512, "color": 5 }, "type": "n8n-nodes-base.stickyNote", "position": [ 176, 304 ], "typeVersion": 1, "id": "a205e22f-7cc1-43cf-9543-bbbcdb101a08", "name": "Sticky Note3" }, { "parameters": { "content": "### 4. Reconciliation & Report\nWaits for all branches, normalizes both datasets, matches invoice\nnumbers in both directions, and builds the CSV download card.", "height": 352, "width": 688, "color": 6 }, "type": "n8n-nodes-base.stickyNote", "position": [ 704, -32 ], "typeVersion": 1, "id": "a046322b-d041-41a5-8f9e-5263a3a50fe2", "name": "Sticky Note4" } ], "pinData": {}, "connections": { "Form: Reconciliation Intake": { "main": [ [ { "node": "Extract: Bank Statement", "type": "main", "index": 0 }, { "node": "Code: Split Invoices", "type": "main", "index": 0 } ] ] }, "Code: Match & Build Report": { "main": [ [ { "node": "Form: Show Summary Report", "type": "main", "index": 0 } ] ] }, "Merge: Invoices & Bank Data": { "main": [ [ { "node": "Code: Match & Build Report", "type": "main", "index": 0 } ] ] }, "Extract: Bank Statement": { "main": [ [ { "node": "Merge: Invoices & Bank Data", "type": "main", "index": 2 } ] ] }, "Extract: Open Invoices": { "main": [ [ { "node": "Merge: Invoices & Bank Data", "type": "main", "index": 0 } ] ] }, "Switch": { "main": [ [ { "node": "Extract: Open Invoices", "type": "main", "index": 0 } ], [ { "node": "Loop Over PDF Invoices", "type": "main", "index": 0 } ] ] }, "Code: Split Invoices": { "main": [ [ { "node": "Switch", "type": "main", "index": 0 } ] ] }, "Extract: Open Invoices PDF": { "main": [ [ { "node": "Loop Over PDF Invoices", "type": "main", "index": 0 } ] ] }, "Loop Over PDF Invoices": { "main": [ [ { "node": "Merge: Invoices & Bank Data", "type": "main", "index": 1 } ], [ { "node": "Extract: Open Invoices PDF", "type": "main", "index": 0 } ] ] } }, "active": false, "settings": { "executionOrder": "v1", "availableInMCP": false }, "tags": [] }