{
  "name": "Financial Close Reconciliation Accelerator",
  "nodes": [
    {
      "parameters": {
        "formTitle": "Financial Close Reconciliation",
        "formDescription": "Upload your bank statement and ledger as CSV files. Each CSV should have columns: id, date, amount, description.",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Bank Statement CSV",
              "fieldType": "file",
              "fieldName": "Bank Statement CSV",
              "multipleFiles": false,
              "acceptFileTypes": ".csv",
              "requiredField": true
            },
            {
              "fieldLabel": "Ledger CSV",
              "fieldType": "file",
              "fieldName": "Ledger CSV",
              "multipleFiles": false,
              "acceptFileTypes": ".csv",
              "requiredField": true
            }
          ]
        },
        "responseMode": "lastNode",
        "options": {}
      },
      "id": "f88f1656-0efe-4ef8-a997-6ed640f14d02",
      "name": "On Reconciliation Upload",
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.6,
      "position": [
        0,
        96
      ],
      "webhookId": "e32407d6-f123-49e5-87f1-dbd453a892a7"
    },
    {
      "parameters": {
        "jsCode": "const item = $input.first();\nconst json = item.json || {};\nconst binary = item.binary || {};\n\n// Filenames declared per field in the trigger's JSON metadata\nconst bankMeta = json['Bank Statement CSV'] || {};\nconst ledgerMeta = json['Ledger CSV'] || {};\nconst bankName = bankMeta.filename || bankMeta.fileName;\nconst ledgerName = ledgerMeta.filename || ledgerMeta.fileName;\n\nconst keys = Object.keys(binary);\nlet bankBin = null;\nlet ledgerBin = null;\n\n// First pass: match by filename\nfor (const k of keys) {\n  const b = binary[k] || {};\n  const fn = b.fileName || b.filename;\n  if (!bankBin && bankName && fn === bankName) { bankBin = b; continue; }\n  if (!ledgerBin && ledgerName && fn === ledgerName) { ledgerBin = b; }\n}\n\n// Fallback: assign remaining binaries by upload order\nconst remaining = keys.filter(k => binary[k] !== bankBin && binary[k] !== ledgerBin);\nif (!bankBin && remaining.length) { bankBin = binary[remaining.shift()]; }\nif (!ledgerBin && remaining.length) { ledgerBin = binary[remaining.shift()]; }\n\nif (!bankBin) { throw new Error('Bank Statement CSV upload not found in submission.'); }\nif (!ledgerBin) { throw new Error('Ledger CSV upload not found in submission.'); }\n\nreturn [{ json, binary: { bank: bankBin, ledger: ledgerBin } }];"
      },
      "id": "4553ba92-e5b5-419b-9084-a07119fec484",
      "name": "Normalize Uploads",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        224,
        96
      ]
    },
    {
      "parameters": {
        "binaryPropertyName": "bank",
        "options": {
          "headerRow": true
        }
      },
      "id": "431accb0-1a81-498e-a6c9-35bb6e4f6533",
      "name": "Extract Bank CSV",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        448,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// Read parsed CSV rows from the two Extract from File nodes.\n// CSV values arrive as strings, so normalize id/date/amount/description.\nconst norm = (rows) => (rows || []).map(i => {\n  const r = i.json || {};\n  return {\n    id: String(r.id != null ? r.id : '').trim(),\n    date: String(r.date != null ? r.date : '').trim(),\n    amount: Number(String(r.amount != null ? r.amount : '').replace(/[^0-9.-]/g, '')),\n    description: String(r.description != null ? r.description : '').trim(),\n  };\n});\n\nconst bank = norm($('Extract Bank CSV').all());\nconst ledger = norm($('Extract Ledger CSV').all());\n\nconst matched = [];\nconst bankUnmatched = [];\nconst usedLedger = {};\n\nfor (const b of bank) {\n  let found = null;\n  for (const l of ledger) {\n    if (!usedLedger[l.id] && l.date === b.date && Number(l.amount) === Number(b.amount)) {\n      found = l;\n      break;\n    }\n  }\n  if (found) {\n    usedLedger[found.id] = true;\n    matched.push({ bank_id: b.id, ledger_id: found.id, date: b.date, amount: b.amount, description: b.description, method: 'exact_prematch' });\n  } else {\n    bankUnmatched.push(b);\n  }\n}\n\nconst ledgerUnmatched = ledger.filter(l => !usedLedger[l.id]);\n\nreturn [{ json: {\n  matched,\n  bank_unmatched: bankUnmatched,\n  ledger_unmatched: ledgerUnmatched,\n  total_bank: bank.length,\n  total_ledger: ledger.length,\n} }];"
      },
      "id": "67a4133d-4e69-4e95-bea6-71f03d588ac6",
      "name": "Pre-Match Exact Transactions",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        896,
        96
      ]
    },
    {
      "parameters": {
        "jsCode": "const data = $input.first().json;\nconst bankUnmatched = data.bank_unmatched || [];\nconst ledgerUnmatched = data.ledger_unmatched || [];\nconst matched = data.matched || [];\n\nconst lines = [];\nlines.push('You are a financial reconciliation assistant helping close the books.');\nlines.push('Match each unmatched BANK transaction to its most likely LEDGER counterpart.');\nlines.push('');\nlines.push('Matching guidance:');\nlines.push('- Small rounding differences under $1 are usually the SAME transaction (likely_match).');\nlines.push('- Date differences of 1-3 days are usually timing delays, NOT errors (likely_match).');\nlines.push('- A bank transaction with no plausible ledger counterpart, or a duplicate-looking charge, must be flagged as a discrepancy.');\nlines.push('- Each ledger transaction can only be used once. If a duplicate bank charge has no remaining ledger match, flag it as a discrepancy.');\nlines.push('');\nlines.push('UNMATCHED BANK TRANSACTIONS:');\nlines.push(JSON.stringify(bankUnmatched, null, 2));\nlines.push('');\nlines.push('UNMATCHED LEDGER TRANSACTIONS:');\nlines.push(JSON.stringify(ledgerUnmatched, null, 2));\nlines.push('');\nlines.push('Respond ONLY with JSON in exactly this shape (no markdown, no commentary):');\nlines.push('{\"results\": [{\"bank_id\": \"\", \"ledger_id\": \"\", \"status\": \"likely_match or discrepancy\", \"reasoning\": \"\"}]}');\n\nconst prompt = lines.join('\\n');\n\nreturn [{ json: {\n  prompt,\n  matched,\n  bank_unmatched: bankUnmatched,\n  ledger_unmatched: ledgerUnmatched,\n  total_bank: data.total_bank,\n  total_ledger: data.total_ledger,\n} }];"
      },
      "id": "b132b65d-3da1-453c-8fb2-ec1ab94216e3",
      "name": "Build AI Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1120,
        96
      ]
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini",
          "cachedResultName": "gpt-4o-mini"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "You are a precise financial reconciliation assistant. Respond only with valid JSON."
            },
            {
              "content": "={{ $json.prompt }}"
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          },
          "temperature": 0
        }
      },
      "id": "3e4af652-95f1-4291-beb9-dbcaa3e1895f",
      "name": "OpenAI Chat Completion",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.3,
      "position": [
        1344,
        96
      ],
      "credentials": {
        "openAiApi": {
          "id": null,
          "name": "n8n credits",
          "__aiGatewayManaged": true
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const ai = $json; // OpenAI dedicated node (Responses API, simplified)\nlet content = '';\ntry { content = ai.output[0].content[0].text; } catch (e) { content = ''; }\n\nlet parsed = { results: [] };\nif (content && typeof content === 'object') {\n  // json_object format: text is already a parsed object\n  parsed = content;\n} else {\n  try {\n    parsed = JSON.parse(content);\n  } catch (e) {\n    const m = (content || '').match(/\\{[\\s\\S]*\\}/);\n    if (m) { try { parsed = JSON.parse(m[0]); } catch (e2) {} }\n  }\n}\n\nconst results = Array.isArray(parsed.results) ? parsed.results : [];\nconst ai_matches = results.filter(r => r && r.status === 'likely_match');\nconst discrepancies = results.filter(r => !r || r.status !== 'likely_match');\n\nconst pre = $('Build AI Prompt').first().json;\nconst matched = pre.matched || [];\nconst total = Number(pre.total_bank) || 0;\n\nconst auto_reconciled_count = matched.length + ai_matches.length;\nconst flagged_for_review_count = discrepancies.length;\nconst auto_reconciled_pct = total > 0 ? Math.round((auto_reconciled_count / total) * 100) : 0;\n\nconst discLines = discrepancies.map(d => '• Bank ' + ((d && d.bank_id) || 'unknown') + ': ' + ((d && d.reasoning) || 'No reasoning provided'));\nconst discrepancy_text = discLines.length\n  ? ('Financial close discrepancies flagged for human review:\\n' + discLines.join('\\n'))\n  : 'No discrepancies flagged.';\n\nconst summary = {\n  total_transactions: total,\n  auto_reconciled_count,\n  flagged_for_review_count,\n  auto_reconciled_pct,\n};\n\nreturn [{ json: { matched, ai_matches, discrepancies, summary, discrepancy_text } }];"
      },
      "id": "b8108807-8edf-4ecb-ac77-9ca4c9299375",
      "name": "Parse & Categorize Results",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1568,
        96
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "disc-count",
              "leftValue": "={{ $json.discrepancies.length }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ]
        },
        "options": {}
      },
      "id": "04e5c34d-0cd0-4c7d-af9f-7324310c2e9d",
      "name": "Any Discrepancies?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1792,
        96
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://hooks.slack.com/services/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",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: $json.discrepancy_text }) }}",
        "options": {}
      },
      "id": "9d44bdcc-9c31-4be5-b80e-457e034a1bad",
      "name": "Post Discrepancies to Slack",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2016,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "const d = $('Parse & Categorize Results').first().json;\nconst s = d.summary || {};\n\nconst headline = (s.auto_reconciled_count || 0) + ' of ' + (s.total_transactions || 0) +\n  ' transactions reconciled automatically (' + (s.auto_reconciled_pct || 0) + '%). ' +\n  (s.flagged_for_review_count || 0) + ' flagged for human review.';\n\nreturn [{ json: {\n  headline,\n  summary: s,\n  matched: d.matched || [],\n  ai_matches: d.ai_matches || [],\n  discrepancies: d.discrepancies || [],\n} }];"
      },
      "id": "c092cf4f-8a18-41f3-b9de-c3e35e236667",
      "name": "Final Summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2240,
        96
      ]
    },
    {
      "parameters": {},
      "id": "14b49f67-892a-4527-9cf5-698e8e7bb997",
      "name": "No Discrepancies (No-Op)",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        2016,
        192
      ]
    },
    {
      "parameters": {
        "binaryPropertyName": "ledger",
        "options": {
          "headerRow": true
        }
      },
      "id": "cd45824c-d353-449b-b029-d9473198d115",
      "name": "Extract Ledger CSV",
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        448,
        192
      ]
    },
    {
      "parameters": {},
      "id": "a1b2c3d4-0000-4000-8000-000000000001",
      "name": "Merge CSV Branches",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        672,
        96
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "On Reconciliation Upload": {
      "main": [
        [
          {
            "node": "Normalize Uploads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize Uploads": {
      "main": [
        [
          {
            "node": "Extract Bank CSV",
            "type": "main",
            "index": 0
          },
          {
            "node": "Extract Ledger CSV",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Bank CSV": {
      "main": [
        [
          {
            "node": "Merge CSV Branches",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Ledger CSV": {
      "main": [
        [
          {
            "node": "Merge CSV Branches",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge CSV Branches": {
      "main": [
        [
          {
            "node": "Pre-Match Exact Transactions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Pre-Match Exact Transactions": {
      "main": [
        [
          {
            "node": "Build AI Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build AI Prompt": {
      "main": [
        [
          {
            "node": "OpenAI Chat Completion",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Completion": {
      "main": [
        [
          {
            "node": "Parse & Categorize Results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse & Categorize Results": {
      "main": [
        [
          {
            "node": "Any Discrepancies?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Any Discrepancies?": {
      "main": [
        [
          {
            "node": "Post Discrepancies to Slack",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "No Discrepancies (No-Op)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Post Discrepancies to Slack": {
      "main": [
        [
          {
            "node": "Final Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "No Discrepancies (No-Op)": {
      "main": [
        [
          {
            "node": "Final Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate"
  },
  "versionId": "9128e8f9-cc0e-42e9-991e-eafd3418d458",
  "meta": {
    "instanceId": "3fc61fb0d3e8f60748860bbe6f6d2d76855ecfa9424031b21a2b760ad41a281c"
  },
  "nodeGroups": [],
  "id": "indIEakexY86VqLo",
  "tags": []
}