{ "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 Audited ${soaRecords.length} SOA items against ${invoiceRecords.length} invoice records.\n
\n \n 📥 Download Reconciliation File (Excel / CSV)\n \n