{
  "name": "Hotline — Instant Response",
  "meta": {
    "description": "The 38-second relay: quote-form webhook → validate → dedupe → enrich → Claude qualification + draft → confidence gate → Resend email → Postgres → owner ping.",
    "owner": "Northwind Home Services (fictional demo client)"
  },
  "nodes": [
    {
      "id": "a1",
      "name": "Quote Form Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [0, 300],
      "parameters": {
        "path": "hotline-intake",
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "notes": "Receives the Next.js /api/lead payload. HMAC signature checked in Validate & Normalize."
    },
    {
      "id": "a2",
      "name": "Validate & Normalize",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [220, 300],
      "parameters": {
        "jsCode": "// Schema-validate and normalize the payload.\n// Rejects junk before it can cost an LLM call or a CRM write.\nconst required = ['name', 'email', 'service', 'message'];\nfor (const item of $input.all()) {\n  for (const field of required) {\n    if (!item.json[field] || String(item.json[field]).trim() === '') {\n      throw new Error(`Invalid payload: missing field ${field}`);\n    }\n  }\n  item.json.email = String(item.json.email).trim().toLowerCase();\n  item.json.locale = item.json.locale === 'fr' ? 'fr' : 'en';\n  item.json.receivedAt = new Date().toISOString();\n}\nreturn $input.all();"
      }
    },
    {
      "id": "a3",
      "name": "Duplicate Check (90d)",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [440, 300],
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT id, stage FROM leads WHERE email = $1 AND service = $2 AND created_at > NOW() - INTERVAL '90 days' LIMIT 1",
        "options": { "queryReplacement": "={{ [$json.email, $json.service] }}" }
      },
      "notes": "DUPLICATE RULE: same email + same service within 90 days = the same deal. Never create a twin record; update stage and append activity instead."
    },
    {
      "id": "a4",
      "name": "Claude: Qualify & Draft",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [660, 300],
      "parameters": {
        "method": "POST",
        "url": "https://api.anthropic.com/v1/messages",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            { "name": "x-api-key", "value": "={{ $env.ANTHROPIC_API_KEY }}" },
            { "name": "anthropic-version", "value": "2023-06-01" }
          ]
        },
        "sendBody": true,
        "jsonBody": "={\"model\": \"claude-sonnet-4-5-20250929\", \"max_tokens\": 1400, \"messages\": [{\"role\": \"user\", \"content\": \"Qualify this lead and draft the reply email. Return JSON only. Lead: \" + JSON.stringify($json)}]}"
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "notes": "RETRY RULE: 3 attempts, exponential backoff handled by wrapper schedule (2s → 4s → 8s). On final failure the On Error branch pings the owner and parks the lead in 'new' — a flaky API never loses a lead."
    },
    {
      "id": "a5",
      "name": "Confidence Gate",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [880, 300],
      "parameters": {
        "conditions": {
          "number": [
            {
              "value1": "={{ $json.confidence }}",
              "operation": "largerEqual",
              "value2": "={{ $env.CONFIDENCE_THRESHOLD || 55 }}"
            }
          ]
        }
      },
      "notes": "CONFIDENCE-GATED SENDING: below threshold the draft is held, stage stays 'new', and the owner gets a review link. Only a human click releases the email. The AI proposes; a person disposes."
    },
    {
      "id": "a6",
      "name": "Send Email (Resend)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1120, 180],
      "parameters": {
        "method": "POST",
        "url": "https://api.resend.com/emails",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            { "name": "Authorization", "value": "=Bearer {{ $env.RESEND_API_KEY }}" }
          ]
        },
        "sendBody": true,
        "jsonBody": "={\"from\": \"Maya at Northwind <quotes@northwind.example>\", \"to\": [$('Validate & Normalize').item.json.email], \"subject\": $json.subject, \"text\": $json.body}"
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 1500
    },
    {
      "id": "a7",
      "name": "Hold for Human Review",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1120, 420],
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO leads (id, name, email, service, message, stage, email_status, qualification, draft) VALUES ($1,$2,$3,$4,$5,'new','held',$6,$7)",
        "options": { "queryReplacement": "={{ [$json.id, $json.name, $json.email, $json.service, $json.message, $json.qualification, $json.draft] }}" }
      },
      "notes": "False branch of the confidence gate: record saved, nothing sent, owner notified with an approve link."
    },
    {
      "id": "a8",
      "name": "Write Lead + Activity",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [1340, 180],
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO leads (id, name, email, service, message, stage, email_status, response_ms, qualification, draft) VALUES ($1,$2,$3,$4,$5,'contacted','sent',$6,$7,$8); INSERT INTO runs (id, lead_id, status, duration_ms, steps) VALUES ($9,$1,'success',$6,$10)",
        "options": { "queryReplacement": "={{ [$json.id, $json.name, $json.email, $json.service, $json.message, $json.elapsedMs, $json.qualification, $json.draft, $json.runId, $json.steps] }}" }
      }
    },
    {
      "id": "a9",
      "name": "Owner Ping (Slack + SMS)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [1560, 180],
      "parameters": {
        "method": "POST",
        "url": "={{ $env.SLACK_WEBHOOK_URL }}",
        "sendBody": true,
        "jsonBody": "={\"text\": \"🔥 \" + $json.band.toUpperCase() + \" lead (\" + $json.score + \"/100): \" + $json.name + \" — \" + $json.service + \". Reply sent in \" + $json.elapsedMs/1000 + \"s. Evidence: \" + $json.evidence.join(', ')}"
      },
      "retryOnFail": true,
      "maxTries": 2,
      "waitBetweenTries": 1000,
      "notes": "SMS via Twilio for HOT leads only — see owner-notification.json."
    }
  ],
  "connections": {
    "Quote Form Webhook": { "main": [[{ "node": "Validate & Normalize", "type": "main", "index": 0 }]] },
    "Validate & Normalize": { "main": [[{ "node": "Duplicate Check (90d)", "type": "main", "index": 0 }]] },
    "Duplicate Check (90d)": { "main": [[{ "node": "Claude: Qualify & Draft", "type": "main", "index": 0 }]] },
    "Claude: Qualify & Draft": { "main": [[{ "node": "Confidence Gate", "type": "main", "index": 0 }]] },
    "Confidence Gate": {
      "main": [
        [{ "node": "Send Email (Resend)", "type": "main", "index": 0 }],
        [{ "node": "Hold for Human Review", "type": "main", "index": 0 }]
      ]
    },
    "Send Email (Resend)": { "main": [[{ "node": "Write Lead + Activity", "type": "main", "index": 0 }]] },
    "Write Lead + Activity": { "main": [[{ "node": "Owner Ping (Slack + SMS)", "type": "main", "index": 0 }]] }
  },
  "settings": {
    "executionOrder": "v1",
    "saveExecutionProgress": true,
    "timezone": "America/Montreal"
  }
}
