{
  "name": "Expense Receipt to Spreadsheet",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "filters": {
          "q": "to:expenses@yourdomain.com OR subject:receipt OR subject:expense"
        },
        "options": {
          "attachmentPrefix": "receipt_"
        }
      },
      "id": "gmail-trigger",
      "name": "Watch for Receipt Emails",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        220,
        300
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "YOUR_GMAIL_CREDENTIAL_ID",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "email_body",
              "name": "email_body",
              "value": "={{ $json.textPlain || $json.snippet || '' }}",
              "type": "string"
            },
            {
              "id": "email_subject",
              "name": "email_subject",
              "value": "={{ $json.subject }}",
              "type": "string"
            },
            {
              "id": "email_from",
              "name": "email_from",
              "value": "={{ $json.from }}",
              "type": "string"
            },
            {
              "id": "email_date",
              "name": "email_date",
              "value": "={{ $json.date }}",
              "type": "string"
            },
            {
              "id": "message_id",
              "name": "message_id",
              "value": "={{ $json.id }}",
              "type": "string"
            },
            {
              "id": "has_attachment",
              "name": "has_attachment",
              "value": "={{ $json.receipt_0 ? 'Yes' : 'No' }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "set-email-data",
      "name": "Extract Email Data",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        440,
        300
      ]
    },
    {
      "parameters": {
        "model": "gpt-4o-mini",
        "messages": {
          "values": [
            {
              "content": "You are an expense receipt data extraction assistant. Extract the following information from this receipt email and return ONLY valid JSON:\n\n- vendor_name: The business or merchant name (e.g., 'Office Depot', 'Shell Gas Station', 'Amazon')\n- expense_date: Date of the purchase in YYYY-MM-DD format\n- total_amount: Total amount as a number (no currency symbols, no commas)\n- currency: Three-letter currency code (USD, EUR, etc.) - default to USD if unclear\n- category: One of: 'Office Supplies', 'Travel', 'Meals', 'Software', 'Equipment', 'Fuel', 'Utilities', 'Professional Services', 'Marketing', 'Other'\n- description: Brief description of what was purchased (max 100 chars)\n- payment_method: 'Credit Card', 'Debit Card', 'Cash', 'PayPal', 'Other', or 'Unknown'\n\nIf you cannot determine a field with confidence, use these defaults:\n- vendor_name: Extract from sender email if no clear vendor\n- expense_date: Use today's date\n- category: 'Other'\n- payment_method: 'Unknown'\n\nExample output:\n{\n  \"vendor_name\": \"Staples\",\n  \"expense_date\": \"2026-01-15\",\n  \"total_amount\": 47.82,\n  \"currency\": \"USD\",\n  \"category\": \"Office Supplies\",\n  \"description\": \"Printer paper and ink cartridges\",\n  \"payment_method\": \"Credit Card\"\n}"
            },
            {
              "content": "Subject: {{ $json.email_subject }}\nFrom: {{ $json.email_from }}\nDate: {{ $json.email_date }}\n\nEmail Body:\n{{ $json.email_body }}",
              "role": "user"
            }
          ]
        },
        "options": {
          "temperature": 0.1
        }
      },
      "id": "openai-extract",
      "name": "Extract Receipt Data with AI",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        660,
        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;\nconst emailData = $('Extract Email Data').first().json;\n\ntry {\n  let expenseData;\n  \n  // Try to parse JSON directly\n  try {\n    expenseData = JSON.parse(response);\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      expenseData = JSON.parse(jsonMatch[1]);\n    } else {\n      throw new Error('Could not find valid JSON in response');\n    }\n  }\n  \n  // Add metadata\n  expenseData.source_email = emailData.email_from;\n  expenseData.email_subject = emailData.email_subject;\n  expenseData.message_id = emailData.message_id;\n  expenseData.has_attachment = emailData.has_attachment;\n  expenseData.logged_at = new Date().toISOString();\n  \n  return [{ json: expenseData }];\n} catch (e) {\n  // Return error row for manual review\n  return [{ \n    json: {\n      vendor_name: 'PARSE ERROR - Manual Review',\n      expense_date: new Date().toISOString().split('T')[0],\n      total_amount: 0,\n      currency: 'USD',\n      category: 'Other',\n      description: 'AI could not parse this receipt - please review manually',\n      payment_method: 'Unknown',\n      source_email: emailData.email_from,\n      email_subject: emailData.email_subject,\n      message_id: emailData.message_id,\n      has_attachment: emailData.has_attachment,\n      logged_at: new Date().toISOString(),\n      error: e.message\n    }\n  }];\n}"
      },
      "id": "parse-json",
      "name": "Parse AI Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        300
      ]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "value": "YOUR_SPREADSHEET_ID",
          "mode": "id"
        },
        "sheetName": {
          "__rl": true,
          "value": "Expenses",
          "mode": "name"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "Date": "={{ $json.expense_date }}",
            "Vendor": "={{ $json.vendor_name }}",
            "Amount": "={{ $json.total_amount }}",
            "Currency": "={{ $json.currency }}",
            "Category": "={{ $json.category }}",
            "Description": "={{ $json.description }}",
            "Payment Method": "={{ $json.payment_method }}",
            "Source Email": "={{ $json.source_email }}",
            "Has Receipt": "={{ $json.has_attachment }}",
            "Logged At": "={{ $json.logged_at }}"
          }
        },
        "options": {}
      },
      "id": "sheets-append",
      "name": "Add to Expense Spreadsheet",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1100,
        300
      ],
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "YOUR_GOOGLE_SHEETS_CREDENTIAL_ID",
          "name": "Google Sheets account"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "status",
              "name": "status",
              "value": "success",
              "type": "string"
            },
            {
              "id": "vendor",
              "name": "vendor",
              "value": "={{ $('Parse AI Response').item.json.vendor_name }}",
              "type": "string"
            },
            {
              "id": "amount",
              "name": "amount",
              "value": "={{ $('Parse AI Response').item.json.total_amount }}",
              "type": "number"
            },
            {
              "id": "category",
              "name": "category",
              "value": "={{ $('Parse AI Response').item.json.category }}",
              "type": "string"
            },
            {
              "id": "logged_at",
              "name": "logged_at",
              "value": "={{ $('Parse AI Response').item.json.logged_at }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "set-output",
      "name": "Set Success Output",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1320,
        300
      ]
    }
  ],
  "connections": {
    "Watch for Receipt Emails": {
      "main": [
        [
          {
            "node": "Extract Email Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Email Data": {
      "main": [
        [
          {
            "node": "Extract Receipt Data with AI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Receipt Data with AI": {
      "main": [
        [
          {
            "node": "Parse AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse AI Response": {
      "main": [
        [
          {
            "node": "Add to Expense Spreadsheet",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add to Expense Spreadsheet": {
      "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": "data-sync",
      "id": "data-sync"
    },
    {
      "name": "expense-tracking",
      "id": "expense-tracking"
    }
  ]
}
