{
  "name": "Gmail support triage: classify, log, draft, dedupe, remind (demo)",
  "nodes": [
    {
      "id": "92e08a49-365d-5d45-aea3-a9ad3725b1b9",
      "name": "Gmail Trigger (support label)",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        },
        "simple": false,
        "filters": {
          "labelIds": [
            "INBOX"
          ],
          "q": "label:support -label:triaged"
        },
        "options": {}
      }
    },
    {
      "id": "ae891fc2-cad2-528e-9d61-11f1bab3199f",
      "name": "Lookup Message-ID (dedupe)",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        220,
        0
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "REPLACE_WITH_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Requests"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "message_id",
              "lookupValue": "={{ $json.headers['message-id'] || $json.id }}"
            }
          ]
        },
        "options": {}
      },
      "alwaysOutputData": true
    },
    {
      "id": "e3e1af36-4983-5cf8-b550-ed42320b6c2b",
      "name": "Already logged?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        440,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose"
          },
          "conditions": [
            {
              "id": "c1",
              "leftValue": "={{ $json.message_id }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "84f14787-8a13-51fe-bc4a-93a1da10e7d4",
      "name": "Skip duplicate",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        660,
        -140
      ],
      "parameters": {}
    },
    {
      "id": "6b44b3d2-4cda-5d10-baa6-99c71c05601d",
      "name": "AI classify + draft (OpenAI)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        80
      ],
      "parameters": {
        "method": "POST",
        "url": "https://api.openai.com/v1/chat/completions",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "openAiApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ model: 'gpt-4o-mini', response_format: { type: 'json_object' }, temperature: 0.2, messages: [ { role: 'system', content: \"You triage support email for a small IT support & consultancy firm. Return ONLY JSON: {\\\"type\\\":\\\"how_to|bug|order|invoice|billing|other\\\",\\\"urgency\\\":\\\"low|normal|high\\\",\\\"order_id\\\":string|null,\\\"invoice_no\\\":string|null,\\\"summary\\\":string(<=25 words),\\\"draft_reply\\\":string(<=120 words, polite, no promises of dates)}\" }, { role: 'user', content: 'From: ' + $('Gmail Trigger (support label)').item.json.from.text + '\\nSubject: ' + $('Gmail Trigger (support label)').item.json.subject + '\\n\\n' + ($('Gmail Trigger (support label)').item.json.text || '').slice(0, 6000) } ] }) }}",
        "options": {
          "timeout": 30000
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 3000,
      "onError": "continueErrorOutput"
    },
    {
      "id": "f34af7e0-f2ba-5c3e-aebe-86b541a54179",
      "name": "Parse AI JSON",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        60
      ],
      "parameters": {
        "jsCode": "const src = $('Gmail Trigger (support label)').item.json;\nlet ai = {};\ntry { ai = JSON.parse($json.choices[0].message.content); } catch (e) { ai = { type: 'other', urgency: 'normal', summary: 'AI parse failed: review manually', draft_reply: '' }; }\nreturn [{ json: {\n  message_id: src.headers?.['message-id'] || src.id,\n  gmail_id: src.id, thread_id: src.threadId,\n  received_at: new Date(Number(src.internalDate || Date.now())).toISOString(),\n  from: src.from?.text || '', subject: src.subject || '',\n  type: ai.type || 'other', urgency: ai.urgency || 'normal',\n  order_id: ai.order_id || '', invoice_no: ai.invoice_no || '',\n  summary: ai.summary || '', draft_reply: ai.draft_reply || '',\n  status: 'open', reminded_at: ''\n} }];"
      }
    },
    {
      "id": "609a9aae-adbe-5db2-a119-ab35587859c5",
      "name": "Log to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        1100,
        60
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "REPLACE_WITH_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Requests"
        },
        "columns": {
          "mappingMode": "autoMapInputData",
          "value": {},
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      }
    },
    {
      "id": "1f35a034-8733-5f3b-92e7-fdd5bacc3f8d",
      "name": "Create Gmail draft (for review)",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1320,
        60
      ],
      "parameters": {
        "resource": "draft",
        "subject": "=Re: {{ $('Parse AI JSON').item.json.subject }}",
        "emailType": "text",
        "message": "={{ $('Parse AI JSON').item.json.draft_reply }}",
        "options": {
          "threadId": "={{ $('Parse AI JSON').item.json.thread_id }}",
          "sendTo": "={{ $('Parse AI JSON').item.json.from }}"
        }
      }
    },
    {
      "id": "f3341a7a-e9e1-5edc-ae0d-3c24e2575040",
      "name": "Label as triaged",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1540,
        60
      ],
      "parameters": {
        "operation": "addLabels",
        "messageId": "={{ $('Parse AI JSON').item.json.gmail_id }}",
        "labelIds": [
          "REPLACE_WITH_TRIAGED_LABEL_ID"
        ]
      }
    },
    {
      "id": "e5df2cd7-6cac-587d-aa06-7bca8030d00c",
      "name": "AI failed: log for manual review",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        880,
        240
      ],
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "REPLACE_WITH_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Errors"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "message_id": "={{ $('Gmail Trigger (support label)').item.json.id }}",
            "subject": "={{ $('Gmail Trigger (support label)').item.json.subject }}",
            "error": "={{ $json.error?.message || 'OpenAI request failed after 3 tries' }}",
            "at": "={{ $now.toISO() }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "message_id",
              "displayName": "message_id",
              "type": "string"
            },
            {
              "id": "subject",
              "displayName": "subject",
              "type": "string"
            },
            {
              "id": "error",
              "displayName": "error",
              "type": "string"
            },
            {
              "id": "at",
              "displayName": "at",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "191a74a3-43e0-5fe0-aea6-10087cf86127",
      "name": "Every weekday 9:00",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        460
      ],
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "cronExpression",
              "expression": "0 9 * * 1-5"
            }
          ]
        }
      }
    },
    {
      "id": "a9ed9792-82e5-5d76-ad5d-9f1f7b9359e2",
      "name": "Read open requests",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        220,
        460
      ],
      "parameters": {
        "operation": "read",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "REPLACE_WITH_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Requests"
        },
        "filtersUI": {
          "values": [
            {
              "lookupColumn": "status",
              "lookupValue": "open"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "007804d1-0d1f-5327-82f7-e89a87459bc4",
      "name": "No reply after X days?",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        460
      ],
      "parameters": {
        "jsCode": "const DAYS = 2; // X days without a reply\nconst cutoff = Date.now() - DAYS * 86400000;\nreturn $input.all().filter(i => new Date(i.json.received_at).getTime() < cutoff && !i.json.reminded_at);"
      }
    },
    {
      "id": "ced7440f-e12c-5bac-acc4-aff6c1cb100a",
      "name": "Send reminder to team",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        660,
        460
      ],
      "parameters": {
        "sendTo": "REPLACE_WITH_TEAM_EMAIL",
        "subject": "=Reminder: no reply yet on \"{{ $json.subject }}\"",
        "emailType": "text",
        "message": "=From: {{ $json.from }}\nType: {{ $json.type }} \u00b7 Urgency: {{ $json.urgency }}\nSummary: {{ $json.summary }}\nReceived: {{ $json.received_at }}\n\nA draft reply is waiting in Gmail.",
        "options": {}
      }
    },
    {
      "id": "e188f7ef-fb68-596b-be7d-c078861598f4",
      "name": "Mark reminded",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.5,
      "position": [
        880,
        460
      ],
      "parameters": {
        "operation": "update",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "REPLACE_WITH_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Requests"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "message_id": "={{ $('No reply after X days?').item.json.message_id }}",
            "reminded_at": "={{ $now.toISO() }}"
          },
          "matchingColumns": [
            "message_id"
          ],
          "schema": [
            {
              "id": "message_id",
              "displayName": "message_id",
              "type": "string"
            },
            {
              "id": "reminded_at",
              "displayName": "reminded_at",
              "type": "string"
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "fe09a603-af91-5058-9ebd-9555aca4dfce",
      "name": "Note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -260
      ],
      "parameters": {
        "width": 620,
        "height": 200,
        "content": "## Gmail triage (demo by Mayank Raj \u00b7 Kingdom of Kumar)\nSample build for an Upwork posting. Replace REPLACE_WITH_* values and connect Gmail, Google Sheets and OpenAI credentials.\n**Dedupe:** Message-ID lookup in the Sheet before processing; processed mail is labelled `triaged`.\n**Errors:** OpenAI retries 3x, then the item is logged to the `Errors` tab. Set the separate error workflow under Settings for crash alerts.\n**Human review:** replies are created as Gmail drafts only, never sent automatically."
      }
    }
  ],
  "connections": {
    "Gmail Trigger (support label)": {
      "main": [
        [
          {
            "node": "Lookup Message-ID (dedupe)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lookup Message-ID (dedupe)": {
      "main": [
        [
          {
            "node": "Already logged?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Already logged?": {
      "main": [
        [
          {
            "node": "Skip duplicate",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "AI classify + draft (OpenAI)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI classify + draft (OpenAI)": {
      "main": [
        [
          {
            "node": "Parse AI JSON",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "AI failed: log for manual review",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse AI JSON": {
      "main": [
        [
          {
            "node": "Log to Google Sheets",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Log to Google Sheets": {
      "main": [
        [
          {
            "node": "Create Gmail draft (for review)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Gmail draft (for review)": {
      "main": [
        [
          {
            "node": "Label as triaged",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every weekday 9:00": {
      "main": [
        [
          {
            "node": "Read open requests",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Read open requests": {
      "main": [
        [
          {
            "node": "No reply after X days?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "No reply after X days?": {
      "main": [
        [
          {
            "node": "Send reminder to team",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send reminder to team": {
      "main": [
        [
          {
            "node": "Mark reminded",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveManualExecutions": true
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}