{
  "name": "n8n Workflow for Small Business With Local Review Replies",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "review-replies",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "cb4c03b1-2177-44b9-9624-a91b70d452df",
      "name": "New Review Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.2,
      "position": [0, 96]
    },
    {
      "parameters": {
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Business Rules"
        },
        "options": {}
      },
      "id": "de2a63b7-f9b2-419e-8b64-0aba264902e9",
      "name": "Get Business Rules",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [272, 224],
      "executeOnce": true
    },
    {
      "parameters": {
        "jsCode": "const body = $('New Review Webhook').first().json.body || {};\nconst rules = {};\nfor (const row of $('Get Business Rules').all()) {\n  const key = String(row.json.setting || '').trim();\n  if (key) rules[key] = String(row.json.value ?? '').trim();\n}\nconst list = (s) => String(s || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean);\n\nconst errors = [];\nconst rating = Number(body.rating);\nif (!Number.isInteger(rating) || rating < 1 || rating > 5) errors.push('rating must be a whole number from 1 to 5');\nif (!String(body.review_id || '').trim()) errors.push('review_id is required');\nif (!rules.business_name) errors.push('Business Rules sheet is missing business_name');\n\nconst text = String(body.review_text ?? body.text ?? '').replace(/\\s+/g, ' ').trim();\nconst reviewer = String(body.reviewer || '').trim() || 'there';\nconst lower = text.toLowerCase();\n\nconst maxRating = Number(rules.approval_rating_max || 3);\nconst keywordHits = list(rules.complaint_keywords).filter(k => lower.includes(k));\nconst ruleFlags = [];\nif (rating <= maxRating) ruleFlags.push('rating ' + rating + ' is ' + maxRating + ' stars or lower');\nif (keywordHits.length) ruleFlags.push('complaint words: ' + keywordHits.join(', '));\nif (!text) ruleFlags.push('rating only, no written review');\n\nreturn [{ json: {\n  valid: errors.length === 0,\n  errors,\n  review: {\n    platform: String(body.platform || 'google').toLowerCase(),\n    review_id: String(body.review_id || ''),\n    reviewer,\n    first_name: reviewer.split(' ')[0],\n    rating,\n    review_text: text,\n  },\n  rules: {\n    business_name: rules.business_name,\n    sign_off: rules.owner_sign_off || rules.business_name,\n    brand_voice: rules.brand_voice || 'Warm, brief and specific.',\n    complaint_contact: rules.complaint_contact || '',\n    banned_phrases: list(rules.banned_phrases),\n    sentiment_labels: list(rules.sentiment_labels || 'positive, neutral, mixed, negative'),\n    topic_labels: list(rules.topic_labels || 'service, food_quality, wait_time, other'),\n  },\n  ruleFlags,\n} }];"
      },
      "id": "0c47cd1c-e9e5-4407-aa61-01771a744b76",
      "name": "Validate and Apply Rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [496, 224]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "v1",
              "leftValue": "={{ $json.valid }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "befb9272-0336-4cdb-ae68-3149c87962fc",
      "name": "Valid Review?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [752, 96]
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "gemma4:12b-it-qat"
        },
        "messages": {
          "values": [
            {
              "content": "=Classify this customer review for {{ $json.rules.business_name }}.\n\nRating: {{ $json.review.rating }} of 5\nReview: \"{{ $json.review.review_text || \"(no written review)\" }}\"\n\nReturn JSON with exactly these keys:\n- \"sentiment\": one of {{ $json.rules.sentiment_labels.join(\", \") }}\n- \"topic\": the single best match from {{ $json.rules.topic_labels.join(\", \") }}\n- \"is_complaint\": true if the customer reports a problem they want fixed or acknowledged, else false\n- \"summary\": one sentence under 20 words describing what the customer said\n- \"customer_wording\": the most important phrase copied exactly from the review, or \"\" if there is no text"
            }
          ]
        },
        "options": {
          "system": "You label small-business customer reviews. Reply with one JSON object and nothing else.",
          "temperature": 0.1,
          "think": false,
          "num_ctx": 4096,
          "format": "json"
        }
      },
      "id": "de3327cd-7ac4-419d-bea3-debad33bb1bf",
      "name": "Ollama: Classify Review",
      "type": "@n8n/n8n-nodes-langchain.ollama",
      "typeVersion": 1,
      "position": [1024, 128]
    },
    {
      "parameters": {
        "jsCode": "const base = $('Validate and Apply Rules').first().json;\nconst j = $input.first().json;\nconst raw = String(j.content ?? j.response ?? j.text ?? j.message?.content ?? '');\nlet a = {};\ntry { a = JSON.parse(raw.replace(/^\\s*```(json)?/i, '').replace(/```\\s*$/, '')); } catch (e) { a = {}; }\n\nconst pick = (val, allowed, fallback) => {\n  const v = String(val || '').trim().toLowerCase().replace(/\\s+/g, '_');\n  return allowed.includes(v) ? v : fallback;\n};\nconst r = base.review;\nconst fallbackSentiment = r.rating >= 4 ? 'positive' : r.rating === 3 ? 'mixed' : 'negative';\nconst analysis = {\n  sentiment: pick(a.sentiment, base.rules.sentiment_labels, fallbackSentiment),\n  topic: pick(a.topic, base.rules.topic_labels, 'other'),\n  is_complaint: a.is_complaint === true || String(a.is_complaint).toLowerCase() === 'true',\n  summary: String(a.summary || '').trim().slice(0, 200),\n  customer_wording: String(a.customer_wording || '').trim().slice(0, 200),\n  parsed_ok: Object.keys(a).length > 0,\n};\nreturn [{ json: { ...base, analysis } }];"
      },
      "id": "a632be33-6b69-492f-a5cd-658ff7e97c06",
      "name": "Check Labels",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1376, 128]
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "gemma4:12b-it-qat"
        },
        "messages": {
          "values": [
            {
              "content": "=Write the public owner reply to this review.\n\nReviewer first name: {{ $json.review.first_name }}\nRating: {{ $json.review.rating }} of 5\nReview: \"{{ $json.review.review_text || \"(no written review)\" }}\"\nSentiment: {{ $json.analysis.sentiment }}. Topic: {{ $json.analysis.topic }}. Complaint: {{ $json.analysis.is_complaint }}\nKey customer wording: \"{{ $json.analysis.customer_wording }}\"\n\nRules:\n- Brand voice: {{ $json.rules.brand_voice }}\n- Respond to what this customer actually said; do not invent details about their visit.\n- {{ $json.analysis.is_complaint || $json.review.rating <= 3 ? \"Acknowledge the problem without excuses or blaming staff, and end with this exact line: \" + $json.rules.complaint_contact : \"Thank them warmly and invite them back.\" }}\n- Never offer refunds, discounts, free items or any compensation, and never admit legal fault.\n- Sign off as: {{ $json.rules.sign_off }}\n\nReturn only the reply text."
            }
          ]
        },
        "options": {
          "system": "=You write short, brand-safe public replies to customer reviews on behalf of {{ $json.rules.business_name }}. You never mention being an AI.",
          "temperature": 0.5,
          "think": false,
          "num_ctx": 4096
        }
      },
      "id": "67cc096c-6caa-435f-b09b-1035d053da44",
      "name": "Ollama: Draft Reply",
      "type": "@n8n/n8n-nodes-langchain.ollama",
      "typeVersion": 1,
      "position": [1600, 128]
    },
    {
      "parameters": {
        "jsCode": "const base = $('Check Labels').first().json;\nconst j = $input.first().json;\nconst reply = String(j.content ?? j.response ?? j.text ?? j.message?.content ?? '')\n  .replace(/^\\s*[\"']|[\"']\\s*$/g, '').trim();\n\nconst reasons = [...base.ruleFlags];\nif (base.analysis.is_complaint) reasons.push('model flagged a complaint');\nif (base.analysis.sentiment === 'negative') reasons.push('negative sentiment');\nif (!base.analysis.parsed_ok) reasons.push('classifier output was not valid JSON');\nconst lowerReply = reply.toLowerCase();\nconst banned = base.rules.banned_phrases.filter(p => lowerReply.includes(p));\nif (banned.length) reasons.push('draft uses banned phrases: ' + banned.join(', '));\nif (reply.length < 20) reasons.push('draft reply is empty or too short');\n\nconst r = base.review;\nreturn [{ json: {\n  received_at: new Date().toISOString(),\n  platform: r.platform,\n  review_id: r.review_id,\n  reviewer: r.reviewer,\n  rating: r.rating,\n  review_text: r.review_text,\n  sentiment: base.analysis.sentiment,\n  topic: base.analysis.topic,\n  is_complaint: base.analysis.is_complaint ? 'yes' : 'no',\n  summary: base.analysis.summary,\n  draft_reply: reply,\n  needs_approval: reasons.length > 0,\n  approval_reasons: [...new Set(reasons)].join('; '),\n} }];"
      },
      "id": "88d4e4d5-f6f6-4e4d-82f4-dea74c27487d",
      "name": "Approval Rules Check",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1552, 224]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "n1",
              "leftValue": "={{ $json.needs_approval }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "31309c84-f318-44bf-881c-cf263f079284",
      "name": "Needs Human Approval?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [1776, 224]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "s1",
              "name": "status",
              "value": "Needs Approval",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "0040007b-1ec6-41b6-85c2-c81732508477",
      "name": "Mark Needs Approval",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [2000, 128]
    },
    {
      "parameters": {
        "operation": "append",
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "YOUR_SPREADSHEET_ID"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Reviews"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "received_at": "={{ $json.received_at }}",
            "platform": "={{ $json.platform }}",
            "review_id": "={{ $json.review_id }}",
            "reviewer": "={{ $json.reviewer }}",
            "rating": "={{ $json.rating }}",
            "review_text": "={{ $json.review_text }}",
            "sentiment": "={{ $json.sentiment }}",
            "topic": "={{ $json.topic }}",
            "is_complaint": "={{ $json.is_complaint }}",
            "summary": "={{ $json.summary }}",
            "draft_reply": "={{ $json.draft_reply }}",
            "status": "={{ $json.status }}",
            "approval_reasons": "={{ $json.approval_reasons }}",
            "approved_by": "",
            "published_at": ""
          },
          "schema": [
            { "id": "received_at", "displayName": "received_at", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "platform", "displayName": "platform", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "review_id", "displayName": "review_id", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "reviewer", "displayName": "reviewer", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "rating", "displayName": "rating", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "review_text", "displayName": "review_text", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "sentiment", "displayName": "sentiment", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "topic", "displayName": "topic", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "is_complaint", "displayName": "is_complaint", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "summary", "displayName": "summary", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "draft_reply", "displayName": "draft_reply", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "status", "displayName": "status", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "approval_reasons", "displayName": "approval_reasons", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "approved_by", "displayName": "approved_by", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true },
            { "id": "published_at", "displayName": "published_at", "required": false, "defaultMatch": false, "display": true, "type": "string", "canBeUsedToMatch": true }
          ]
        },
        "options": {
          "cellFormat": "RAW"
        }
      },
      "id": "7b112eb2-c5ea-4028-9112-99104d417f7d",
      "name": "Save to Review Log",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4.7,
      "position": [2224, 224]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "s2",
              "name": "status",
              "value": "Draft - Routine",
              "type": "string"
            }
          ]
        },
        "includeOtherFields": true,
        "options": {}
      },
      "id": "39947002-34f0-403c-be3b-a51e21c11540",
      "name": "Mark Routine Draft",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [2000, 320]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ error: \"invalid review payload\", details: $json.errors }) }}",
        "options": {
          "responseCode": 400
        }
      },
      "id": "4d700f1e-e6d6-4735-94a5-c6b4dd1a352b",
      "name": "Reject Bad Payload",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [1008, 448]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ JSON.stringify({ review_id: $(\"Approval Rules Check\").first().json.review_id, status: $json.status, sentiment: $json.sentiment, topic: $json.topic, approval_reasons: $json.approval_reasons, draft_reply: $json.draft_reply }) }}",
        "options": {}
      },
      "id": "0361f787-cad2-46a7-b540-c7bdc377ffc6",
      "name": "Return Draft",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.5,
      "position": [2032, 0]
    },
    {
      "parameters": {
        "content": "## Local Review Replies\nPOST a review to the webhook:\n`{ platform, review_id, reviewer, rating, review_text }`\n\nRules live in the **Business Rules** tab. Every review is logged to **Reviews**; anything flagged lands in the **Approval Queue** tab. Nothing is published.\n\nAfter import: set YOUR_SPREADSHEET_ID on both Google Sheets nodes and pick your Google Sheets and Ollama credentials.",
        "height": 260,
        "width": 420,
        "color": 4
      },
      "id": "9c87cbef-1fd0-4f4d-ae90-bada324b246b",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [-48, -224]
    }
  ],
  "connections": {
    "New Review Webhook": { "main": [[{ "node": "Get Business Rules", "type": "main", "index": 0 }]] },
    "Get Business Rules": { "main": [[{ "node": "Validate and Apply Rules", "type": "main", "index": 0 }]] },
    "Validate and Apply Rules": { "main": [[{ "node": "Valid Review?", "type": "main", "index": 0 }]] },
    "Valid Review?": {
      "main": [
        [{ "node": "Ollama: Classify Review", "type": "main", "index": 0 }],
        [{ "node": "Reject Bad Payload", "type": "main", "index": 0 }]
      ]
    },
    "Ollama: Classify Review": { "main": [[{ "node": "Check Labels", "type": "main", "index": 0 }]] },
    "Check Labels": { "main": [[{ "node": "Ollama: Draft Reply", "type": "main", "index": 0 }]] },
    "Ollama: Draft Reply": { "main": [[{ "node": "Approval Rules Check", "type": "main", "index": 0 }]] },
    "Approval Rules Check": { "main": [[{ "node": "Needs Human Approval?", "type": "main", "index": 0 }]] },
    "Needs Human Approval?": {
      "main": [
        [{ "node": "Mark Needs Approval", "type": "main", "index": 0 }],
        [{ "node": "Mark Routine Draft", "type": "main", "index": 0 }]
      ]
    },
    "Mark Needs Approval": { "main": [[{ "node": "Save to Review Log", "type": "main", "index": 0 }]] },
    "Save to Review Log": { "main": [[{ "node": "Return Draft", "type": "main", "index": 0 }]] },
    "Mark Routine Draft": { "main": [[{ "node": "Save to Review Log", "type": "main", "index": 0 }]] }
  },
  "settings": {
    "executionOrder": "v1"
  }
}
