{
  "id": "AD36Ma2lsIJBzwIa",
  "name": "whatsapp Invoice Agent",
  "tags": [],
  "nodes": [
    {
      "id": "cbd2bf3a-80e9-416b-9fee-12a2747b0907",
      "name": "WhatsApp Trigger",
      "type": "n8n-nodes-base.whatsAppTrigger",
      "position": [
        704,
        176
      ],
      "parameters": {
        "options": {},
        "updates": [
          "messages"
        ]
      },
      "typeVersion": 1
    },
    {
      "id": "d8d6f532-cdf4-4459-8ee4-924483ceda08",
      "name": "Analyze Image",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1456,
        176
      ],
      "parameters": {
        "url": "https://api.ocr.space/parse/image",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "contentType": "multipart-form-data",
        "sendHeaders": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "file",
              "parameterType": "formBinaryData",
              "inputDataFieldName": "data"
            }
          ]
        },
        "headerParameters": {
          "parameters": [
            {
              "name": "apikey",
              "value": "{{ OCR_SPACE_API_KEY }}"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "3ed72ac4-daf2-43dc-bd6f-5cac4295bfc2",
      "name": "Download File",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1200,
        176
      ],
      "parameters": {
        "url": "{{ $json.url }}",
        "options": {},
        "responseFormat": "file",
        "headerParametersUi": {
          "parameter": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ YOUR_FACEBOOK_ACCESS_TOKEN }}"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "593e8766-75be-4523-8183-e788eaf22cf6",
      "name": "Add Invoice To Drive",
      "type": "n8n-nodes-base.googleDrive",
      "position": [
        1168,
        432
      ],
      "parameters": {
        "name": "=Invoice {{ $json['Due Date'] }}",
        "driveId": {
          "__rl": true,
          "mode": "list",
          "value": "My Drive"
        },
        "options": {},
        "folderId": {
          "__rl": true,
          "mode": "list",
          "value": "1CbPlxSzy9XZQf3wxMAvm6qVQOPcPcVV8",
          "cachedResultUrl": "https://drive.google.com/drive/folders/1CbPlxSzy9XZQf3wxMAvm6qVQOPcPcVV8",
          "cachedResultName": "iNVOICE db"
        }
      },
      "credentials": {
        "googleDriveOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 3
    },
    {
      "id": "3ee34650-3693-478d-9432-9a60e72bedae",
      "name": "Update DataBase",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        704,
        432
      ],
      "parameters": {
        "columns": {
          "value": {
            "Notes": "={{ $json.Notes }}",
            "Amount": "={{ $json.Amount }}",
            "Due Date": "={{ $json.DueDate }}",
            "Invoice Date": "={{ $json.InvoiceDate }}",
            "Payment Method": "={{ $json.PaymentMethod }}"
          },
          "schema": [
            {
              "id": "Amount",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Amount",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Payment Method",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Payment Method",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Invoice Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Invoice Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Due Date",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Due Date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Notes",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "Notes",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "Amount"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "appendOrUpdate",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1D13TAbXIUWF_zNt4VwEv7MGaQUY8pErisqZwKY-ANeU/edit#gid=0",
          "cachedResultName": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1D13TAbXIUWF_zNt4VwEv7MGaQUY8pErisqZwKY-ANeU",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1D13TAbXIUWF_zNt4VwEv7MGaQUY8pErisqZwKY-ANeU/edit?usp=drivesdk",
          "cachedResultName": "Save Invoice Details"
        }
      },
      "typeVersion": 4.6
    },
    {
      "id": "f3c66131-bb3f-40f1-a4d4-ba29bbb93748",
      "name": "Reply",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        1728,
        432
      ],
      "parameters": {
        "textBody": "={{ $json.output }}",
        "operation": "send",
        "phoneNumberId": "={{ $('WhatsApp Trigger').item.json.metadata.display_phone_number }}",
        "additionalFields": {},
        "recipientPhoneNumber": "={{ $('WhatsApp Trigger').item.json.contacts[0].wa_id }}"
      },
      "typeVersion": 1
    },
    {
      "id": "e66b61e6-8101-4cf7-a0f6-35ffb0900939",
      "name": "Original Invoice Retrieval",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        912,
        432
      ],
      "parameters": {
        "url": "={{ $('Download File').item.json.url }}",
        "options": {},
        "responseFormat": "file",
        "headerParametersUi": {
          "parameter": [
            {
              "name": "Authorization",
              "value": "Bearer {{ FACEBOOK_ACCESS_TOKEN }}"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "8ac12019-4495-4150-92e0-da27cb7c08b1",
      "name": "Invoice Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1408,
        432
      ],
      "parameters": {
        "text": "={{ $('Analyze Image').item.json.ParsedResults[0].ParsedText }}",
        "options": {
          "systemMessage": "From the given parsed invoice text, extract and summarize the following key points in 3\u20134 short lines:\n\nTotal Amount\nPayment Method\nDue Date\n\nAny important instruction or penalty mentioned in the Notes section\n\nThe response should be short, clear, and user-friendly. Ignore unnecessary lines and correct any obvious OCR formatting issues like extra commas or spacing in currency.\n\n"
        },
        "promptType": "define"
      },
      "typeVersion": 2.1
    },
    {
      "id": "f2e861df-25b7-4cb6-b997-a550cbeee3b0",
      "name": "Parse Text",
      "type": "n8n-nodes-base.code",
      "position": [
        1728,
        176
      ],
      "parameters": {
        "jsCode": "// Step 1: Get the raw text from OCR output\nconst rawText = $json.ParsedResults[0].ParsedText || '';\n\n// Step 2: Clean and split into lines\nconst cleaned = rawText.replace(/\\r/g, '').replace(/\\\\n/g, '\\n');\nconst lines = cleaned.split('\\n').map(l => l.trim()).filter(Boolean);\n\n// Step 3: Helper function to support both \":\" and \".\" after field names\nfunction extractField(label) {\n  const index = lines.findIndex(line =>\n    line.toLowerCase().startsWith(label.toLowerCase() + ':') ||\n    line.toLowerCase().startsWith(label.toLowerCase() + '.')\n  );\n\n  if (index !== -1) {\n    return lines[index].split(/[:.]/).slice(1).join(':').trim();\n  }\n  return null;\n}\n\n// Step 4: Extract Amount\nlet amountLine = lines.find(line => line.toLowerCase().includes('total amount'));\nlet amount = amountLine ? amountLine.split(/[:.]/).pop().trim() : null;\n\n// Step 5: Extract Payment Method (next 1\u20133 lines)\nlet paymentMethod = '';\nconst paymentIndex = lines.findIndex(l => l.toLowerCase().includes('payment method'));\nif (paymentIndex !== -1) {\n  for (let i = paymentIndex + 1; i <= paymentIndex + 3 && i < lines.length; i++) {\n    paymentMethod += lines[i] + ' ';\n  }\n  paymentMethod = paymentMethod.trim();\n}\n\n// Step 6: Extract Notes (everything after Notes label)\nlet notes = '';\nconst notesIndex = lines.findIndex(l => l.toLowerCase().startsWith('notes'));\nif (notesIndex !== -1) {\n  notes = lines.slice(notesIndex + 1).join(' ').trim();\n}\n\n// Step 7: Return the structured data\nreturn [\n  {\n    json: {\n      InvoiceDate: extractField('Date'),\n      DueDate: extractField('Due Date'),\n      Amount: amount,\n      PaymentMethod: paymentMethod,\n      Notes: notes\n    }\n  }\n];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "b4d3c31b-a03e-48e3-9494-a5d0f66730a4",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1200,
        704
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "fdee5820-e117-42e5-884d-3113dce51e1d",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        656,
        128
      ],
      "parameters": {
        "color": 7,
        "width": 688,
        "height": 208,
        "content": "## Whatsapp Intake"
      },
      "typeVersion": 1
    },
    {
      "id": "cb3317e1-d28d-4e16-a9c2-50d9fd30d5f2",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1376,
        128
      ],
      "parameters": {
        "color": 6,
        "width": 528,
        "height": 208,
        "content": "## OCR & Parsing"
      },
      "typeVersion": 1
    },
    {
      "id": "675080f0-1ae0-4467-b57d-54029df9076c",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1376,
        368
      ],
      "parameters": {
        "color": 4,
        "width": 528,
        "height": 224,
        "content": "## AI Summary & Reply"
      },
      "typeVersion": 1
    },
    {
      "id": "64508997-d051-4b79-b57b-f64d3b3af6c4",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        656,
        368
      ],
      "parameters": {
        "width": 688,
        "height": 224,
        "content": "## Update & Save Invoice Record"
      },
      "typeVersion": 1
    },
    {
      "id": "5522c5ad-b60f-471a-9926-cb75942dcd32",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1136,
        624
      ],
      "parameters": {
        "color": 3,
        "width": 208,
        "height": 208,
        "content": "## Chat Model"
      },
      "typeVersion": 1
    },
    {
      "id": "d5942506-70ea-4c9a-b842-5fcbb228003e",
      "name": "Get Download URL",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        944,
        176
      ],
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $json.messages[0].document.id }}"
      },
      "notesInFlow": false,
      "typeVersion": 1
    },
    {
      "id": "65d1ced6-8806-46d1-a2e5-33d913f3d934",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        48,
        128
      ],
      "parameters": {
        "width": 528,
        "height": 864,
        "content": "# \ud83e\uddfe WhatsApp Invoice Automation\n\n## How it works\nThis workflow automates invoice processing via WhatsApp. When a new invoice image or PDF arrives, it\u2019s automatically downloaded and scanned with OCR to extract key data such as **amount**, **date**, **payment method**, and **notes**.\n\nThe parsed data is logged to **Google Sheets**, the original file is uploaded to **Google Drive**, and an AI-generated summary is sent back to the sender on WhatsApp.\n\n## \u2699\ufe0f Setup steps\n\n### 1. WhatsApp Cloud API\nCreate a WhatsApp Business App on [Meta Developers](https://developers.facebook.com/).  \nThen add your Access Token and Phone Number ID in the Trigger and Reply nodes.\n\n### 2. OCR.Space API\nGet a free API key from [ocr.space/ocrapi](https://ocr.space/ocrapi)  \nand paste it in the Analyze Image node.\n\n### 3. Google Sheets & Drive\nConnect your Google account and ensure your sheet has columns like:\n- Amount  \n- Date  \n- Notes\n\n### 4. OpenAI\nGet your API key from [OpenAI](https://platform.openai.com/)  \nand add it to the Chat Model node."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "7cbba7bf-dc1c-4209-854d-8b7b382d7276",
  "connections": {
    "Parse Text": {
      "main": [
        [
          {
            "node": "Update DataBase",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Analyze Image": {
      "main": [
        [
          {
            "node": "Parse Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Download File": {
      "main": [
        [
          {
            "node": "Analyze Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Invoice Agent": {
      "main": [
        [
          {
            "node": "Reply",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Update DataBase": {
      "main": [
        [
          {
            "node": "Original Invoice Retrieval",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Download URL": {
      "main": [
        [
          {
            "node": "Download File",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp Trigger": {
      "main": [
        [
          {
            "node": "Get Download URL",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Invoice Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Add Invoice To Drive": {
      "main": [
        [
          {
            "node": "Invoice Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Original Invoice Retrieval": {
      "main": [
        [
          {
            "node": "Add Invoice To Drive",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}