{
  "name": "AtHearth Gmail Inbox Automation",
  "nodes": [
    {
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "filters": {
          "includeSpamTrash": false
        },
        "options": {}
      },
      "id": "gmail-trigger",
      "name": "Gmail Trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1,
      "position": [
        240,
        300
      ],
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "gpt-4o-mini"
        },
        "messages": {
          "values": [
            {
              "content": "=You are an email analyzer for AtHearth, a rental property service for foreigners in Japan.\n\n## IMPORTANT RULES\n\n### 1. User Seriousness Check\n- Users with 3+ favorites = serious\n- Users with detailed questions = serious\n- Users with vague/short messages = low priority\n\n### 2. Spy Risk Detection (Red Flags)\n- RC not completed but requesting viewing = suspicious (-20 points)\n- RC not completed but many favorites (6+) = suspicious (-15 points)\n- Unusually detailed questions about security/keys = suspicious (-10 points)\n- Suspicious email domains (guerrillamail, tempmail, 10minutemail) = suspicious (-20 points)\n- Single + under 25 years old = higher risk (-20 points)\n- Overseas access + claims to have residence card = contradiction (-25 points)\n\n### 3. Positive Indicators\n- RC completed = trustworthy (+20 points)\n- Family (multiple occupants) = trustworthy (+15 points)\n- Specific moving reason (job transfer, marriage, childbirth) = trustworthy (+15 points)\n- Has submitted residence card = trustworthy (+30 points)\n\n### 4. Response Guidelines\n- NEVER promise viewings before eligibility check\n- NEVER propose specific properties (users should search themselves)\n- NEVER demand documents immediately (understand situation first)\n- If NG_STUDENT_VISA: Check if starting work in April\n- If NG_INCOME: Check if partner can be the contractor\n- Always offer a call option: https://cal.com/athearth/30min\n\n### 5. Risk Score Thresholds\n- 70+: Low risk - proceed with document check\n- 50-69: Medium - additional questions needed\n- 30-49: High risk - request multiple documents\n- <30: Spy suspect - do not proceed until documents submitted\n\n---\n\n## EMAIL TO ANALYZE\n\nFrom: {{ $json.from }}\nSubject: {{ $json.subject }}\nDate: {{ $json.date }}\n\nBody:\n{{ $json.text || $json.snippet }}\n\n---\n\nAnalyze and respond in JSON format:\n{\n  \"category\": \"inquiry | viewing_request | document_submission | question | complaint | other\",\n  \"priority\": \"high | medium | low\",\n  \"summary\": \"1-2 sentence summary in Japanese\",\n  \"spy_risk_assessment\": {\n    \"estimated_score\": 0-100,\n    \"risk_level\": \"low | medium | high | spy_suspect\",\n    \"red_flags\": [\"list of detected red flags\"],\n    \"positive_indicators\": [\"list of positive signs\"]\n  },\n  \"user_category_guess\": \"OK_EMPLOYED | OK_STUDENT | NG_STUDENT_VISA | NG_INCOME | NG_FREELANCE | UNKNOWN\",\n  \"residence_card_needed\": true/false,\n  \"suggested_reply\": \"Draft reply in the same language as the original email\",\n  \"next_actions\": [\"list of actions for support team\"],\n  \"questions_to_ask\": [\"clarifying questions if needed\"]\n}"
            }
          ]
        },
        "options": {
          "responseFormat": "json_object"
        }
      },
      "id": "ai-analysis",
      "name": "AI Email Analysis",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        480,
        300
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "const gmail = $('Gmail Trigger').item.json;\nlet aiContent = $('AI Email Analysis').item.json.message.content;\n\n// Remove code block markers (```json ... ```)\naiContent = aiContent.replace(/```json\\n?/g, '').replace(/```\\n?/g, '').trim();\n\nlet aiResult;\ntry {\n  aiResult = JSON.parse(aiContent);\n} catch (e) {\n  aiResult = {\n    category: 'unknown',\n    priority: 'medium',\n    summary: 'AI\u5206\u6790\u7d50\u679c\u306e\u30d1\u30fc\u30b9\u306b\u5931\u6557: ' + e.message,\n    spy_risk_assessment: { risk_level: 'unknown', estimated_score: 50 },\n    suggested_reply: ''\n  };\n}\n\nconst riskEmoji = aiResult.spy_risk_assessment.risk_level === 'low' ? '\ud83d\udfe2' : \n                  aiResult.spy_risk_assessment.risk_level === 'medium' ? '\ud83d\udfe1' : \n                  aiResult.spy_risk_assessment.risk_level === 'high' ? '\ud83d\udfe0' : '\ud83d\udd34';\n\nconst priorityEmoji = aiResult.priority === 'high' ? '\ud83d\udd25' : \n                      aiResult.priority === 'medium' ? '\ud83d\udccc' : '\ud83d\udcdd';\n\nconst message = `\ud83d\udce7 *New Email Analysis*\n\n*From:* ${gmail.From || gmail.from || 'Unknown'}\n*Subject:* ${gmail.Subject || gmail.subject || 'No Subject'}\n\n---\n\n${priorityEmoji} *Priority:* ${aiResult.priority}\n${riskEmoji} *Spy Risk:* ${aiResult.spy_risk_assessment.risk_level} (${aiResult.spy_risk_assessment.estimated_score}/100)\n*Category:* ${aiResult.category}\n\n*Summary:*\n${aiResult.summary}\n\n---\n\n*Suggested Reply:*\n${aiResult.suggested_reply ? aiResult.suggested_reply.substring(0, 500) : 'N/A'}${aiResult.suggested_reply && aiResult.suggested_reply.length > 500 ? '...' : ''}`;\n\nreturn { slackMessage: message };"
      },
      "id": "format-message",
      "name": "Format Slack Message",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        720,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "REPLACE_WITH_SLACK_WEBHOOK_URL",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: $json.slackMessage }) }}",
        "options": {}
      },
      "id": "slack-notification",
      "name": "Send to Slack",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        960,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "condition-success",
              "leftValue": "={{ $json.statusCode }}",
              "rightValue": 200,
              "operator": {
                "type": "number",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "check-response",
      "name": "Check Response",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        1200,
        300
      ]
    },
    {
      "parameters": {
        "content": "## AtHearth Gmail Inbox Automation\n\n**Purpose**: Automatically process incoming emails to support@athearth.com\n\n### Flow:\n1. Gmail Trigger monitors inbox every minute\n2. AI analyzes email content and categorizes\n3. Code node formats the message\n4. Results sent to Slack with rich formatting\n\n### Setup Required:\n1. Add Gmail OAuth2 credentials (support@athearth.com)\n2. Add OpenAI API credentials\n3. Replace REPLACE_WITH_SLACK_WEBHOOK_URL in 'Send to Slack' node\n\n### \u26a0\ufe0f IMPORTANT:\nDO NOT share Slack Webhook URLs publicly!\n\n### Gist URL for updates:\nhttps://gist.githubusercontent.com/athearthapp/6366619f81741ab1b1666ef4eb9ba3c5/raw/gmail-inbox-automation.json",
        "height": 380,
        "width": 340
      },
      "id": "sticky-note",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -60,
        180
      ]
    }
  ],
  "connections": {
    "Gmail Trigger": {
      "main": [
        [
          {
            "node": "AI Email Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Email Analysis": {
      "main": [
        [
          {
            "node": "Format Slack Message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Slack Message": {
      "main": [
        [
          {
            "node": "Send to Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send to Slack": {
      "main": [
        [
          {
            "node": "Check Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [
    {
      "name": "AtHearth"
    },
    {
      "name": "Email"
    },
    {
      "name": "Automation"
    }
  ]
}