{
  "name": "Post-Appointment Review & Sentiment Routing",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "hoursInterval": 1
            }
          ]
        }
      },
      "id": "appt-cron",
      "name": "Schedule Trigger - Hourly",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [180, 240]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT a.id, a.\"customerName\", a.\"customerPhone\", a.\"serviceName\", a.\"completedAt\"\nFROM \"Appointment\" a\nWHERE a.status = 'completed'\n  AND a.\"completedAt\" >= NOW() - INTERVAL '2 hours 15 minutes'\n  AND a.\"completedAt\" < NOW() - INTERVAL '2 hours'\n  AND a.\"reviewSent\" = false\nLIMIT 50;"
      },
      "id": "appt-fetch-db",
      "name": "Postgres - Fetch Completed Appointments",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [420, 240],
      "credentials": {
        "postgres": {
          "id": "postgres-cred-placeholder",
          "name": "Production Database"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v25.0/{{$env.WHATSAPP_PHONE_NUMBER_ID}}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"messaging_product\": \"whatsapp\",\n  \"to\": \"{{ $json.customerPhone }}\",\n  \"type\": \"template\",\n  \"template\": {\n    \"name\": \"appointment_review_survey\",\n    \"language\": { \"code\": \"en\" },\n    \"components\": [\n      {\n        \"type\": \"body\",\n        \"parameters\": [\n          { \"type\": \"text\", \"text\": \"{{ $json.customerName }}\" },\n          { \"type\": \"text\", \"text\": \"{{ $json.serviceName }}\" }\n        ]\n      }\n    ]\n  }\n}"
      },
      "id": "appt-send-survey",
      "name": "WhatsApp - Dispatch 2h Followup Survey",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [660, 240],
      "credentials": {
        "httpHeaderAuth": {
          "id": "meta-whatsapp-token-cred",
          "name": "WhatsApp Cloud API Token"
        }
      }
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "appointment-survey-webhook",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "appt-incoming-survey",
      "name": "Webhook - Inbound Customer Rating",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [180, 520],
      "webhookId": "survey-response-hook"
    },
    {
      "parameters": {
        "jsCode": "const body = $input.first().json.body || $input.first().json;\nconst ratingNumber = parseInt(body.rating || body.button_reply?.id || '0', 10);\n\nreturn [{\n  json: {\n    appointment_id: body.appointment_id || 'apt-101',\n    customer_name: body.customer_name || 'Customer',\n    customer_phone: body.customer_phone || body.from || '',\n    rating: ratingNumber,\n    feedback_notes: body.comment || body.text || 'No comment provided',\n    is_promoter: ratingNumber >= 4,\n    received_at: new Date().toISOString()\n  }\n}];"
      },
      "id": "appt-parse-rating",
      "name": "Parse Rating & Sentiment",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [420, 520]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 1
          },
          "conditions": [
            {
              "id": "cond-rating-check",
              "leftValue": "={{ $json.rating }}",
              "operator": {
                "type": "number",
                "operation": "gte"
              },
              "rightValue": 4
            }
          ],
          "combinator": "and"
        }
      },
      "id": "appt-if-high-rating",
      "name": "Is High Rating (4-5 Stars)?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [660, 520]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v25.0/{{$env.WHATSAPP_PHONE_NUMBER_ID}}/messages",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"messaging_product\": \"whatsapp\",\n  \"to\": \"{{ $('Parse Rating & Sentiment').item.json.customer_phone }}\",\n  \"type\": \"text\",\n  \"text\": {\n    \"body\": \"Thank you so much {{ $('Parse Rating & Sentiment').item.json.customer_name }}! We are thrilled you had a 5-star experience. Could you share your review on Google? It takes 30 seconds: https://g.page/r/codeven/review\"\n  }\n}"
      },
      "id": "appt-send-google-link",
      "name": "WhatsApp - Send Google Review Link",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [940, 440],
      "credentials": {
        "httpHeaderAuth": {
          "id": "meta-whatsapp-token-cred",
          "name": "WhatsApp Cloud API Token"
        }
      }
    },
    {
      "parameters": {
        "channel": "#customer-retention-alerts",
        "text": "=🚨 *Low Rating Alert ({{ $('Parse Rating & Sentiment').item.json.rating }}/5 Stars)*\n*Customer*: {{ $('Parse Rating & Sentiment').item.json.customer_name }} ({{ $('Parse Rating & Sentiment').item.json.customer_phone }})\n*Appointment*: #{{ $('Parse Rating & Sentiment').item.json.appointment_id }}\n*Customer Note*: \"{{ $('Parse Rating & Sentiment').item.json.feedback_notes }}\"\n*Manager Protocol*: Please contact customer within 30 minutes for resolution.",
        "options": {}
      },
      "id": "appt-alert-manager",
      "name": "Slack - Alert Manager & Escalate",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2.2,
      "position": [940, 620],
      "credentials": {
        "slackApi": {
          "id": "slack-cred-placeholder",
          "name": "Slack Bot Account"
        }
      }
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { status: 'acknowledged', routed_to: $('Parse Rating & Sentiment').item.json.is_promoter ? 'google_review' : 'internal_escalation' } }}",
        "options": {}
      },
      "id": "appt-respond-webhook",
      "name": "Respond to Survey Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1220, 520]
    }
  ],
  "connections": {
    "Schedule Trigger - Hourly": {
      "main": [
        [
          {
            "node": "Postgres - Fetch Completed Appointments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Postgres - Fetch Completed Appointments": {
      "main": [
        [
          {
            "node": "WhatsApp - Dispatch 2h Followup Survey",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook - Inbound Customer Rating": {
      "main": [
        [
          {
            "node": "Parse Rating & Sentiment",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Rating & Sentiment": {
      "main": [
        [
          {
            "node": "Is High Rating (4-5 Stars)?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is High Rating (4-5 Stars)?": {
      "main": [
        [
          {
            "node": "WhatsApp - Send Google Review Link",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Slack - Alert Manager & Escalate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp - Send Google Review Link": {
      "main": [
        [
          {
            "node": "Respond to Survey Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Slack - Alert Manager & Escalate": {
      "main": [
        [
          {
            "node": "Respond to Survey Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}
