{
  "name": "Account manager-v1",
  "nodes": [
    {
      "parameters": {
        "updates": [
          "messages"
        ],
        "options": {}
      },
      "type": "n8n-nodes-base.whatsAppTrigger",
      "typeVersion": 1,
      "position": [
        1936,
        624
      ],
      "id": "f11e49c5-9f6d-4558-8c48-e6658c054769",
      "name": "WhatsApp Trigger"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "image",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "59363409-26b1-4d66-aca8-9c71d549bf1d"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "Image route "
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "36b63731-2d95-414a-904f-8539c26122cc",
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "text",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "text route "
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "dad785ce-14a2-48e9-854c-f83466ed5f7d",
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "document",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "document route"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.4,
      "position": [
        2128,
        608
      ],
      "id": "89c8434e-ec28-4e4b-b8a0-77be7afcb2c6",
      "name": "Switch"
    },
    {
      "parameters": {
        "resource": "image",
        "operation": "analyze",
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.0-flash",
          "mode": "list",
          "cachedResultName": "models/gemini-2.0-flash"
        },
        "text": "=Analyze this image. \n\nEXTRACT & RETURN RAW JSON ONLY (No Markdown, No Explanations):\n{\n\"summary\": \"Short title (e.g. 'Starbucks Coffee' or 'Client Payment')\",\n\"amount\": Number (Extract total value),\n\"currency\": \"3-letter ISO code (Default to 'USD' if symbol is \u20b9 or missing)\",\n\"date\": \"YYYY-MM-DD\" (If missing, return null),\n\"category\": \"Exact Match from: [BUSINESS, INVESTMENTS, SAVINGS, DEBT, EDUCATION, BILLS & UTILITIES, ENTERTAINMENT, TRANSPORT, FOOD, HEALTH & WELLNESS, SHOPPING, OTHER, SUBSCRIPTIONS, TRANSFERS]. Default to 'OTHER'.\",\n\"type\": \"Income\" or \"Expense\" (Prioritize user caption keywords like 'Income', 'Salary'. If ambiguous, assume 'Expense').\n}",
        "inputType": "binary",
        "options": {}
      },
      "id": "7f8ff22e-7ed8-47f7-8c49-a7a6830793d5",
      "name": "Analyze an image",
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "position": [
        2848,
        448
      ],
      "typeVersion": 1,
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "resource": "document",
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.0-flash",
          "mode": "list",
          "cachedResultName": "models/gemini-2.0-flash"
        },
        "text": "=Analyze this document.\n\nEXTRACT & RETURN RAW JSON ONLY (No Markdown):\n{\n\"summary\": \"Vendor name or short description\",\n\"amount\": Number,\n\"currency\": \"ISO code (Default 'USD')\",\n\"date\": \"YYYY-MM-DD\" (Return null if not found),\n\"category\": \"Exact Match from: [BUSINESS, INVESTMENTS, SAVINGS, DEBT, EDUCATION, BILLS & UTILITIES, ENTERTAINMENT, TRANSPORT, FOOD, HEALTH & WELLNESS, SHOPPING, OTHER, SUBSCRIPTIONS, TRANSFERS]\",\n\"type\": \"Income\" or \"Expense\" (Check caption first. Default 'Expense').\n}",
        "inputType": "binary",
        "options": {}
      },
      "id": "de03f57c-64cd-4717-bc2b-9b92bd2bc9ba",
      "name": "Analyze a file",
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "position": [
        2848,
        976
      ],
      "typeVersion": 1,
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $json.messages[0].document.id }}"
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        2400,
        880
      ],
      "id": "8973479e-6a26-4209-8064-cee62e03bbf2",
      "name": "Download doc",
      "retryOnFail": true
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.0-flash",
          "mode": "list",
          "cachedResultName": "models/gemini-2.0-flash"
        },
        "messages": {
          "values": [
            {
              "content": "=Analyze this Text. {{ $json.messages[0].text.body }}\n\n\nEXTRACT & RETURN RAW JSON ONLY (No Markdown):\n{\n\"summary\": \"Vendor name or short description\",\n\"amount\": Number,\n\"currency\": \"ISO code (Default 'USD')\",\n\"date\": \"YYYY-MM-DD\" (Return null if not found),\n\"category\": \"Exact Match from: [BUSINESS, INVESTMENTS, SAVINGS, DEBT, EDUCATION, BILLS & UTILITIES, ENTERTAINMENT, TRANSPORT, FOOD, HEALTH & WELLNESS, SHOPPING, OTHER, SUBSCRIPTIONS, TRANSFERS]\",\n\"type\": \"Income\" or \"Expense\" (Check caption first. Default 'Expense').\n}"
            }
          ]
        },
        "jsonOutput": true,
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1,
      "position": [
        2720,
        624
      ],
      "id": "f9b632db-a6db-4dd1-aac1-39fa9f5af500",
      "name": "Message a model",
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "url": "={{ $json.url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        2624,
        352
      ],
      "id": "a08df5da-56e5-4930-a990-b5c9f235769a",
      "name": "Download image1",
      "retryOnFail": true
    },
    {
      "parameters": {
        "url": "={{ $json.url }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        2624,
        880
      ],
      "id": "4b4050c0-49eb-4f88-895a-9e198621f1ac",
      "name": "Download Doc",
      "retryOnFail": true
    },
    {
      "parameters": {
        "jsCode": "// Initialize empty text\nlet aiText = '';\nlet foundItem = null;\n\n// LOOP: Check all incoming items to find the one with the AI data\nfor (const item of items) {\n  const json = item.json;\n  \n  // 1. Check for Gemini/Google structure (content.parts[0].text)\n  if (json.content && json.content.parts && json.content.parts[0]) {\n     aiText = json.content.parts[0].text;\n     foundItem = item;\n     break; \n  }\n  // 2. Check for OpenAI/Text structure\n  else if (typeof json.content === 'string') {\n     aiText = json.content;\n     foundItem = item;\n     break;\n  }\n  // 3. Check for generic text output\n  else if (json.text) {\n     aiText = json.text;\n     foundItem = item;\n     break;\n  }\n}\n\n// If we couldn't find ANY text in any item, error out\nif (!aiText) {\n  throw new Error(\"Could not find AI text in the input items. Check Merge node mode.\");\n}\n\n// ----------------------------------------\n// CLEANUP LOGIC\n// ----------------------------------------\n\n// Regex to find the JSON curly braces {} and ignore markdown\nconst jsonMatch = aiText.match(/\\{[\\s\\S]*\\}/);\n\nif (jsonMatch) {\n  const parsedData = JSON.parse(jsonMatch[0]);\n  \n  // MERGE TRICK: Keep the original binary/link data if it exists\n  // This ensures the Google Drive link passes through to Notion\n  if (foundItem) {\n      return { ...foundItem.json, ...parsedData };\n  } else {\n      return parsedData;\n  }\n} else {\n  throw new Error(\"The AI output didn't contain valid JSON. Got this instead: \" + aiText);\n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3520,
        624
      ],
      "id": "bf969f83-8aaf-470f-9c31-8d42af0acf11",
      "name": "Cleanup outputs"
    },
    {
      "parameters": {
        "resource": "databasePage",
        "databaseId": {
          "__rl": true,
          "value": "YOUR_DATABASE_ID_HERE",
          "mode": "list",
          "cachedResultName": "Finance ",
          "cachedResultUrl": "https://www.notion.so/YOUR_DATABASE_ID_HERE"
        },
        "title": "={{ $json.summary }}",
        "propertiesUi": {
          "propertyValues": [
            {
              "key": "Amount|number",
              "numberValue": "={{ $json.amount }}"
            },
            {
              "key": "Category|relation",
              "relationValue": [
                "={{ $json.matched_category_id }}"
              ]
            },
            {
              "key": "Date|date",
              "includeTime": false,
              "date": "={{ $json.date }}"
            },
            {
              "key": "Type|select",
              "selectValue": "={{ $json.type }}"
            },
            {
              "key": "Notes|rich_text",
              "textContent": "={{ $('WhatsApp Trigger').first()?.json?.messages?.[0]?.text?.body || \"Receipt Uploaded\" }}"
            },
            {
              "key": "Receipt|files",
              "fileUrls": {
                "fileUrl": [
                  {
                    "name": "receipt",
                    "url": "={{ \n$('Upload file').isExecuted ? $('Upload file').first().json.webViewLink : \n($('Upload file1').isExecuted ? $('Upload file1').first().json.webViewLink : \n\"https://placehold.co/600x400/png?text=No+Receipt\") \n}}"
                  }
                ]
              }
            }
          ]
        },
        "options": {
          "iconType": "file",
          "icon": "=https://www.notion.so/icons/cash_gray.svg?mode=dark"
        }
      },
      "type": "n8n-nodes-base.notion",
      "typeVersion": 2.2,
      "position": [
        4128,
        624
      ],
      "id": "1abdc98b-ac2c-4337-9780-d53d1b6b21f3",
      "name": "Create a database page",
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "resource": "databasePage",
        "operation": "getAll",
        "databaseId": {
          "__rl": true,
          "value": "YOUR_DATABASE_ID_HERE",
          "mode": "list",
          "cachedResultName": "Category",
          "cachedResultUrl": "https://www.notion.so/YOUR_DATABASE_ID_HERE"
        },
        "returnAll": true,
        "options": {}
      },
      "type": "n8n-nodes-base.notion",
      "typeVersion": 2.2,
      "position": [
        3744,
        624
      ],
      "id": "f1da2ece-d6cc-4ab3-82c1-c8245b6f3feb",
      "name": "Get many database pages",
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "jsCode": "// 1. Get the list of categories from the previous node\nconst notionCategories = items;\n\n// 2. Get the expense data from the 'Cleanup outputs' node\n// We use $('Node Name').first() to reference data from up the stream\nconst expenseData = $('Cleanup outputs').first().json;\n\n// 3. Normalize the AI category to lowercase for easier matching\nconst aiCategory = expenseData.category.trim().toLowerCase();\n\n// 4. Find the matching Notion Page\nconst match = notionCategories.find(page => {\n  const notionName = page.json.name.toLowerCase(); // Assuming property is 'name'\n  return notionName === aiCategory;\n});\n\n// 5. Prepare the output\nif (match) {\n  // Found it! Add the Notion Page ID to the expense data\n  return [{\n    json: {\n      ...expenseData,\n      matched_category_id: match.json.id\n    }\n  }];\n} else {\n  // No match found. You might want to assign a \"Default\" or \"Uncategorized\" ID here\n  return [{\n    json: {\n      ...expenseData,\n      matched_category_id: null, \n      error: `No category matched for ${expenseData.category}`\n    }\n  }];\n}"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        3936,
        624
      ],
      "id": "4a147667-4ca5-4521-8f17-e85c56b987fd",
      "name": "Final parse"
    },
    {
      "parameters": {
        "name": "=Receipt_{{ $now.toFormat('yyyy-MM-dd-HH-mm-ss') }}.jpg",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "value": "YOUR_FOLDER_ID_HERE",
          "mode": "list",
          "cachedResultName": "Receipts and Invoices ( docs )",
          "cachedResultUrl": "https://drive.google.com/drive/folders/YOUR_FOLDER_ID_HERE"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2848,
        256
      ],
      "id": "befb6757-ef05-48b4-86a8-54450400c1d6",
      "name": "Upload file",
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "name": "=Receipt_{{ $now.toFormat('yyyy-MM-dd-HH-mm-ss') }}.jpg",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "folderId": {
          "__rl": true,
          "value": "YOUR_FOLDER_ID_HERE",
          "mode": "list",
          "cachedResultName": "Receipts and Invoices ( docs )",
          "cachedResultUrl": "https://drive.google.com/drive/folders/YOUR_FOLDER_ID_HERE"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleDrive",
      "typeVersion": 3,
      "position": [
        2848,
        784
      ],
      "id": "566215f7-fcb4-4ccd-a572-7b2212017be0",
      "name": "Upload file1",
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineByPosition",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        3136,
        352
      ],
      "id": "6559f03a-633a-41c9-a770-d6df3f7dc055",
      "name": "Merge"
    },
    {
      "parameters": {
        "mode": "combine",
        "combineBy": "combineByPosition",
        "options": {}
      },
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3.2,
      "position": [
        3136,
        880
      ],
      "id": "a99b73e6-0c6e-4089-a868-e4a78117b386",
      "name": "Merge1"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "YOUR_PHONE_NUMBER_ID_HERE",
        "recipientPhoneNumber": "YOUR_RECIPIENT_PHONE_NUMBER_HERE",
        "textBody": "=\ud83e\uddfe Receipt Drafted\n\nSummary: {{ $json.property_name }}\nAmount: {{ $json.property_amount }}\nDate: {{ $json.property_date.start }}\n\n\ud83d\udc47 Tap below to finalize or edit:\n{{ $json[\"url\"] }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        4368,
        624
      ],
      "id": "2b0fbd00-7ab4-41f7-a180-b3822bb86b73",
      "name": "Send message",
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "content": "### Process Images \ud83d\udcf7",
        "height": 352,
        "width": 1184,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2240,
        224
      ],
      "typeVersion": 1,
      "id": "f811e279-610c-4569-aa32-1e4babd71fbb",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "### Process Documents \ud83d\udcc4\n",
        "height": 352,
        "width": 1184,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2240,
        768
      ],
      "typeVersion": 1,
      "id": "7eb1bf29-8a5d-43ad-b587-c48d3d868b17",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "content": "### Process Messages\n",
        "width": 496,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2592,
        592
      ],
      "id": "2b8d037f-a9ad-40fb-9d4e-5290e72b64c6",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "### Store the data to Notion & Send confirmation \u2705",
        "height": 304,
        "width": 1088,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3488,
        528
      ],
      "typeVersion": 1,
      "id": "871919c6-8af5-4194-a7df-cb5ce5b0dee3",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $json.messages[0].image.id }}"
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1.1,
      "position": [
        2400,
        352
      ],
      "id": "01f7397a-d4c1-45ae-a3b5-ed1aa1087028",
      "name": "Download image",
      "retryOnFail": true
    }
  ],
  "connections": {
    "WhatsApp Trigger": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Download image",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Message a model",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Download doc",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze an image": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Analyze a file": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Download doc": {
      "main": [
        [
          {
            "node": "Download Doc",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message a model": {
      "main": [
        [
          {
            "node": "Cleanup outputs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download image1": {
      "main": [
        [
          {
            "node": "Upload file",
            "type": "main",
            "index": 0
          },
          {
            "node": "Analyze an image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download Doc": {
      "main": [
        [
          {
            "node": "Upload file1",
            "type": "main",
            "index": 0
          },
          {
            "node": "Analyze a file",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cleanup outputs": {
      "main": [
        [
          {
            "node": "Get many database pages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get many database pages": {
      "main": [
        [
          {
            "node": "Final parse",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Final parse": {
      "main": [
        [
          {
            "node": "Create a database page",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload file": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload file1": {
      "main": [
        [
          {
            "node": "Merge1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge": {
      "main": [
        [
          {
            "node": "Cleanup outputs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge1": {
      "main": [
        [
          {
            "node": "Cleanup outputs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create a database page": {
      "main": [
        [
          {
            "node": "Send message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download image": {
      "main": [
        [
          {
            "node": "Download image1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "81c86ae2-8846-4dbc-8c98-2604da519bba",
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "id": "bGpYOiPA22cREj3d",
  "tags": []
}