{
  "name": "Expense Invoice Reader (template)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 15
            }
          ]
        }
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000001",
      "name": "Every 15 Minutes",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Nothing to paste here. Connect the three credentials and run once:\n// the first run creates the folder \"Expense Reader\" in your Drive (Inbox, Processed, Needs Review)\n// and the sheet \"Expense Log\" inside it. Drop receipt photos or PDFs into Inbox.\nreturn [{ json: {\n  folderName: 'Expense Reader',\n  sheetName: 'Expense Log',\n  model: 'gemini-2.5-flash',\n  maxFilesPerRun: 10,\n  minConfidence: 0.7, // below this, a person checks it\n} }];"
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000002",
      "name": "Config",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "GET",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"name = '\" + $json.folderName + \"' and mimeType = 'application/vnd.google-apps.folder' and trashed = false\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name)"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            },
            {
              "name": "includeItemsFromAllDrives",
              "value": "true"
            }
          ]
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000003",
      "name": "Find Setup Folder",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "c-setup",
              "leftValue": "={{ ($json.files || []).length > 0 }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000004",
      "name": "Already Set Up?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        660,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "POST",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ name: $('Config').first().json.folderName, mimeType: 'application/vnd.google-apps.folder' }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000005",
      "name": "Create Setup Folder",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        880,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "POST",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ name: 'Inbox', mimeType: 'application/vnd.google-apps.folder', parents: [$('Create Setup Folder').first().json.id] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000006",
      "name": "Create Inbox",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "POST",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ name: 'Processed', mimeType: 'application/vnd.google-apps.folder', parents: [$('Create Setup Folder').first().json.id] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000007",
      "name": "Create Processed",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1320,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "POST",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ name: 'Needs Review', mimeType: 'application/vnd.google-apps.folder', parents: [$('Create Setup Folder').first().json.id] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000008",
      "name": "Create Needs Review",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1540,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "POST",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "fields",
              "value": "id,name"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ name: $('Config').first().json.sheetName, mimeType: 'application/vnd.google-apps.spreadsheet', parents: [$('Create Setup Folder').first().json.id] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000009",
      "name": "Create Expense Log",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1760,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "method": "POST",
        "url": "=https://sheets.googleapis.com/v4/spreadsheets/{{ $json.id }}:batchUpdate",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ requests: [\n    { updateSheetProperties: { properties: { sheetId: 0, title: 'Invoices', gridProperties: { frozenRowCount: 1 } }, fields: 'title,gridProperties.frozenRowCount' } },\n    { addSheet: { properties: { title: 'Items', gridProperties: { frozenRowCount: 1 } } } }] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000010",
      "name": "Add Tabs",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1980,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "method": "POST",
        "url": "=https://sheets.googleapis.com/v4/spreadsheets/{{ $('Create Expense Log').first().json.id }}/values:batchUpdate",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ valueInputOption: 'RAW', data: [\n    { range: 'Invoices!A1', values: [[\"Invoice ID\",\"Expense Date\",\"Vendor\",\"Category\",\"Total\",\"Discount\",\"Tax\",\"Payment Method\",\"Description\",\"Status\",\"Review Reason\",\"File Link\",\"File Name\",\"Processed At\"]] }, { range: 'Items!A1', values: [[\"Invoice ID\",\"Expense Date\",\"Vendor\",\"Item\",\"Qty\",\"Unit Price\",\"Gross\",\"Discount\",\"Net\",\"Status\"]] }] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000011",
      "name": "Write Headers",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2200,
        560
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "jsCode": "const p = $('Create Setup Folder').first().json;\nreturn [{ json: { message: 'Setup done. Drop receipts into \"' + p.name + ' / Inbox\" in your Drive. The next run reads them.', folder: 'https://drive.google.com/drive/folders/' + p.id } }];"
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000012",
      "name": "Setup Done",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2420,
        560
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "GET",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"'\" + $json.files[0].id + \"' in parents and trashed = false\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name,mimeType)"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            },
            {
              "name": "includeItemsFromAllDrives",
              "value": "true"
            }
          ]
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000013",
      "name": "List Setup Folder",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        880,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "jsCode": "// Finds the Inbox, Processed and Needs Review folders and the sheet inside the setup folder.\nconst cfg = $('Config').first().json;\nconst parentId = $('Find Setup Folder').first().json.files[0].id;\nconst files = $input.first().json.files || [];\nconst find = (name, mime) => (files.find(f => f.name === name && f.mimeType === mime) || {}).id;\nconst FOLDER = 'application/vnd.google-apps.folder', SHEET = 'application/vnd.google-apps.spreadsheet';\nconst ids = { parentId, inboxId: find('Inbox', FOLDER), processedId: find('Processed', FOLDER), reviewId: find('Needs Review', FOLDER), sheetId: find(cfg.sheetName, SHEET) };\nconst missing = Object.entries({ Inbox: ids.inboxId, Processed: ids.processedId, 'Needs Review': ids.reviewId, [cfg.sheetName]: ids.sheetId }).filter(([, v]) => !v).map(([k]) => k);\nif (missing.length) throw new Error('The \"' + cfg.folderName + '\" folder is missing: ' + missing.join(', ') + '. Restore it from Drive trash, or delete the whole folder and run again to recreate it.');\nreturn [{ json: { ...ids, maxFilesPerRun: cfg.maxFilesPerRun } }];"
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000014",
      "name": "Locate Setup",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "GET",
        "url": "https://www.googleapis.com/drive/v3/files",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "q",
              "value": "={{ \"'\" + $json.inboxId + \"' in parents and trashed = false and mimeType != 'application/vnd.google-apps.folder'\" }}"
            },
            {
              "name": "fields",
              "value": "files(id,name,mimeType,createdTime,webViewLink)"
            },
            {
              "name": "orderBy",
              "value": "createdTime"
            },
            {
              "name": "pageSize",
              "value": "={{ $json.maxFilesPerRun }}"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            },
            {
              "name": "includeItemsFromAllDrives",
              "value": "true"
            }
          ]
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000015",
      "name": "List Inbox Files",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1320,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "jsCode": "// One item per new file in the inbox. No files, nothing else runs.\nreturn ($input.first().json.files || []).map(f => ({ json: f }));"
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000016",
      "name": "Split Files",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1540,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "GET",
        "url": "=https://www.googleapis.com/drive/v3/files/{{ $json.id }}",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "alt",
              "value": "media"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "options": {
          "response": {
            "response": {
              "responseFormat": "file",
              "outputPropertyName": "data"
            }
          }
        }
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000017",
      "name": "Download File",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1760,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "jsCode": "// Sends each file to Gemini with a strict JSON schema, so the answer is always the same shape.\nconst SUPPORTED = ['image/jpeg', 'image/png', 'image/webp', 'image/heic', 'image/heif', 'application/pdf'];\nconst PROMPT = \"You are an accounts assistant. Read the attached expense document (receipt, nota, invoice or payment screenshot) and extract its details.\\nRules:\\n- Return plain numbers with no separators. Read the local number format: in Indonesian receipts \\\"14.700\\\" = 14700 and \\\"1.250.000\\\" = 1250000.\\n- total = the final amount actually paid. discount = total discount as a positive number. tax = tax amount if printed, else null.\\n- expense_date as YYYY-MM-DD. If no date is visible, use null.\\n- vendor = the store or recipient name. description = one short line summarising what was bought or paid.\\n- items: list EVERY line item separately, in printed order. Never merge or skip items. amount = the line amount before discount; a discount printed under an item belongs to that item.\\n- Lines like Subtotal, Total, Tax, Change or member points are not items.\\n- For a transfer or payment screenshot, create one item from the transfer note.\\n- category: the category with the largest share of the total, from the allowed list.\\n- confidence: 0 to 1, how sure you are that the date AND total are correct. Lower it for blurry or handwritten values.\\n- notes: anything illegible, guessed or suspicious. Use null for anything not present. Never invent values.\";\nconst SCHEMA = {\"type\":\"OBJECT\",\"properties\":{\"is_expense_document\":{\"type\":\"BOOLEAN\"},\"document_type\":{\"type\":\"STRING\",\"enum\":[\"Receipt\",\"Transfer\",\"Nota\",\"Invoice\",\"Other\"]},\"expense_date\":{\"type\":\"STRING\",\"nullable\":true},\"vendor\":{\"type\":\"STRING\",\"nullable\":true},\"description\":{\"type\":\"STRING\",\"nullable\":true},\"payment_method\":{\"type\":\"STRING\",\"nullable\":true},\"total\":{\"type\":\"NUMBER\",\"nullable\":true},\"discount\":{\"type\":\"NUMBER\",\"nullable\":true},\"tax\":{\"type\":\"NUMBER\",\"nullable\":true},\"category\":{\"type\":\"STRING\",\"enum\":[\"Pantry & Refreshments\",\"Meals & Catering\",\"Cleaning & Toiletries\",\"Office Supplies\",\"Printing & Courier\",\"Transport, Fuel & Parking\",\"Travel\",\"Utilities & Internet\",\"Repairs & Maintenance\",\"Equipment & Furniture\",\"Outsourced Services\",\"Employee Welfare\",\"Other\"]},\"items\":{\"type\":\"ARRAY\",\"items\":{\"type\":\"OBJECT\",\"properties\":{\"name\":{\"type\":\"STRING\"},\"qty\":{\"type\":\"NUMBER\",\"nullable\":true},\"unit_price\":{\"type\":\"NUMBER\",\"nullable\":true},\"amount\":{\"type\":\"NUMBER\"},\"discount\":{\"type\":\"NUMBER\",\"nullable\":true}},\"required\":[\"name\",\"amount\"]}},\"confidence\":{\"type\":\"NUMBER\"},\"notes\":{\"type\":\"STRING\",\"nullable\":true}},\"required\":[\"is_expense_document\",\"document_type\",\"expense_date\",\"vendor\",\"total\",\"category\",\"items\",\"confidence\"]};\nconst files = $('Split Files').all();\nconst out = [];\nfor (let i = 0; i < $input.all().length; i++) {\n  const file = files[i].json;\n  let body = null, buildError = '';\n  try {\n    if (!SUPPORTED.includes(file.mimeType)) throw new Error('unsupported file type ' + file.mimeType);\n    const buf = await this.helpers.getBinaryDataBuffer(i, 'data');\n    if (!buf || buf.length < 100) throw new Error('the file is empty');\n    body = {\n      contents: [{ role: 'user', parts: [\n        { text: PROMPT + '\\n\\nFile name: ' + file.name },\n        { inline_data: { mime_type: file.mimeType, data: buf.toString('base64') } },\n      ] }],\n      generationConfig: { temperature: 0, responseMimeType: 'application/json', responseSchema: SCHEMA },\n    };\n  } catch (e) { buildError = 'Could not read the file: ' + e.message; }\n  // Gemini needs a body even when we already know the file is unreadable; the check step catches it.\n  out.push({ json: { body: body || { contents: [{ role: 'user', parts: [{ text: 'Reply with {}' }] }] }, buildError }, pairedItem: { item: i } });\n}\nreturn out;"
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000018",
      "name": "Build Gemini Request",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1980,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googlePalmApi",
        "method": "POST",
        "url": "=https://generativelanguage.googleapis.com/v1beta/models/{{ $('Config').first().json.model }}:generateContent",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify($json.body) }}",
        "options": {
          "timeout": 120000,
          "batching": {
            "batch": {
              "batchSize": 1,
              "batchInterval": 4000
            }
          }
        }
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000019",
      "name": "Gemini Reads Receipt",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2200,
        300
      ],
      "onError": "continueRegularOutput",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "jsCode": "// The checks: anything doubtful goes to a person instead of being guessed.\nconst cfg = $('Config').first().json;\nconst files = $('Split Files').all(), built = $('Build Gemini Request').all();\nconst now = new Date().toISOString().replace('T', ' ').slice(0, 16);\nconst out = [];\n$input.all().forEach((it, i) => {\n  const file = files[i].json, buildError = built[i].json.buildError;\n  let d = {}, reasons = [], retryLater = false;\n  const errDetail = it.json.error ? JSON.stringify(it.json.error) : '';\n  if (buildError) reasons.push(buildError);\n  else if (errDetail && /quota|too many requests|429|RESOURCE_EXHAUSTED|unavailable|overloaded|50[0-4]|timeout|timed out|ECONN|socket/i.test(errDetail)) {\n    retryLater = true; // AI quota or outage: leave the file in the inbox, the next run tries again\n  } else {\n    try { d = JSON.parse(it.json.candidates[0].content.parts[0].text); }\n    catch (e) { reasons.push('AI reply could not be read' + (errDetail ? ': ' + (it.json.error.message || errDetail).slice(0, 200) : '')); }\n  }\n  const items = Array.isArray(d.items) ? d.items : [];\n  if (!buildError && Object.keys(d).length) {\n    if (d.is_expense_document === false) reasons.push('Not an expense document');\n    if (!d.expense_date) reasons.push('No date found');\n    if (d.total == null) reasons.push('Total is not readable');\n    if ((d.confidence ?? 0) < cfg.minConfidence) reasons.push('Low confidence (' + Math.round((d.confidence ?? 0) * 100) + '%)');\n    const net = items.reduce((s, x) => s + (x.amount || 0) - (x.discount || 0), 0);\n    if (d.total != null && items.length && Math.abs(net - d.total) > Math.max(1000, d.total * 0.01)) reasons.push('Items add up to ' + net + ', not the total ' + d.total);\n  }\n  const status = reasons.length ? 'Needs Review' : 'OK';\n  const day = (d.expense_date || now.slice(0, 10)).replace(/-/g, '').slice(2);\n  const invoiceId = 'EXP-' + day + '-' + file.id.slice(-5);\n  const invoiceRow = [invoiceId, d.expense_date || '', d.vendor || '', d.category || '', d.total ?? '', d.discount ?? '', d.tax ?? '',\n    d.payment_method || '', d.description || '', status, reasons.join('; '), file.webViewLink || '', file.name, now];\n  const itemRows = (items.length ? items : [{ name: d.description || 'See document', amount: d.total ?? '' }]).map(x => [\n    invoiceId, d.expense_date || '', d.vendor || '', x.name, x.qty ?? '', x.unit_price ?? '', x.amount ?? '', x.discount ?? '',\n    x.amount === '' ? '' : (x.amount || 0) - (x.discount || 0), status]);\n  out.push({ json: { retryLater, fileId: file.id, fileName: file.name, invoiceId, status, reasons, invoiceRow, itemRows, notes: d.notes || '' }, pairedItem: { item: i } });\n});\nreturn out;"
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000020",
      "name": "Check Result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        2420,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "c0",
              "leftValue": "={{ !$json.retryLater }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000021",
      "name": "Got an AI Answer?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        2640,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "method": "POST",
        "url": "=https://sheets.googleapis.com/v4/spreadsheets/{{ $('Locate Setup').first().json.sheetId }}/values/Invoices!A1:append",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "valueInputOption",
              "value": "USER_ENTERED"
            },
            {
              "name": "insertDataOption",
              "value": "INSERT_ROWS"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ values: [$json.invoiceRow] }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000022",
      "name": "Add Invoice Row",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2860,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleSheetsOAuth2Api",
        "method": "POST",
        "url": "=https://sheets.googleapis.com/v4/spreadsheets/{{ $('Locate Setup').first().json.sheetId }}/values/Items!A1:append",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "valueInputOption",
              "value": "USER_ENTERED"
            },
            {
              "name": "insertDataOption",
              "value": "INSERT_ROWS"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ values: $('Check Result').item.json.itemRows }) }}",
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000023",
      "name": "Add Item Rows",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3080,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "c1",
              "leftValue": "={{ $('Check Result').item.json.status === 'Needs Review' }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000024",
      "name": "Needs Review?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        3300,
        300
      ]
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "PATCH",
        "url": "=https://www.googleapis.com/drive/v3/files/{{ $('Check Result').item.json.fileId }}",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "addParents",
              "value": "={{ $('Locate Setup').first().json.reviewId }}"
            },
            {
              "name": "removeParents",
              "value": "={{ $('Locate Setup').first().json.inboxId }}"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000025",
      "name": "Move to Needs Review",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3520,
        200
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleDriveOAuth2Api",
        "method": "PATCH",
        "url": "=https://www.googleapis.com/drive/v3/files/{{ $('Check Result').item.json.fileId }}",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "addParents",
              "value": "={{ $('Locate Setup').first().json.processedId }}"
            },
            {
              "name": "removeParents",
              "value": "={{ $('Locate Setup').first().json.inboxId }}"
            },
            {
              "name": "supportsAllDrives",
              "value": "true"
            }
          ]
        },
        "options": {}
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000026",
      "name": "Move to Processed",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3520,
        400
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000
    },
    {
      "parameters": {
        "content": "## Expense invoice reader\nEvery 15 minutes: reads new receipts from a Drive inbox, extracts them with Gemini, checks them, writes rows to Google Sheets and files each receipt.\n\n**Setup: just connect your accounts**\n1. Open each node with a red warning and pick or create its credential: **Google Drive OAuth2**, **Google Sheets OAuth2** and **Google Gemini (PaLM) API** (a key from aistudio.google.com).\n2. Click **Execute workflow** once. It creates the folder **Expense Reader** in your Drive with Inbox, Processed, Needs Review and the sheet **Expense Log**.\n3. Drop a receipt photo or PDF into **Inbox** and execute again to see it land in the sheet.\n4. Turn on the **Active** toggle.\n\nAnything doubtful (no date, unreadable total, low confidence, items that do not add up) goes to **Needs Review** with the reason in the sheet. Nothing is guessed.\n\n**Good to know**\n- If Gemini hits its quota or is down, the file stays in Inbox and the next run tries again. A free Gemini key allows only a few requests a day; use a paid key for real volume.\n- If writing to the sheet fails, the run stops before moving the file, so no receipt is lost.\n- Change the model, folder name or confidence level in **Config**.",
        "height": 470,
        "width": 600
      },
      "id": "a1b2c3d4-0000-4000-8000-000000000027",
      "name": "How it works",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -200
      ]
    }
  ],
  "connections": {
    "Every 15 Minutes": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Find Setup Folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Setup Folder": {
      "main": [
        [
          {
            "node": "Already Set Up?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Already Set Up?": {
      "main": [
        [
          {
            "node": "List Setup Folder",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create Setup Folder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Setup Folder": {
      "main": [
        [
          {
            "node": "Create Inbox",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Inbox": {
      "main": [
        [
          {
            "node": "Create Processed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Processed": {
      "main": [
        [
          {
            "node": "Create Needs Review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Needs Review": {
      "main": [
        [
          {
            "node": "Create Expense Log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Expense Log": {
      "main": [
        [
          {
            "node": "Add Tabs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add Tabs": {
      "main": [
        [
          {
            "node": "Write Headers",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Write Headers": {
      "main": [
        [
          {
            "node": "Setup Done",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "List Setup Folder": {
      "main": [
        [
          {
            "node": "Locate Setup",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Locate Setup": {
      "main": [
        [
          {
            "node": "List Inbox Files",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "List Inbox Files": {
      "main": [
        [
          {
            "node": "Split Files",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Files": {
      "main": [
        [
          {
            "node": "Download File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download File": {
      "main": [
        [
          {
            "node": "Build Gemini Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Gemini Request": {
      "main": [
        [
          {
            "node": "Gemini Reads Receipt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini Reads Receipt": {
      "main": [
        [
          {
            "node": "Check Result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Result": {
      "main": [
        [
          {
            "node": "Got an AI Answer?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Got an AI Answer?": {
      "main": [
        [
          {
            "node": "Add Invoice Row",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "Add Invoice Row": {
      "main": [
        [
          {
            "node": "Add Item Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add Item Rows": {
      "main": [
        [
          {
            "node": "Needs Review?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Needs Review?": {
      "main": [
        [
          {
            "node": "Move to Needs Review",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Move to Processed",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {}
}