{
  "name": "Invoice Email to QuickBooks",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "filters": {
          "q": "subject:Invoice has:attachment"
        },
        "options": {
          "attachmentPrefix": "attachment_"
        }
      },
      "id": "gmail-trigger",
      "name": "Watch for Invoice Emails",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        220,
        300
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "YOUR_GMAIL_CREDENTIAL_ID",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "model": "gpt-4o-mini",
        "messages": {
          "values": [
            {
              "content": "You are an invoice data extraction assistant. Extract the following information from the invoice and return ONLY valid JSON:\n\n- vendor_name: The company or person who issued the invoice\n- invoice_number: The invoice/reference number\n- invoice_date: Date in YYYY-MM-DD format\n- due_date: Due date in YYYY-MM-DD format (if not found, use invoice_date + 30 days)\n- total_amount: Total amount as a number (no currency symbols)\n- currency: Three-letter currency code (USD, EUR, etc.)\n- line_items: Array of objects with description, quantity, unit_price, amount\n\nExample output:\n{\n  \"vendor_name\": \"Acme Corp\",\n  \"invoice_number\": \"INV-2024-001\",\n  \"invoice_date\": \"2024-01-15\",\n  \"due_date\": \"2024-02-14\",\n  \"total_amount\": 1250.00,\n  \"currency\": \"USD\",\n  \"line_items\": [\n    {\"description\": \"Consulting Services\", \"quantity\": 10, \"unit_price\": 125, \"amount\": 1250}\n  ]\n}"
            },
            {
              "content": "={{ $json.attachment_0 }}",
              "role": "user"
            }
          ]
        },
        "options": {
          "temperature": 0.1
        }
      },
      "id": "openai-extract",
      "name": "Extract Invoice Data",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        440,
        300
      ],
      "credentials": {
        "openAiApi": {
          "id": "YOUR_OPENAI_CREDENTIAL_ID",
          "name": "OpenAI account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Parse the OpenAI response to get clean JSON\nconst response = $input.first().json.message.content;\n\ntry {\n  const invoiceData = JSON.parse(response);\n  return [{ json: invoiceData }];\n} catch (e) {\n  // Try to extract JSON from markdown code blocks\n  const jsonMatch = response.match(/```json?\\n?([\\s\\S]*?)\\n?```/);\n  if (jsonMatch) {\n    return [{ json: JSON.parse(jsonMatch[1]) }];\n  }\n  throw new Error('Could not parse invoice data: ' + e.message);\n}"
      },
      "id": "parse-json",
      "name": "Parse JSON Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        300
      ]
    },
    {
      "parameters": {
        "resource": "vendor",
        "operation": "getAll",
        "filters": {
          "displayName": "={{ $json.vendor_name }}"
        },
        "options": {
          "maxResults": 5
        }
      },
      "id": "qb-find-vendor",
      "name": "Find Vendor in QuickBooks",
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        880,
        300
      ],
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "YOUR_QUICKBOOKS_CREDENTIAL_ID",
          "name": "QuickBooks account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "vendor-exists",
              "leftValue": "={{ $json.QueryResponse?.Vendor?.length }}",
              "rightValue": "0",
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "if-vendor-exists",
      "name": "Vendor Exists?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1100,
        300
      ]
    },
    {
      "parameters": {
        "resource": "vendor",
        "operation": "create",
        "displayName": "={{ $('Parse JSON Response').item.json.vendor_name }}"
      },
      "id": "qb-create-vendor",
      "name": "Create New Vendor",
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1320,
        420
      ],
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "YOUR_QUICKBOOKS_CREDENTIAL_ID",
          "name": "QuickBooks account"
        }
      }
    },
    {
      "parameters": {
        "resource": "bill",
        "operation": "create",
        "vendorRef": "={{ $('If Vendor Exists?').first().json.QueryResponse?.Vendor?.[0]?.Id ?? $('Create New Vendor').item.json.Vendor.Id }}",
        "additionalFields": {
          "docNumber": "={{ $('Parse JSON Response').item.json.invoice_number }}",
          "txnDate": "={{ $('Parse JSON Response').item.json.invoice_date }}",
          "dueDate": "={{ $('Parse JSON Response').item.json.due_date }}"
        },
        "Line": {
          "lineValues": [
            {
              "Amount": "={{ $('Parse JSON Response').item.json.total_amount }}",
              "DetailType": "AccountBasedExpenseLineDetail",
              "description": "={{ $('Parse JSON Response').item.json.line_items.map(i => i.description).join(', ') }}"
            }
          ]
        }
      },
      "id": "qb-create-bill",
      "name": "Create Bill in QuickBooks",
      "type": "n8n-nodes-base.quickbooks",
      "typeVersion": 1,
      "position": [
        1540,
        300
      ],
      "credentials": {
        "quickBooksOAuth2Api": {
          "id": "YOUR_QUICKBOOKS_CREDENTIAL_ID",
          "name": "QuickBooks account"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "status",
              "name": "status",
              "value": "success",
              "type": "string"
            },
            {
              "id": "vendor",
              "name": "vendor",
              "value": "={{ $('Parse JSON Response').item.json.vendor_name }}",
              "type": "string"
            },
            {
              "id": "invoice_number",
              "name": "invoice_number",
              "value": "={{ $('Parse JSON Response').item.json.invoice_number }}",
              "type": "string"
            },
            {
              "id": "amount",
              "name": "amount",
              "value": "={{ $('Parse JSON Response').item.json.total_amount }}",
              "type": "number"
            },
            {
              "id": "bill_id",
              "name": "bill_id",
              "value": "={{ $json.Bill.Id }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "set-output",
      "name": "Set Success Output",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1760,
        300
      ]
    }
  ],
  "connections": {
    "Watch for Invoice Emails": {
      "main": [
        [
          {
            "node": "Extract Invoice Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Invoice Data": {
      "main": [
        [
          {
            "node": "Parse JSON Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse JSON Response": {
      "main": [
        [
          {
            "node": "Find Vendor in QuickBooks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Vendor in QuickBooks": {
      "main": [
        [
          {
            "node": "Vendor Exists?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vendor Exists?": {
      "main": [
        [
          {
            "node": "Create Bill in QuickBooks",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create New Vendor",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create New Vendor": {
      "main": [
        [
          {
            "node": "Create Bill in QuickBooks",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Bill in QuickBooks": {
      "main": [
        [
          {
            "node": "Set Success Output",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "instanceId": "uzunu-automation-templates"
  },
  "pinData": {},
  "versionId": "1",
  "triggerCount": 1,
  "tags": [
    {
      "name": "invoicing",
      "id": "invoicing"
    },
    {
      "name": "quickbooks",
      "id": "quickbooks"
    },
    {
      "name": "email-automation",
      "id": "email-automation"
    }
  ]
}
