{
  "name": "Phase 3 - Follow-up Nudge",
  "nodes": [
    {
      "parameters": {},
      "id": "439c93be-b8f8-4c51-a582-acac2deef0f2",
      "name": "Manual Trigger",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        -260,
        300
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "7d81ca3f-717b-4075-a28e-c4c0aeb99d84",
              "name": "supabaseUrl",
              "value": "https://YOUR_PROJECT_REF.supabase.co",
              "type": "string"
            },
            {
              "id": "97787837-f7d3-46d3-8b9f-05a162e337e3",
              "name": "followUpAfterHours",
              "value": "0",
              "type": "string"
            },
            {
              "id": "2e118d42-bc96-4f05-b808-62ba2e166567",
              "name": "followUpMax",
              "value": "2",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "7f3b854e-96c2-4eb6-a02c-f9694fe59df0",
      "name": "Config",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -40,
        300
      ]
    },
    {
      "parameters": {
        "method": "GET",
        "url": "={{ $('Config').item.json.supabaseUrl + '/rest/v1/contacts?outreach_status=eq.message_sent&follow_up_count=lt.' + ($('Config').item.json.followUpMax || 2) + '&last_contacted_at=lt.' + $now.minus({ hours: Number($('Config').item.json.followUpAfterHours || 0) }).toUTC().toISO() + '&select=id,name,role,follow_up_count,school_id,schools(name,tier,board,city)' }}",
        "options": {},
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "supabaseApi"
      },
      "id": "4620f469-c2eb-423c-bfe2-dbfc686b05f7",
      "name": "Get Silent Contacts",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        180,
        300
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const out = [];\nfor (const item of items) {\n  const c = item.json;\n  const s = Array.isArray(c.schools) ? (c.schools[0] || {}) : (c.schools || {});\n  const userPrompt =\n    \"Write a brief, friendly LinkedIn follow-up to \" + (c.name || 'there') +\n    \", \" + (c.role || 'school leader') + \" at \" + (s.name || 'their school') +\n    \", who hasn't replied to your first message yet.\\n\" +\n    \"2-3 sentences, no pressure, add ONE small reason to engage and ONE soft ask. Do NOT paste any link. Return only the message.\";\n  out.push({ json: { contactId: c.id, name: c.name, userPrompt: userPrompt, nextFollowUp: (Number(c.follow_up_count)||0)+1 } });\n}\nreturn out;"
      },
      "id": "9e446489-2531-4ef6-a4f0-267afa9419d7",
      "name": "Build Nudge",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        400,
        300
      ]
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "GPT-4O-MINI"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "You write short, friendly LinkedIn FOLLOW-UP nudges from a partnerships lead at Learn with Leaders (LwL) to a school contact who hasn't replied to the first message yet. LwL brings student leadership and enrichment programs (World Leaders Academy, Edge Club, Future Doctors Fellowship, TEO Launchpad) to schools. Write ONE short nudge (2-3 sentences), warm and no-pressure, with one small reason to engage and one soft ask. Do NOT paste any link, do NOT hard-sell, do NOT invent facts. No 'Dear', no sign-off. Return ONLY the message text."
            },
            {
              "content": "={{ $json.userPrompt }}"
            }
          ]
        },
        "builtInTools": {},
        "options": {}
      },
      "id": "40f473c5-9c7e-483e-818b-892bc18c8439",
      "name": "Message a model",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.3,
      "position": [
        620,
        300
      ],
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const src = $('Build Nudge').all();\nfunction extractText(r){\n  if(r==null) return '';\n  if(typeof r==='string') return r;\n  if(Array.isArray(r.output)){let a='';for(const m of r.output){if(m&&Array.isArray(m.content)){for(const c of m.content){if(c&&typeof c.text==='string')a+=c.text;}}else if(typeof m==='string')a+=m;else if(m&&typeof m.text==='string')a+=m.text;}if(a)return a;}\n  if(typeof r.output_text==='string')return r.output_text;\n  if(typeof r.output==='string')return r.output;\n  if(typeof r.content==='string')return r.content;\n  if(typeof r.text==='string')return r.text;\n  if(r.message&&typeof r.message.content==='string')return r.message.content;\n  if(r.choices&&r.choices[0]&&r.choices[0].message&&typeof r.choices[0].message.content==='string')return r.choices[0].message.content;\n  if(Array.isArray(r.content))return r.content.map(b=>(b&&b.text)?b.text:'').join('');\n  return '';\n}\nconst out=[];\nfor(let i=0;i<items.length;i++){\n  const text=extractText(items[i].json).trim();\n  const c=(src[i]&&src[i].json)?src[i].json:{};\n  if(!text) continue;\n  out.push({json:{contactId:c.contactId,name:c.name,messageBody:text,nextFollowUp:c.nextFollowUp}});\n}\nreturn out;"
      },
      "id": "98174eda-acd2-45a1-bc15-85e9472ba13b",
      "name": "Extract Nudge",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        860,
        300
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Config').item.json.supabaseUrl + '/rest/v1/messages' }}",
        "options": {},
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "supabaseApi",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ { \"contact_id\": $json.contactId, \"direction\": \"outbound\", \"body\": $json.messageBody, \"source\": \"follow_up\" } }}"
      },
      "id": "800ecafb-bdaf-4a34-8e34-93fb550478ff",
      "name": "Insert Nudge",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        200
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    },
    {
      "parameters": {
        "method": "PATCH",
        "url": "={{ $('Config').item.json.supabaseUrl + '/rest/v1/contacts?id=eq.' + $json.contactId }}",
        "options": {},
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "supabaseApi",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Prefer",
              "value": "return=minimal"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ { \"outreach_status\": \"follow_up_sent\", \"follow_up_count\": $json.nextFollowUp, \"last_contacted_at\": $now.toISO() } }}"
      },
      "id": "26d94cdd-e4e7-4040-b389-7dd2fafefc40",
      "name": "Set Follow-up Sent",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1100,
        400
      ],
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "retryOnFail": true,
      "maxTries": 3,
      "waitBetweenTries": 2000
    }
  ],
  "connections": {
    "Manual Trigger": {
      "main": [
        [
          {
            "node": "Config",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Config": {
      "main": [
        [
          {
            "node": "Get Silent Contacts",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Silent Contacts": {
      "main": [
        [
          {
            "node": "Build Nudge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Nudge": {
      "main": [
        [
          {
            "node": "Message a model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message a model": {
      "main": [
        [
          {
            "node": "Extract Nudge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Nudge": {
      "main": [
        [
          {
            "node": "Insert Nudge",
            "type": "main",
            "index": 0
          },
          {
            "node": "Set Follow-up Sent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}