{
  "name": "TTC Online Enrollment: trial sign-up to GoHighLevel (webhook, validate, sibling-aware dedupe, score, upsert, trial opportunity, follow-up, teacher alert, dead-letter)",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "trial",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "ee3e603c-bfd1-4058-b764-693941874d5f",
      "name": "Trial Sign-up Webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "webhookId": "22505d2b-fccc-48dd-bc8b-da55e271f794"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "041d8bbd-031e-44c6-82f7-0681a4210f7b",
              "name": "ghlBase",
              "value": "https://services.leadconnectorhq.com",
              "type": "string"
            },
            {
              "id": "8d47e2ee-bd1d-4d0e-ba12-fe288769e73b",
              "name": "ghlToken",
              "value": "REPLACE_WITH_PRIVATE_INTEGRATION_TOKEN",
              "type": "string"
            },
            {
              "id": "a70a05bb-c803-44a8-87fd-9372e2181245",
              "name": "locationId",
              "value": "REPLACE_WITH_LOCATION_ID",
              "type": "string"
            },
            {
              "id": "b257a270-dba5-46c7-9a8a-a1b91314cc0b",
              "name": "pipelineId",
              "value": "REPLACE_WITH_PIPELINE_ID",
              "type": "string"
            },
            {
              "id": "83e7b499-b54c-4136-90c6-09a9a2554614",
              "name": "stageNewLeadId",
              "value": "REPLACE_WITH_TRIAL_STARTED_STAGE_ID",
              "type": "string"
            },
            {
              "id": "a63680d3-36b7-4961-9961-2323f88257fb",
              "name": "nurtureWorkflowId",
              "value": "REPLACE_WITH_TRIAL_FOLLOWUP_WORKFLOW_ID",
              "type": "string"
            },
            {
              "id": "1661e01f-eb0e-43f9-956c-c393133e9b95",
              "name": "alertWebhookUrl",
              "value": "REPLACE_WITH_SLACK_OR_DISCORD_WEBHOOK",
              "type": "string"
            },
            {
              "id": "609a23e3-2135-47a4-9828-ec0f43ad2df0",
              "name": "body",
              "value": "={{ $json.body }}",
              "type": "object"
            }
          ]
        },
        "options": {}
      },
      "id": "a10a3b06-0d0a-4455-bc08-5ecfd3105972",
      "name": "Config",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        220,
        300
      ]
    },
    {
      "parameters": {
        "jsCode": "// Validate + normalize a TTC Online trial sign-up (same fields and rules as the live form). Never trust the form.\nconst b = $input.first().json.body || {};\nconst GRADES = ['Preschool','Kinder','Grade 1','Grade 2','Grade 3','Grade 4','Grade 5','Grade 6']; // grades open for TTC Online\nconst errs = [];\nconst email = String(b.email || '').trim().toLowerCase();\nconst childName = String(b.childName || '').trim().replace(/\\s+/g, ' ');\nif (childName.split(' ').length < 2) errs.push(\"child's first and last name are required\");\nif (GRADES.indexOf(b.grade) < 0) errs.push('grade is not open for TTC Online');\nif (!String(b.parentName || '').trim()) errs.push('parent/guardian name is required');\nif (!/^[^\\s@]+@[^\\s@]+\\.[a-z]{2,}$/i.test(email)) errs.push('email is not valid');\nfunction phMobile(p) { const m = String(p || '').replace(/[^\\d+]/g, '').match(/^(?:\\+?63|0)?(9\\d{9})$/); return m ? '+63' + m[1] : ''; }\nconst phone = phMobile(b.phone);\nif (!phone) errs.push('a valid PH mobile number is required');\nif (b.agree !== true) errs.push('the parent must agree to the TTC Online terms');\nconst cap = (s) => String(s || '').split(/\\s+/).filter(Boolean).map((w) => w.charAt(0).toUpperCase() + w.slice(1).toLowerCase()).join(' ');\nconst parent = cap(String(b.parentName || '').trim()), pw = parent.split(' ');\nconst note = String(b.note || '').trim().slice(0, 500);\nconst needs = [['exam', /\\b(exam|test|quiz|review|periodical|quarterly)\\b/i], ['reading', /\\b(read|reading|basa|phonics|marungko)\\b/i], ['sses', /\\b(sses|special science)\\b/i]].filter((x) => x[1].test(note)).map((x) => x[0]);\nconst utm = Object.assign({ source: 'direct', medium: 'none', campaign: '' }, b.utm || {});\nreturn [{ json: {\n  valid: errs.length === 0, errors: errs,\n  idempotencyKey: String(b.idempotencyKey || ''),\n  parentName: parent, firstName: pw[0] || '', lastName: pw.slice(1).join(' '),\n  email, phone, childName: cap(childName), grade: b.grade, note, needs, utm, termsAccepted: b.agree === true,\n} }];"
      },
      "id": "1b9c7c01-3f0b-4622-8fad-6028e0b2c297",
      "name": "Validate & Normalize",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        300
      ]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.valid }}",
              "value2": true
            }
          ]
        }
      },
      "id": "9834c05e-2e90-4f50-b503-ef15a1d048a7",
      "name": "Is valid?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        660,
        300
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { ok: false, errors: $json.errors } }}",
        "options": {
          "responseCode": 400
        }
      },
      "id": "427709c1-0794-4040-95aa-64a6fb1584c3",
      "name": "Respond 400",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        880,
        480
      ]
    },
    {
      "parameters": {
        "jsCode": "// Idempotency + sibling-aware dedupe: one parent contact, one trial per child.\nconst store = $getWorkflowStaticData('global');\nstore.seen = store.seen || {}; store.kids = store.kids || {};\nconst now = Date.now();\nfor (const k of Object.keys(store.seen)) if (now - store.seen[k] > 7 * 864e5) delete store.seen[k];\nconst item = $input.first().json;\nconst key = item.idempotencyKey || (item.email + '|' + item.childName + '|' + item.utm.campaign);\nif (store.seen[key]) return [{ json: { ...item, duplicate: true, alreadyTrial: false } }];\nstore.seen[key] = now;\n// one free trial per child: the same child with the same parent email OR mobile (as the live form checks)\nconst child = item.childName.toLowerCase();\nconst kidKey = item.email + '|' + child, kidKeyPhone = item.phone + '|' + child;\nconst existingChild = !!(store.kids[kidKey] || store.kids[kidKeyPhone]);\nif (existingChild) return [{ json: { ...item, duplicate: true, alreadyTrial: true } }]; // stop here: nothing in the CRM is touched\nstore.kids[kidKey] = now; store.kids[kidKeyPhone] = now;\n// Score + segment (same rules as the demo)\nlet s = item.needs.includes('exam') ? 30 : (item.needs.includes('reading') || item.needs.includes('sses')) ? 25 : 15;\nif (item.note) s += 5;\nconst kind = { facebook: 'social', tiktok: 'social', messenger: 'social', youtube: 'social', google: 'search', referral: 'referral' }[item.utm.source] || 'social';\ns += { social: 10, search: 15, referral: 30 }[kind];\nif (item.phone) s += 10;\nif (item.grade === 'Grade 6') s += 5;\ns = Math.min(100, s);\nconst gi = ['Preschool','Kinder','Grade 1','Grade 2','Grade 3','Grade 4','Grade 5','Grade 6'].indexOf(item.grade);\nconst band = gi < 2 ? 'early-years' : gi < 5 ? 'primary' : 'intermediate';\nconst temp = s >= 70 ? 'hot' : s >= 45 ? 'warm' : 'cold';\nconst tags = ['ttc-online-trial', 'band:' + band].concat(item.needs.map((x) => 'need:' + x), ['temp:' + temp, 'src:' + item.utm.source, 'grade:' + item.grade.toLowerCase().replace(' ', '-')]);\nconst teacherAlert = item.needs.includes('sses') ? 'set up the SSES curriculum' : item.needs.includes('exam') ? 'exam review' : item.needs.includes('reading') ? 'reading help' : item.utm.source === 'referral' ? 'referral family' : '';\nreturn [{ json: { ...item, duplicate: false, dedupeKey: key, kidKey, kidKeyPhone, existingChild, score: s, band, temp, tags, teacherAlert } }];"
      },
      "id": "cda9d303-dbf0-4b10-bd01-b3569c1b16e4",
      "name": "Dedupe + Score",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        200
      ]
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $json.duplicate }}",
              "value2": true
            }
          ]
        }
      },
      "id": "119a968d-c80f-482c-b8db-ffa5a3d6988f",
      "name": "Duplicate?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1100,
        200
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json.alreadyTrial ? { ok: false, alreadyTrial: true, message: $json.childName + ' already used the free trial. Sign in with the details we sent to your email to subscribe.' } : { ok: true, duplicate: true } }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "28978a9c-84c1-4be4-96f6-1f1db3a54269",
      "name": "Respond 200 (replay or trial used)",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1320,
        60
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.ghlBase }}/contacts/upsert",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('Config').first().json.ghlToken }}"
            },
            {
              "name": "Version",
              "value": "2021-07-28"
            },
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({\n  locationId: $('Config').first().json.locationId,\n  firstName: $json.firstName, lastName: $json.lastName, email: $json.email,\n  phone: $json.phone || undefined,\n  source: 'TTC Online trial (' + $json.utm.source + ')',\n  customFields: [\n    { key: 'child_name', fieldValue: $json.childName },\n    { key: 'grade_level', fieldValue: $json.grade },\n    { key: 'needs', fieldValue: $json.needs.join(', ') },\n    { key: 'parent_message', fieldValue: $json.note },\n    { key: 'lead_score', fieldValue: $json.score },\n    { key: 'first_touch_source', fieldValue: $json.utm.source },\n    { key: 'first_touch_campaign', fieldValue: $json.utm.campaign },\n    { key: 'terms_accepted', fieldValue: $json.termsAccepted ? 'yes' : 'no' }\n  ]\n}) }}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "80c95432-8e9f-40ed-a879-d2447edff36e",
      "name": "GHL: Upsert contact",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1320,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.ghlBase }}/contacts/{{ $('GHL: Upsert contact').first().json.contact.id }}/tags",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('Config').first().json.ghlToken }}"
            },
            {
              "name": "Version",
              "value": "2021-07-28"
            },
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ tags: $('Dedupe + Score').first().json.tags }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "18b1f05d-b336-4e8a-8048-895d24da519f",
      "name": "GHL: Add tags",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1540,
        300
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "boolean": [
            {
              "value1": "={{ $('Dedupe + Score').first().json.existingChild }}",
              "value2": false
            }
          ]
        }
      },
      "id": "b9d97450-3dc2-4fc3-bdcd-33c8fbf34a76",
      "name": "New child?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1760,
        220
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.ghlBase }}/opportunities/",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('Config').first().json.ghlToken }}"
            },
            {
              "name": "Version",
              "value": "2021-07-28"
            },
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({\n  locationId: $('Config').first().json.locationId,\n  pipelineId: $('Config').first().json.pipelineId,\n  pipelineStageId: $('Config').first().json.stageNewLeadId,\n  contactId: $('GHL: Upsert contact').first().json.contact.id,\n  name: $('Dedupe + Score').first().json.childName + ' - ' + $('Dedupe + Score').first().json.grade + ' - TTC Online trial',\n  status: 'open',\n  source: $('Dedupe + Score').first().json.utm.source\n}) }}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "a917cc47-de50-42b0-a9c9-88e63dc2c24b",
      "name": "GHL: Create opportunity",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1980,
        120
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.ghlBase }}/contacts/{{ $('GHL: Upsert contact').first().json.contact.id }}/workflow/{{ $('Config').first().json.nurtureWorkflowId }}",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Authorization",
              "value": "=Bearer {{ $('Config').first().json.ghlToken }}"
            },
            {
              "name": "Version",
              "value": "2021-07-28"
            },
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ eventStartTime: $now.toISO() }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "id": "96f34975-2eb4-4268-967d-6f70b5f7ccf4",
      "name": "GHL: Start trial follow-up",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2200,
        220
      ],
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000,
      "onError": "continueErrorOutput"
    },
    {
      "parameters": {
        "conditions": {
          "string": [
            {
              "value1": "={{ $('Dedupe + Score').first().json.teacherAlert }}",
              "operation": "isNotEmpty"
            }
          ]
        }
      },
      "id": "87094003-413f-4001-8ff4-896fb782ebc0",
      "name": "Teacher alert?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        2420,
        220
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.alertWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: 'New TTC Online trial: ' + $('Dedupe + Score').first().json.childName + ' (' + $('Dedupe + Score').first().json.grade + '), ' + $('Dedupe + Score').first().json.teacherAlert + '. Parent: ' + $('Dedupe + Score').first().json.parentName + ($('Dedupe + Score').first().json.note ? '. Message: \"' + $('Dedupe + Score').first().json.note + '\"' : '') + '. Check in within the day.' }) }}",
        "options": {
          "timeout": 10000
        }
      },
      "id": "d7ceb971-93e8-46a8-9546-f779f2a8cd62",
      "name": "Alert teacher on duty",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2640,
        120
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { ok: true, contactId: $('GHL: Upsert contact').first().json.contact.id, newParent: $('GHL: Upsert contact').first().json.new, child: $('Dedupe + Score').first().json.childName, newChild: !$('Dedupe + Score').first().json.existingChild, score: $('Dedupe + Score').first().json.score } }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "1cafe8c7-2f5b-4c0a-9a1b-794e5b4b3e85",
      "name": "Respond 200",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2860,
        220
      ]
    },
    {
      "parameters": {
        "jsCode": "// Dead-letter: keep the full payload so nothing is lost, release the idempotency key so a replay can succeed.\nconst store = $getWorkflowStaticData('global');\nstore.dlq = store.dlq || [];\nconst lead = $('Dedupe + Score').first().json;\nconst err = $input.first().json.error || $input.first().json;\nstore.dlq.push({ at: new Date().toISOString(), lead, error: typeof err === 'string' ? err : (err.message || JSON.stringify(err).slice(0, 500)) });\nif (store.seen && lead.dedupeKey) delete store.seen[lead.dedupeKey];\nif (store.kids && lead.kidKey && !lead.existingChild) { delete store.kids[lead.kidKey]; delete store.kids[lead.kidKeyPhone]; }\nreturn [{ json: { deadLettered: true, email: lead.email, queueSize: store.dlq.length, error: store.dlq[store.dlq.length - 1].error } }];"
      },
      "id": "ccc09d93-3781-4ee4-bcbf-f33a2e0c8728",
      "name": "Dead-letter queue",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1980,
        520
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').first().json.alertWebhookUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: 'GHL call failed after 3 tries for ' + $json.email + '. Saved to dead-letter queue (' + $json.queueSize + ' waiting). Error: ' + $json.error }) }}",
        "options": {
          "timeout": 10000
        }
      },
      "id": "77792fde-0098-47a1-863b-900d15e5379c",
      "name": "Alert ops (CRM failure)",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        2200,
        520
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ { ok: true, queued: true, note: 'Saved. We will finish setting up the account shortly.' } }}",
        "options": {
          "responseCode": 202
        }
      },
      "id": "fee855aa-ed65-42f2-8a53-e738f293e35e",
      "name": "Respond 202 (queued)",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2420,
        520
      ]
    }
  ],
  "connections": {
    "Trial Sign-up Webhook": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Validate & Normalize",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate & Normalize": {
      "main": [
        [
          {
            "node": "Is valid?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Is valid?": {
      "main": [
        [
          {
            "node": "Dedupe + Score",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond 400",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dedupe + Score": {
      "main": [
        [
          {
            "node": "Duplicate?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Duplicate?": {
      "main": [
        [
          {
            "node": "Respond 200 (replay or trial used)",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "GHL: Upsert contact",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GHL: Upsert contact": {
      "main": [
        [
          {
            "node": "GHL: Add tags",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Dead-letter queue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GHL: Add tags": {
      "main": [
        [
          {
            "node": "New child?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Dead-letter queue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "New child?": {
      "main": [
        [
          {
            "node": "GHL: Create opportunity",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond 200",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GHL: Create opportunity": {
      "main": [
        [
          {
            "node": "GHL: Start trial follow-up",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Dead-letter queue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GHL: Start trial follow-up": {
      "main": [
        [
          {
            "node": "Teacher alert?",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Dead-letter queue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Teacher alert?": {
      "main": [
        [
          {
            "node": "Alert teacher on duty",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Respond 200",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert teacher on duty": {
      "main": [
        [
          {
            "node": "Respond 200",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Dead-letter queue": {
      "main": [
        [
          {
            "node": "Alert ops (CRM failure)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Alert ops (CRM failure)": {
      "main": [
        [
          {
            "node": "Respond 202 (queued)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "saveDataErrorExecution": "all",
    "saveDataSuccessExecution": "all"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "tags": []
}
