{
  "name": "Bank Statement to QuickBooks Import",
  "nodes": [
    {
      "parameters": {
        "operation": "pdf",
        "binaryPropertyName": "Bank_Statement_PDF",
        "options": {
          "password": "205355306"
        }
      },
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        -512,
        2384
      ],
      "id": "4c02aa36-7fce-40ce-899f-ab91298484f1",
      "name": "Extract PDF Text"
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Extract all financial transactions from the provided bank statement text.\n\n{{ $json.text }}\n\nFor EACH transaction, do the following carefully:\n\n1. Determine whether the transaction is:\n   - \"credit\" → money received / deposited\n   - \"debit\" → money spent / withdrawn\n\n2. Extract:\n   - Transaction date (convert to YYYY-MM-DD format)\n   - Full transaction description\n   - Transaction amount (always a positive number)\n   - Reference number if present (otherwise return an empty string)\n   - Payee or counterparty name (clean and human-readable)\n\nImportant rules:\n- Do NOT return explanations or extra text.\n- Do NOT wrap the result in an object.\n- Return ONLY a JSON array.\n- Each transaction must strictly follow the defined schema.\n- If any field is missing in the statement, return an empty string (not null).\n\nReturn format example:\n[\n  {\n    \"transactionType\": \"debit\",\n    \"date\": \"YYYY-MM-DD\",\n    \"description\": \"string\",\n    \"amount\": number,\n    \"referenceNumber\": \"string\",\n    \"payee\": \"string\"\n  }\n]",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "You are a financial data extraction expert.\nYou specialize in reading bank statements and converting them into structured transaction data.\nYou must be precise with dates, amounts, and credit/debit classification.\nOutput must strictly match the requested JSON schema with no additional text."
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        -336,
        2384
      ],
      "id": "ac5bdffa-c9ca-4895-b3f0-8e0a62a4f70c",
      "name": "Transaction Extractor AI",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"array\",\n  \"items\": {\n    \"type\": \"object\",\n    \"properties\": {\n      \"transactionType\": {\n        \"type\": \"string\",\n        \"enum\": [\"credit\", \"debit\"]\n      },\n      \"date\": {\n        \"type\": \"string\",\n        \"pattern\": \"^\\\\d{4}-\\\\d{2}-\\\\d{2}$\"\n      },\n      \"description\": {\n        \"type\": \"string\"\n      },\n      \"amount\": {\n        \"type\": \"number\"\n      },\n      \"referenceNumber\": {\n        \"type\": \"string\"\n      },\n      \"payee\": {\n        \"type\": \"string\"\n      }\n    },\n    \"required\": [\n      \"transactionType\",\n      \"date\",\n      \"description\",\n      \"amount\",\n      \"referenceNumber\",\n      \"payee\"\n    ]\n  }\n}"
      },
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "typeVersion": 1.3,
      "position": [
        -176,
        2592
      ],
      "id": "9e7c625d-cf17-40e2-82bd-8fa347500309",
      "name": "JSON Output Parser"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://sandbox-quickbooks.api.intuit.com/v3/company/company_id/salesreceipt?minorversion=75",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "quickBooksOAuth2Api",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json) }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2288,
        2368
      ],
      "id": "f716a32d-73fd-4880-a89b-50ca78a84319",
      "name": "Create QuickBooks SalesReceipt",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "formTitle": "QuickBooks Bank Statement Upload",
        "formDescription": "Upload your bank statement PDF to automatically create entries in QuickBooks",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Bank Statement PDF",
              "fieldType": "file",
              "acceptFileTypes": ".pdf",
              "requiredField": true
            }
          ]
        },
        "options": {
          "appendAttribution": false
        }
      },
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.3,
      "position": [
        -688,
        2384
      ],
      "id": "c6da9b06-cfd1-4817-9f92-89ef83595f80",
      "name": "Bank Statement Form",
      "webhookId": "9821e4cc-29fa-4b5b-85b7-5523e2e17a24"
    },
    {
      "parameters": {
        "model": "openai/gpt-oss-20b:free",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "typeVersion": 1,
      "position": [
        -352,
        2592
      ],
      "id": "99e8f9f3-5c25-4b55-95b8-e86d59b37d6a",
      "name": "OpenRouter Chat Model",
      "credentials": {
        "openRouterApi": {
          "id": "9lpcAhgXlMTyr0Vp",
          "name": "OpenRouter account"
        }
      }
    },
    {
      "parameters": {
        "fieldToSplitOut": "output",
        "options": {}
      },
      "type": "n8n-nodes-base.splitOut",
      "typeVersion": 1,
      "position": [
        -48,
        2384
      ],
      "id": "ff0fc56e-71e0-49d6-8d5d-26710f1db245",
      "name": "Split Transactions"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        160,
        2384
      ],
      "id": "3e5fa8b1-17aa-4f7e-96e8-8861f75bf207",
      "name": "Loop Over Items"
    },
    {
      "parameters": {
        "jsCode": "// // --------------------------------\n// // 1. Get transaction correctly\n// // --------------------------------\n// const txn = $('Loop Over Items').first().json;\n\n// // --------------------------------\n// // 2. Get resolved itemRef\n// // --------------------------------\n// const itemRef = $('Collect All Item Mappings').first().json.itemRef;\n\n// // --------------------------------\n// // 3. Hard validation\n// // --------------------------------\n// if (!txn.amount) {\n//   throw new Error('Transaction amount missing');\n// }\n\n// if (!itemRef?.value) {\n//   throw new Error('ItemRef not resolved');\n// }\n\n// const amount = Number(txn.amount);\n\n// if (isNaN(amount)) {\n//   throw new Error('Amount is not a number');\n// }\n\n// // --------------------------------\n// // 4. Build SalesReceipt payload\n// // --------------------------------\n// const payload = {\n//   Line: [\n//     {\n//       LineNum: 1,\n//       Amount: amount,\n//       Description: txn.description || '',\n//       DetailType: 'SalesItemLineDetail',\n//       SalesItemLineDetail: {\n//         ItemRef: {\n//           value: itemRef.value,\n//           name: itemRef.name\n//         },\n//         Qty: 1,\n//         UnitPrice: amount,\n//         TaxCodeRef: {\n//           value: 'NON'\n//         }\n//       }\n//     }\n//   ],\n//   TxnDate: txn.date,\n//   PrivateNote: `${txn.description} - Ref: ${txn.referenceNumber || 'N/A'}`,\n//   CustomerRef: {\n//     value: '1'\n//   },\n//   DepositToAccountRef: {\n//     value: '35'\n//   },\n//   TotalAmt: amount\n// };\n\n// return { json: payload };\n\n\n\n// --------------------------------\n// 1. Transaction\n// --------------------------------\nconst txn = $('Loop Over Items').first().json;\n\n// --------------------------------\n// 2. ItemRef\n// --------------------------------\nconst itemRef = $('Collect All Item Mappings').first().json.itemRef;\n\n// --------------------------------\n// 3. Resolve CustomerRef DIRECTLY\n// --------------------------------\nlet customer;\n\n// Try existing customer first\ntry {\n  customer = $('Get many customers').first().json;\n} catch (_) {}\n\n// If not found, use newly created customer\nif (!customer?.Id) {\n  customer = $('Create a Customer').first().json;\n}\n\nif (!customer?.Id) {\n  throw new Error('Customer not resolved');\n}\n\nconst customerRef = {\n  value: customer.Id,\n  name: customer.DisplayName\n};\n\n// --------------------------------\n// 4. Validation\n// --------------------------------\nconst amount = Number(txn.amount);\n\nif (!amount || isNaN(amount)) {\n  throw new Error('Invalid transaction amount');\n}\nif (!itemRef?.value) {\n  throw new Error('ItemRef missing');\n}\n\n// --------------------------------\n// 5. SalesReceipt Payload\n// --------------------------------\nconst payload = {\n  Line: [\n    {\n      LineNum: 1,\n      Amount: amount,\n      Description: txn.description || '',\n      DetailType: 'SalesItemLineDetail',\n      SalesItemLineDetail: {\n        ItemRef: {\n          value: itemRef.value,\n          name: itemRef.name\n        },\n        Qty: 1,\n        UnitPrice: amount,\n        TaxCodeRef: { value: 'NON' }\n      }\n    }\n  ],\n  TxnDate: txn.date,\n  PrivateNote: `${txn.description} - Ref: ${txn.referenceNumber || 'N/A'}`,\n  CustomerRef: customerRef,\n  DepositToAccountRef: { value: '35' },\n  TotalAmt: amount\n};\n\nreturn { json: payload };\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2112,
        2368
      ],
      "id": "e54d40cc-5383-4bec-8fc7-c07ac25bc3b7",
      "name": "Build Salesreceipt Payload"
    },
    {
      "parameters": {
        "operation": "getAll",
        "filters": {
          "query": "=WHERE DisplayName = '{{ $json.itemRef.name }}'"
        }
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1568,
        2352
      ],
      "id": "1c01b90a-3d7a-4fb0-86db-237be3614acf",
      "name": "Get many customers",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "resource": "vendor",
        "operation": "create",
        "displayName": "={{ $('Loop Over Items').item.json.payee }}",
        "additionalFields": {
          "CompanyName": "={{ $('Loop Over Items').item.json.payee }}"
        }
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1168,
        2480
      ],
      "id": "812ab8f6-9107-4c04-afae-b273a391feb0",
      "name": "Create Vendor",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "1",
              "leftValue": "={{ $json.Id }}",
              "operator": {
                "type": "string",
                "operation": "empty"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        944,
        2544
      ],
      "id": "f4bc0b3d-1c71-4fa3-b382-29c0fd844b83",
      "name": "Vendor Exists?"
    },
    {
      "parameters": {
        "resource": "vendor",
        "operation": "getAll",
        "filters": {
          "query": "=WHERE DisplayName = '{{ $('Loop Over Items').item.json.payee }}'"
        }
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        752,
        2544
      ],
      "id": "5c950636-48e2-41ea-8e72-5740d54c484d",
      "name": "Find Vendor",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "url": "=https://sandbox-quickbooks.api.intuit.com/v3/company/company_id/query?minorversion=75",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "quickBooksOAuth2Api",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "query",
              "value": "SELECT Id, Name, AccountType, AccountSubType FROM Account"
            }
          ]
        },
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        592,
        2544
      ],
      "id": "95bcc639-1c4b-443f-8454-871777028d5a",
      "name": "Search Categories",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://sandbox-quickbooks.api.intuit.com/v3/company/company_id/item?minorversion=75",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "quickBooksOAuth2Api",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"Name\": \"{{ $json.itemsToCreate[0].name }}\",\n  \"Description\": \"{{ $json.itemsToCreate[0].description }}\",\n  \"Type\": \"{{ $json.itemsToCreate[0].type }}\",\n  \"IncomeAccountRef\": {\n    \"value\": \"{{ $json.itemsToCreate[0].incomeAccountRef }}\"\n  },\n  \"ExpenseAccountRef\": {\n    \"value\": \"{{ $json.itemsToCreate[0].expenseAccountRef }}\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1168,
        2256
      ],
      "id": "fd46c79a-e5b3-4341-9df7-3171adbaaa7c",
      "name": "Create Items",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// // --------------------------------\n// // 1. From previous decision node\n// // --------------------------------\n// const decision = $('Check Which Items to Create').first().json;\n\n// // --------------------------------\n// // 2. If item was created\n// // --------------------------------\n// if (decision.needsCreation) {\n//   const created = $('Create Items').first().json;\n//   const item = created.Item || created;\n\n//   return [{\n//     json: {\n//       itemRef: {\n//         value: item.Id,\n//         name: item.Name\n//       }\n//     }\n//   }];\n// }\n\n// // --------------------------------\n// // 3. If existing item was found\n// // --------------------------------\n// const key = decision.desiredItemName;\n// const existing = decision.existingItemMapping[key];\n\n// return [{\n//   json: {\n//     itemRef: {\n//       value: existing.id,\n//       name: existing.name\n//     }\n//   }\n// }];\n\n\n\n// --------------------------------\n// 1. Decision\n// --------------------------------\nconst decision = $('Check Which Items to Create').first().json;\n\n// --------------------------------\n// 2. If item was newly created\n// --------------------------------\nif (decision.needsCreation) {\n  const created = $('Create Items').first().json;\n  const item = created.Item || created;\n\n  return [{\n    json: {\n      itemRef: {\n        value: item.Id,\n        name: item.Name\n      }\n    }\n  }];\n}\n\n// --------------------------------\n// 3. If existing item was found\n// --------------------------------\nconst key = decision.desiredItemName;\nconst existing = decision.existingItemMapping[key];\n\n// 🔐 SAFETY CHECK\nif (!existing) {\n  throw new Error(`Item mapping missing for: ${key}`);\n}\n\nreturn [{\n  json: {\n    itemRef: {\n      value: existing.id,\n      name: existing.name\n    }\n  }\n}];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1392,
        2352
      ],
      "id": "e10e1255-1fc4-4a1f-92be-3555e98edb6a",
      "name": "Collect All Item Mappings"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "1",
              "leftValue": "={{ $json.needsCreation }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        944,
        2336
      ],
      "id": "2ffc100a-73c4-4fb4-be29-5f7ccd48a093",
      "name": "Need to Create Items?"
    },
    {
      "parameters": {
        "resource": "item",
        "operation": "getAll",
        "returnAll": true,
        "filters": {}
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        592,
        2336
      ],
      "id": "9c5d190e-748d-4dcd-b69f-3ff5ee386061",
      "name": "Get All QB Items",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// // --------------------------------\n// // 1. Inputs\n// // --------------------------------\n// const txn = $('Loop Over Items').item.json;\n// const qbItems = $input.all(); // from \"Get All QB Items\"\n\n// // --------------------------------\n// // 2. Normalize name logic\n// // --------------------------------\n// const normalize = (s) =>\n//   s.toLowerCase().replace(/[^a-z0-9]/g, ' ').trim();\n\n// // Item name derived from transaction\n// const desiredItemName = normalize(txn.payee || txn.description);\n\n// // --------------------------------\n// // 3. Build existing item lookup\n// // --------------------------------\n// const existingMap = {};\n\n// qbItems.forEach(n => {\n//   if (n.json?.Name && n.json?.Id) {\n//     existingMap[normalize(n.json.Name)] = {\n//       id: n.json.Id,\n//       name: n.json.Name\n//     };\n//   }\n// });\n\n// // --------------------------------\n// // 4. Decide create or reuse\n// // --------------------------------\n// const itemsToCreate = [];\n// const existingItemMapping = {};\n\n// if (existingMap[desiredItemName]) {\n//   existingItemMapping[desiredItemName] = existingMap[desiredItemName];\n// } else {\n//   itemsToCreate.push({\n//     name: txn.payee || 'Service',\n//     description: txn.description,\n//     type: 'Service',\n//     incomeAccountRef: '79',   // Income account\n//     expenseAccountRef: '80'   // Expense account\n//   });\n// }\n\n// return [{\n//   json: {\n//     desiredItemName,\n//     itemsToCreate,\n//     existingItemMapping,\n//     needsCreation: itemsToCreate.length > 0\n//   }\n// }];\n\n\n\n// --------------------------------\n// 1. Inputs\n// --------------------------------\nconst txn = $('Loop Over Items').first().json;\nconst qbItems = $input.all();\n\n// --------------------------------\n// 2. Utility\n// --------------------------------\nconst normalize = s =>\n  s.toLowerCase().replace(/[^a-z0-9]/g, ' ').trim();\n\nconst shortenName = (name) => {\n  if (!name) return 'Service';\n  return name\n    .replace(/services?/gi, '')\n    .replace(/limited|ltd|pvt|private/gi, '')\n    .trim();\n};\n\n// --------------------------------\n// 3. Desired item name\n// --------------------------------\nconst desiredItemName = normalize(shortenName(txn.payee || txn.description));\n\n// --------------------------------\n// 4. Existing item map\n// --------------------------------\nconst existingMap = {};\n\nqbItems.forEach(n => {\n  if (n.json?.Name && n.json?.Id) {\n    existingMap[normalize(n.json.Name)] = {\n      id: n.json.Id,\n      name: n.json.Name\n    };\n  }\n});\n\n// --------------------------------\n// 5. Decide create or reuse\n// --------------------------------\nconst itemsToCreate = [];\nconst existingItemMapping = {};\n\nif (existingMap[desiredItemName]) {\n  existingItemMapping[desiredItemName] = existingMap[desiredItemName];\n} else {\n  itemsToCreate.push({\n    name: shortenName(txn.payee),\n    description: txn.description,\n    type: 'Service',\n    incomeAccountRef: '79',\n    expenseAccountRef: '80'\n  });\n}\n\nreturn [{\n  json: {\n    desiredItemName,\n    itemsToCreate,\n    existingItemMapping,\n    needsCreation: itemsToCreate.length > 0\n  }\n}];\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        768,
        2336
      ],
      "id": "e8699b14-792a-44f4-9a73-3890e833b345",
      "name": "Check Which Items to Create"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.transactionType }}",
                    "rightValue": "credit",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "655116ac-b3b9-42d8-965e-7a6dc73d096b"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Credit"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "179cb4e7-89b9-4b98-9f95-109d6efedf20",
                    "leftValue": "={{ $json.transactionType }}",
                    "rightValue": "debit",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Debit"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.3,
      "position": [
        368,
        2400
      ],
      "id": "6f2d345c-c3e8-43df-91db-633caa5df247",
      "name": "Credit or Debit?"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "1",
              "leftValue": "={{ $json.Id }}",
              "operator": {
                "type": "string",
                "operation": "empty"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1728,
        2352
      ],
      "id": "2e0b7839-efd6-4717-a76d-ae7c7d943124",
      "name": "Customers Exists?1"
    },
    {
      "parameters": {
        "operation": "create",
        "displayName": "={{ $('Collect All Item Mappings').item.json.itemRef.name }}",
        "additionalFields": {
          "CompanyName": "={{ $('Collect All Item Mappings').item.json.itemRef.name }}"
        }
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1904,
        2272
      ],
      "id": "dd9aed93-a6cd-4063-b7e2-a32326e0e3ea",
      "name": "Create a Customer",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://sandbox-quickbooks.api.intuit.com/v3/company/company_id/purchase?minorversion=75",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "quickBooksOAuth2Api",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"TxnDate\": \"{{ $json.TxnDate }}\",\n  \"PrivateNote\": \"{{ $json.PrivateNote }}\",\n\n  \"EntityRef\": {\n    \"type\": \"Vendor\",\n    \"value\": \"{{ $json.EntityRef.value }}\",\n    \"name\": \"{{ $json.EntityRef.name }}\"\n  },\n\n  \"PaymentType\": \"{{ $json.PaymentType }}\",\n\n  \"AccountRef\": {\n    \"value\": \"35\",\n    \"name\": \"Checking\"\n  },\n\n  \"Line\": [\n    {\n      \"Amount\": {{ $json.Line[0].Amount }},\n      \"DetailType\": \"AccountBasedExpenseLineDetail\",\n      \"AccountBasedExpenseLineDetail\": {\n        \"AccountRef\": {\n          \"value\": \"{{ $json.Line[0].AccountBasedExpenseLineDetail.AccountRef.value }}\",\n          \"name\": \"{{ $json.Line[0].AccountBasedExpenseLineDetail.AccountRef.name }}\"\n        },\n        \"TaxCodeRef\": {\n          \"value\": \"NON\"\n        }\n      }\n    }\n  ]\n}\n",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1552,
        2560
      ],
      "id": "33069c05-78a9-45e3-b97e-a798ef1c1e14",
      "name": "Create QuickBooks Expense",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// // -----------------------------\n// // 1. Transaction\n// // -----------------------------\n// const txn = $('Loop Over Items').item.json;\n\n// // -----------------------------\n// // 2. Vendor (from Merge node)\n// // -----------------------------\n// const vendor = $input.first().json;\n\n// if (!vendor || !vendor.Id) {\n//   throw new Error(`Vendor not resolved for payee: ${txn.payee}`);\n// }\n\n// // -----------------------------\n// // 3. Build Expense Payload\n// // -----------------------------\n// const expensePayload = {\n//   TxnDate: txn.date,\n//   PrivateNote: `${txn.description} - Ref: ${txn.referenceNumber || 'N/A'}`,\n//   EntityRef: {\n//     type: \"Vendor\",\n//     value: vendor.Id,\n//     name: vendor.DisplayName || vendor.CompanyName\n//   },\n//   PaymentType: \"Cash\",\n//   TotalAmt: txn.amount,\n//   Line: [\n//     {\n//       Amount: txn.amount,\n//       DetailType: \"AccountBasedExpenseLineDetail\",\n//       AccountBasedExpenseLineDetail: {\n//         AccountRef: {\n//           value: \"35\",   // ✅ Bank Account (Checking)\n//           name: \"Checking\"\n//         },\n//         TaxCodeRef: {\n//           value: \"NON\"\n//         }\n//       }\n//     }\n//   ]\n// };\n\n// return { json: expensePayload };\n\n\n\n\n// -----------------------------\n// 1. Transaction\n// -----------------------------\nconst txn = $('Loop Over Items').item.json;\nconst description = (txn.description || '').toLowerCase();\n\n// -----------------------------\n// 2. Vendor (from Merge logic)\n// -----------------------------\nconst vendor = $input.first().json;\n\nif (!vendor || !vendor.Id) {\n  throw new Error(`Vendor not resolved for payee: ${txn.payee}`);\n}\n\n// -----------------------------\n// 3. Load Categories (Chart of Accounts)\n// -----------------------------\nconst categoryItems =\n  $items('Search Categories')[0]?.json?.QueryResponse?.Account || [];\n\nif (!categoryItems.length) {\n  throw new Error('No categories found from QuickBooks');\n}\n\n// Build lookup map: name -> account\nconst categoryMap = {};\nfor (const acc of categoryItems) {\n  if (acc.AccountType === 'Expense') {\n    categoryMap[acc.Name.toLowerCase()] = acc;\n  }\n}\n\n// -----------------------------\n// 4. Auto Category Mapping Logic\n// -----------------------------\nlet selectedCategory = null;\n\nif (description.includes('zelle') || description.includes('bank') || description.includes('charge')) {\n  selectedCategory = categoryMap['bank charges'];\n}\nelse if (description.includes('insurance')) {\n  selectedCategory = categoryMap['insurance expense'];\n}\nelse if (description.includes('ads') || description.includes('advertising')) {\n  selectedCategory = categoryMap['advertising'];\n}\nelse if (description.includes('vendor') || description.includes('service')) {\n  selectedCategory = categoryMap['professional fees'];\n}\n\n// Default fallback\nif (!selectedCategory) {\n  selectedCategory = categoryMap['services'];\n}\n\nif (!selectedCategory) {\n  throw new Error('No matching expense category found');\n}\n\n// -----------------------------\n// 5. Build Expense Payload (CORRECT)\n// -----------------------------\nconst expensePayload = {\n  TxnDate: txn.date,\n  PrivateNote: `${txn.description} - Ref: ${txn.referenceNumber || 'N/A'}`,\n  EntityRef: {\n    type: 'Vendor',\n    value: vendor.Id,\n    name: vendor.DisplayName || vendor.CompanyName\n  },\n  PaymentType: 'Cash',\n  TotalAmt: txn.amount,\n  Line: [\n    {\n      Amount: txn.amount,\n      DetailType: 'AccountBasedExpenseLineDetail',\n      AccountBasedExpenseLineDetail: {\n        AccountRef: {\n          value: selectedCategory.Id,\n          name: selectedCategory.Name\n        },\n        BillableStatus: 'NotBillable',\n        TaxCodeRef: {\n          value: 'NON'\n        }\n      }\n    }\n  ]\n};\n\nreturn { json: expensePayload };\n"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1376,
        2560
      ],
      "id": "d7698bd5-0ad1-474c-8659-2cdf23f3ad5e",
      "name": "Build Expense Payload"
    }
  ],
  "pinData": {},
  "connections": {
    "Extract PDF Text": {
      "main": [
        [
          {
            "node": "Transaction Extractor AI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Transaction Extractor AI": {
      "main": [
        [
          {
            "node": "Split Transactions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "JSON Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Transaction Extractor AI",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Create QuickBooks SalesReceipt": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Bank Statement Form": {
      "main": [
        [
          {
            "node": "Extract PDF Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Transaction Extractor AI",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Split Transactions": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [],
        [
          {
            "node": "Credit or Debit?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Salesreceipt Payload": {
      "main": [
        [
          {
            "node": "Create QuickBooks SalesReceipt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get many customers": {
      "main": [
        [
          {
            "node": "Customers Exists?1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Vendor": {
      "main": [
        [
          {
            "node": "Build Expense Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vendor Exists?": {
      "main": [
        [
          {
            "node": "Create Vendor",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Expense Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Vendor": {
      "main": [
        [
          {
            "node": "Vendor Exists?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Search Categories": {
      "main": [
        [
          {
            "node": "Find Vendor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Items": {
      "main": [
        [
          {
            "node": "Collect All Item Mappings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Need to Create Items?": {
      "main": [
        [
          {
            "node": "Create Items",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Collect All Item Mappings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get All QB Items": {
      "main": [
        [
          {
            "node": "Check Which Items to Create",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Which Items to Create": {
      "main": [
        [
          {
            "node": "Need to Create Items?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect All Item Mappings": {
      "main": [
        [
          {
            "node": "Get many customers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Credit or Debit?": {
      "main": [
        [
          {
            "node": "Get All QB Items",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Search Categories",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Customers Exists?1": {
      "main": [
        [
          {
            "node": "Create a Customer",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Salesreceipt Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a Customer": {
      "main": [
        [
          {
            "node": "Build Salesreceipt Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create QuickBooks Expense": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Expense Payload": {
      "main": [
        [
          {
            "node": "Create QuickBooks Expense",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "be861850-2ffa-4938-8fce-47e746ee69c3",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "f1c26778ec36097a9722a22c47c5e9c01f00b8862dadd0121ec118026a370fa6"
  },
  "id": "hvvZGCXID5luktp8",
  "tags": []
}