{
  "name": "Purchase Bill OCR to QuickBooks",
  "nodes": [
    {
      "parameters": {
        "fieldToSplitOut": "itemsToCreate",
        "options": {}
      },
      "type": "n8n-nodes-base.splitOut",
      "typeVersion": 1,
      "position": [
        880,
        656
      ],
      "id": "5cd45125-d01e-418a-903e-fe802450c7b0",
      "name": "Split Items to Create"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://sandbox-quickbooks.api.intuit.com/v3/company/{companyId}/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.name }}\",\n  \"Description\": \"{{ $json.description }}\",\n  \"Type\": \"{{ $json.type }}\",\n  \"IncomeAccountRef\": {\n    \"value\": \"{{ $json.incomeAccountRef }}\"\n  },\n  \"ExpenseAccountRef\": {\n    \"value\": \"{{ $json.expenseAccountRef }}\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1056,
        656
      ],
      "id": "2f269bbc-2b3e-4252-9ed2-98cccb705f4b",
      "name": "Create Items",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineAll",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        128,
        944
      ],
      "id": "589fd785-a6ef-4079-8444-fde9716ee498",
      "name": "Merge Item Creation Paths",
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "jsCode": "// Collect all item mappings from both existing and newly created items\nconst checkResult = $('Check Which Items to Create').first().json;\nconst itemMapping = { ...checkResult.existingItemMapping };\n\n// Add newly created items to mapping\ntry {\n  const createdItems = $('Create Items').all();\n  createdItems.forEach(node => {\n    const item = node.json;\n    // QuickBooks returns the item in an 'Item' wrapper\n    const itemData = item.Item || item;\n    if (itemData.Name && itemData.Id) {\n      itemMapping[itemData.Name] = itemData.Id;\n    }\n  });\n} catch (error) {\n  // No items were created, that's fine\n}\n\n// Get the extracted data\nconst extractedData = $('Prepare Items to Check').first().json.extractedData;\n\nreturn [{\n  json: {\n    extractedData: extractedData,\n    allItemMapping: itemMapping\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        368,
        944
      ],
      "id": "22b11174-8e95-4f2c-ae3f-19ed9ee6216f",
      "name": "Collect All Item Mappings"
    },
    {
      "parameters": {
        "resource": "vendor",
        "operation": "getAll",
        "filters": {
          "query": "=WHERE DisplayName = '{{ $json.extractedData.vendor.name }}'"
        }
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        608,
        944
      ],
      "id": "c9dd2fb9-3edf-4142-8f6e-85c722bfe491",
      "name": "Find 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": [
        832,
        944
      ],
      "id": "c935059e-8e3f-484c-990f-dd6efb7b1d79",
      "name": "Vendor Exists?"
    },
    {
      "parameters": {
        "resource": "vendor",
        "operation": "create",
        "displayName": "={{ $('Collect All Item Mappings').first().json.extractedData.vendor.name }}",
        "additionalFields": {
          "CompanyName": "={{ $('Collect All Item Mappings').first().json.extractedData.vendor.name }}",
          "PrimaryEmailAddr": "={{ $('Collect All Item Mappings').first().json.extractedData.vendor.email }}"
        }
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1088,
        896
      ],
      "id": "83018036-244e-4944-b9a4-1734791e1ede",
      "name": "Create Vendor",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://sandbox-quickbooks.api.intuit.com/v3/company/{companyId}/bill?minorversion=75",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "quickBooksOAuth2Api",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.billPayload) }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        -112,
        816
      ],
      "id": "162d31f7-2d18-492c-a7ff-cc301d6e1bcf",
      "name": "Create Bill ",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "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": [
        672,
        672
      ],
      "id": "38e3163c-9d7b-49d4-8bdd-edd09b753881",
      "name": "Need to Create Items?"
    },
    {
      "parameters": {
        "resource": "item",
        "operation": "getAll",
        "returnAll": true,
        "filters": {}
      },
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        272,
        672
      ],
      "id": "bf963af3-43dd-4bd9-b83d-5492e1bb0bb5",
      "name": "Get All QB Items",
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "rDZGGm1O6BX5zxkN",
          "name": "QuickBooks Online account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const extractedData = $input.first().json.output;\nconst lineItems = extractedData.line_items || [];\n\nconst itemsToCheck = lineItems\n  .filter(item => item.item_name && item.item_name.trim() !== '')\n  .map(item => ({\n    name: item.item_name,\n    description: item.description || item.item_name,\n    unitPrice: parseFloat(item.unit_price) || parseFloat(item.amount),\n    type: 'Service'\n  }));\n\nreturn [{\n  json: {\n    extractedData: extractedData,\n    itemsToCheck: itemsToCheck\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        912,
        320
      ],
      "id": "837035af-964f-4f85-933e-2eaaf3cfaae5",
      "name": "Prepare Items to Check"
    },
    {
      "parameters": {
        "text": "={{ $json.cleaned_text }}",
        "schemaType": "fromJson",
        "jsonSchemaExample": "{\n  \"invoice_number\": \"\",\n  \"invoice_date\": \"\",\n  \"due_date\": \"\",\n  \"vendor\": {\n    \"name\": \"\",\n    \"address\": \"\",\n    \"email\": \"\",\n    \"phone\": \"\"\n  },\n  \"line_items\": [\n    {\n      \"item_name\": \"\",\n      \"description\": \"\",\n      \"quantity\": 0,\n      \"unit_price\": 0,\n      \"amount\": 0\n    }\n  ],\n  \"subtotal\": 0,\n  \"tax\": 0,\n  \"total\": 0\n}",
        "options": {
          "systemPromptTemplate": "Extract invoice data accurately. Extract vendor info, line items with item names, quantities, unit prices, and amounts. Return numbers as numbers, not strings."
        }
      },
      "type": "@n8n/n8n-nodes-langchain.informationExtractor",
      "typeVersion": 1.2,
      "position": [
        592,
        320
      ],
      "id": "7ba22fd0-5939-4de6-8723-c6f1e6dab786",
      "name": "Extract Invoice Data"
    },
    {
      "parameters": {
        "jsCode": "const text = $json[\"text\"] || '';\nlet data = '';\n\nif (Object.keys($binary || {}).length) {\n  data = $binary.data ? Buffer.from($binary.data.data).toString('utf8') : '';\n}\n\nconst cleaned = (text || data || '').replace(/\\r\\n/g,'\\n').replace(/\\n+/g,'\\n').trim();\n\nreturn [{ \n  json: { \n    cleaned_text: cleaned \n  } \n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        432,
        320
      ],
      "id": "3a243c48-61de-437a-a07a-cd0dada04381",
      "name": "Clean Text"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        64,
        448
      ],
      "id": "b5f7bd64-6983-42be-867f-1d3806cba6f1",
      "name": "Loop Over Invoices"
    },
    {
      "parameters": {
        "jsCode": "const item = $input.first();\nconst binaries = item.binary || {};\nconst output = [];\n\nfor (const key of Object.keys(binaries)) {\n  output.push({\n    json: { \n      file: key,\n      filename: key,\n      mimeType: binaries[key].mimeType,\n      fileSize: binaries[key].fileSize\n    },\n    binary: {\n      data: binaries[key]\n    }\n  });\n}\n\nreturn output;"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -128,
        448
      ],
      "id": "01b02350-0429-45b6-a7c9-1090d78b5f4f",
      "name": "Convert to Separate Items"
    },
    {
      "parameters": {
        "operation": "pdf",
        "options": {}
      },
      "type": "n8n-nodes-base.extractFromFile",
      "typeVersion": 1.1,
      "position": [
        272,
        320
      ],
      "id": "ed082d33-cd5d-4942-9063-ee9b3a3043b3",
      "name": "Extract from PDF"
    },
    {
      "parameters": {
        "jsCode": "const itemsToCheck = $('Prepare Items to Check').first().json.itemsToCheck;\nconst existingItems = $input.all();\n\nconst existingItemMap = {};\nexistingItems.forEach(itemNode => {\n  const item = itemNode.json;\n  if (item.Name) {\n    existingItemMap[item.Name.toLowerCase()] = {\n      id: item.Id,\n      name: item.Name\n    };\n  }\n});\n\nconst itemsToCreate = [];\nconst itemMapping = {};\n\nitemsToCheck.forEach(item => {\n  const itemNameLower = item.name.toLowerCase();\n  \n  if (existingItemMap[itemNameLower]) {\n    itemMapping[item.name] = existingItemMap[itemNameLower].id;\n  } else {\n    itemsToCreate.push({\n      name: item.name,\n      description: item.description,\n      type: item.type,\n      incomeAccountRef: \"79\",\n      expenseAccountRef: \"80\"\n    });\n  }\n});\n\nreturn [{\n  json: {\n    itemsToCreate: itemsToCreate,\n    existingItemMapping: itemMapping,\n    needsCreation: itemsToCreate.length > 0\n  }\n}];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        672
      ],
      "id": "bb39b660-589a-4534-9d27-8d84f3b473f7",
      "name": "Check Which Items to Create"
    },
    {
      "parameters": {
        "jsCode": "const extractedData = $('Collect All Item Mappings').first().json.extractedData;\nconst itemMapping = $('Collect All Item Mappings').first().json.allItemMapping;\n\n// Get vendor info\nlet vendorId, vendorName;\n\ntry {\n  const vendorNode = $('Create Vendor').first();\n  vendorId = vendorNode.json.Id;\n  vendorName = vendorNode.json.DisplayName;\n} catch {\n  const vendorNode = $('Find Vendor').first();\n  vendorId = vendorNode.json.Id;\n  vendorName = vendorNode.json.DisplayName;\n}\n\nif (!vendorId) {\n  throw new Error(`Vendor not found: ${extractedData.vendor.name}`);\n}\n\n// Build line items\nconst lineItems = [];\n\nextractedData.line_items.forEach((item, index) => {\n  // Try exact match first, then case-insensitive match\n  let itemId = itemMapping[item.item_name];\n  \n  if (!itemId) {\n    // Try case-insensitive lookup\n    const itemNameLower = item.item_name.toLowerCase();\n    for (const [key, value] of Object.entries(itemMapping)) {\n      if (key.toLowerCase() === itemNameLower) {\n        itemId = value;\n        break;\n      }\n    }\n  }\n  \n  if (!itemId) {\n    throw new Error(`Item not found: ${item.item_name}`);\n  }\n  \n  const quantity = parseFloat(item.quantity) || 1;\n  const unitPrice = parseFloat(item.unit_price) || (parseFloat(item.amount) / quantity);\n  \n  lineItems.push({\n    LineNum: index + 1,\n    Description: item.description || item.item_name,\n    Amount: parseFloat(item.amount),\n    DetailType: \"ItemBasedExpenseLineDetail\",\n    ItemBasedExpenseLineDetail: {\n      ItemRef: {\n        value: itemId,\n        name: item.item_name\n      },\n      Qty: quantity,\n      UnitPrice: unitPrice,\n      BillableStatus: \"NotBillable\",\n      TaxCodeRef: {\n        value: \"NON\"\n      }\n    }\n  });\n});\n\n// Add tax if exists\nif (extractedData.tax && parseFloat(extractedData.tax) > 0) {\n  lineItems.push({\n    LineNum: lineItems.length + 1,\n    Description: 'Tax',\n    Amount: parseFloat(extractedData.tax),\n    DetailType: 'AccountBasedExpenseLineDetail',\n    AccountBasedExpenseLineDetail: {\n      AccountRef: {\n        value: '1'\n      },\n      BillableStatus: 'NotBillable',\n      TaxCodeRef: {\n        value: 'NON'\n      }\n    }\n  });\n}\n\n// Parse dates\nlet billDate = extractedData.invoice_date;\nlet dueDate = extractedData.due_date;\n\nif (billDate && !billDate.match(/^\\d{4}-\\d{2}-\\d{2}$/)) {\n  billDate = new Date(billDate).toISOString().split('T')[0];\n}\n\nif (dueDate && !dueDate.match(/^\\d{4}-\\d{2}-\\d{2}$/)) {\n  dueDate = new Date(dueDate).toISOString().split('T')[0];\n}\n\n// Build bill payload\nconst billPayload = {\n  Line: lineItems,\n  VendorRef: {\n    value: vendorId,\n    name: vendorName\n  },\n  DocNumber: extractedData.invoice_number,\n  TxnDate: billDate,\n  DueDate: dueDate || billDate\n};\n\nif (extractedData.vendor?.address) {\n  const addressLines = extractedData.vendor.address.split('\\n');\n  billPayload.VendorAddr = {\n    Line1: addressLines[0] || '',\n    Line2: addressLines[1] || '',\n    Line3: addressLines[2] || ''\n  };\n}\n\nreturn {\n  json: {\n    billPayload: billPayload,\n    summary: {\n      vendor: vendorName,\n      billNumber: extractedData.invoice_number,\n      total: extractedData.total,\n      lineItems: lineItems.length\n    }\n  }\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1216,
        1056
      ],
      "id": "59868c19-b1fd-478b-802c-d18cf81a7f6d",
      "name": "Build Bill Payload"
    },
    {
      "parameters": {
        "model": "openai/gpt-oss-20b:free",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "typeVersion": 1,
      "position": [
        592,
        544
      ],
      "id": "62b429f9-fe5d-43f8-8127-16e9a911de28",
      "name": "OpenRouter Chat Model",
      "credentials": {
        "openRouterApi": {
          "id": "XDH1ME5qL4duPuQc",
          "name": "OpenRouter account"
        }
      }
    },
    {
      "parameters": {
        "formTitle": "Invoice Parser + QuickBooks Bill Creator",
        "formFields": {
          "values": [
            {
              "fieldLabel": "Invoice File",
              "fieldType": "file",
              "acceptFileTypes": ".pdf",
              "requiredField": true
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.formTrigger",
      "typeVersion": 2.3,
      "position": [
        -320,
        448
      ],
      "id": "f54154a7-d3e7-41c7-b545-68f0bb0194ca",
      "name": "On bill submission",
      "webhookId": "d28cfa82-69c8-42da-a0b5-1a23131f918e"
    }
  ],
  "pinData": {},
  "connections": {
    "Split Items to Create": {
      "main": [
        [
          {
            "node": "Create Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Items": {
      "main": [
        [
          {
            "node": "Merge Item Creation Paths",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Item Creation Paths": {
      "main": [
        [
          {
            "node": "Collect All Item Mappings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Collect All Item Mappings": {
      "main": [
        [
          {
            "node": "Find Vendor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Vendor": {
      "main": [
        [
          {
            "node": "Vendor Exists?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vendor Exists?": {
      "main": [
        [
          {
            "node": "Create Vendor",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Build Bill Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Vendor": {
      "main": [
        [
          {
            "node": "Build Bill Payload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Bill ": {
      "main": [
        [
          {
            "node": "Loop Over Invoices",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Need to Create Items?": {
      "main": [
        [
          {
            "node": "Split Items to Create",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Merge Item Creation Paths",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Get All QB Items": {
      "main": [
        [
          {
            "node": "Check Which Items to Create",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Items to Check": {
      "main": [
        [
          {
            "node": "Get All QB Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Invoice Data": {
      "main": [
        [
          {
            "node": "Prepare Items to Check",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean Text": {
      "main": [
        [
          {
            "node": "Extract Invoice Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Invoices": {
      "main": [
        [],
        [
          {
            "node": "Extract from PDF",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Convert to Separate Items": {
      "main": [
        [
          {
            "node": "Loop Over Invoices",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract from PDF": {
      "main": [
        [
          {
            "node": "Clean Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Which Items to Create": {
      "main": [
        [
          {
            "node": "Need to Create Items?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Bill Payload": {
      "main": [
        [
          {
            "node": "Create Bill ",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Extract Invoice Data",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "On bill submission": {
      "main": [
        [
          {
            "node": "Convert to Separate Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "3766c499-8ef8-49e2-9e40-5be31cfe56d3",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "f1c26778ec36097a9722a22c47c5e9c01f00b8862dadd0121ec118026a370fa6"
  },
  "id": "4UZIu0ZO2pIwBMDJ",
  "tags": []
}