{
  "name": "WhatSync: appointment reminders",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "days",
              "triggerAtHour": 10
            }
          ]
        }
      },
      "name": "Every day at 10",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        0
      ],
      "id": "cddeb099-fea4-48c0-a504-14e8588e4b58"
    },
    {
      "parameters": {},
      "name": "Try it by hand",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        200
      ],
      "id": "555772b3-551c-4b82-a984-95b6e114f0a5"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "fd6d7546-de46-4a4c-a30f-03b89e5ef555",
              "name": "whatsyncUrl",
              "value": "https://whatsync.app",
              "type": "string"
            },
            {
              "id": "320651c8-09dd-4735-a7ab-d7d4d18592bd",
              "name": "businessName",
              "value": "Casa Luna",
              "type": "string"
            },
            {
              "id": "56411202-d6bf-468d-acd0-b60abb5b4220",
              "name": "timezone",
              "value": "Europe/Madrid",
              "type": "string"
            },
            {
              "id": "f14fe99a-4d05-46bb-ad87-4ee594cb9e99",
              "name": "appointmentsUrl",
              "value": "https://example.com/api/appointments",
              "type": "string"
            },
            {
              "id": "4ff803df-f861-49b4-a432-eb7f15b594e7",
              "name": "channel",
              "value": "business",
              "type": "string"
            },
            {
              "id": "0851f349-b2ea-4c97-a579-8f0b20df2a84",
              "name": "templateName",
              "value": "appointment_reminder",
              "type": "string"
            },
            {
              "id": "ce1b17f4-c24a-4330-aa0e-8527c1baf730",
              "name": "templateLanguage",
              "value": "en_US",
              "type": "string"
            },
            {
              "id": "06e34b19-3946-43cf-a332-851557025a81",
              "name": "alertUrl",
              "value": "https://hooks.slack.com/services/REPLACE/WITH/YOURS",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "name": "Settings",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        220,
        0
      ],
      "id": "82830192-37f1-40e6-ac46-fce238020abf",
      "notes": "channel: business sends your approved template (works for anyone who agreed). channel: qr sends plain text from a personal number: only for people that number already chats with."
    },
    {
      "parameters": {
        "method": "GET",
        "url": "={{ $json.appointmentsUrl }}",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "date",
              "value": "={{ $now.setZone($json.timezone).plus({ days: 1 }).toISODate() }}"
            }
          ]
        },
        "options": {
          "timeout": 15000
        }
      },
      "name": "Tomorrow's appointments",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        440,
        0
      ],
      "id": "885d3ca0-cce0-48f6-acf1-90246eafc53e",
      "notes": "Your own system. It must answer {\"appointments\": [{\"id\", \"name\", \"phone\", \"date\", \"time\", \"opted_in\"}]}."
    },
    {
      "parameters": {
        "jsCode": "// One item per person who agreed to reminders. The key is fixed per appointment and day,\n// so running this workflow twice on the same day can never remind anyone twice.\nconst settings = $('Settings').first().json;\nconst answer = $input.first().json;\nconst list = Array.isArray(answer) ? answer : (answer.appointments || []);\nconst items = [];\nfor (const a of list) {\n  if (a.opted_in !== true) continue; // no reminder without the person's yes\n  const phone = String(a.phone || '').replace(/\\D/g, '');\n  if (!/^\\d{7,15}$/.test(phone) || !a.id || !a.date || !a.time) continue;\n  const niceDate = new Date(a.date + 'T12:00:00Z').toLocaleDateString('en-GB', { weekday: 'long', day: 'numeric', month: 'long', timeZone: 'UTC' });\n  const body = settings.channel === 'business'\n    ? { channel: 'business', phoneNumber: phone, templateName: settings.templateName, templateLanguage: settings.templateLanguage,\n        templateParameters: [String(a.name || 'there'), niceDate, String(a.time)], recipientOptInConfirmed: true }\n    : { channel: 'qr', phoneNumber: phone, text: 'Hi ' + (a.name || 'there') + ', a reminder of your appointment with ' + settings.businessName + ' on ' + niceDate + ' at ' + a.time + '. Reply here if you need to change it.' };\n  items.push({ json: { appointment_id: String(a.id), name: a.name || '', phone, key: 'reminder-' + String(a.id).replace(/[^A-Za-z0-9._:-]/g, '-') + '-' + a.date, body } });\n}\nreturn items;\n"
      },
      "name": "Who gets a reminder",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        660,
        0
      ],
      "id": "6a1b41dd-3e1c-481d-a4e4-1101e89d52d5",
      "alwaysOutputData": false
    },
    {
      "parameters": {
        "workflowId": {
          "__rl": true,
          "value": "PICK_THE_SAFE_SEND_WORKFLOW",
          "mode": "list",
          "cachedResultName": "WhatSync: safe send"
        },
        "workflowInputs": {
          "mappingMode": "defineBelow",
          "value": {
            "tool": "send_message",
            "body": "={{ $json.body }}",
            "idempotencyKey": "={{ $json.key }}"
          },
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": true,
          "schema": [
            {
              "id": "tool",
              "displayName": "tool",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "string"
            },
            {
              "id": "body",
              "displayName": "body",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "object"
            },
            {
              "id": "idempotencyKey",
              "displayName": "idempotencyKey",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "canBeUsedToMatch": true,
              "type": "string"
            }
          ]
        },
        "mode": "each",
        "options": {
          "waitForSubWorkflow": true
        }
      },
      "name": "Send reminder",
      "type": "n8n-nodes-base.executeWorkflow",
      "typeVersion": 1.2,
      "position": [
        880,
        0
      ],
      "id": "39376e90-2f90-41da-a349-3e321363b20f"
    },
    {
      "parameters": {
        "jsCode": "// Counts what went out and lists what did not.\nconst planned = $('Who gets a reminder').all().map((item) => item.json);\nconst results = $input.all().map((item) => item.json);\nconst problems = [];\nresults.forEach((r, i) => {\n  const who = planned.find((p) => r.idempotency_key && r.idempotency_key.startsWith(p.key)) || planned[i] || {};\n  if (!r.ok) problems.push('• ' + (who.name || '') + ' +' + (who.phone || '?') + ': ' + r.outcome + ' (' + r.code + ') ' + String(r.message || '').slice(0, 160));\n});\nconst sent = results.filter((r) => r.ok).length;\nreturn [{ json: { sent, failed: problems.length,\n  text: 'Appointment reminders: ' + sent + ' sent, ' + problems.length + ' not sent.' + (problems.length ? '\\n' + problems.join('\\n') : '') } }];\n"
      },
      "name": "Summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1100,
        0
      ],
      "id": "b760b5a6-8edb-4ed6-a930-43afeb3bcfe0"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "960ec667-94e2-402a-aae2-766587578d99",
              "leftValue": "={{ $json.failed }}",
              "rightValue": 0,
              "operator": {
                "type": "number",
                "operation": "gt"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "name": "Any not sent?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1320,
        0
      ],
      "id": "1396b074-18d8-4e23-a283-e8339042e065"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings').first().json.alertUrl }}",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ text: $json.text }) }}",
        "options": {
          "timeout": 15000
        }
      },
      "name": "Alert: reminders not sent",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1540,
        -100
      ],
      "id": "feb69c21-50cc-40c7-a160-0b2c191d572a",
      "notes": "Works as is with a Slack incoming webhook. Swap this node for Email, Telegram or anything else that reaches a person."
    },
    {
      "parameters": {
        "content": "## WhatsApp appointment reminders\nEvery day at 10, read tomorrow's appointments from your own system and send each person who agreed a reminder. One reminder per appointment per day, even if the workflow runs twice.\n\n**Set up**\n1. Import **WhatSync: safe send** first and publish it. Pick it in **Send reminder**.\n2. Fill in **Settings**: the URL that lists tomorrow's appointments, your template name and language, the alert URL.\n3. On the WhatsApp Business API, get a template approved with three variables: name, date, time.\n4. Click **Execute workflow** to try it, then publish.\n\nOnly people with opted_in true get a message. Use the Business API for reminders to customers. A personal number is only for people it already chats with, and WhatSync holds back messages to strangers.\nGuide: https://whatsync.app/docs/guides/appointment-reminders",
        "height": 340,
        "width": 620,
        "color": 4
      },
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        -420
      ],
      "id": "54d73dd7-4945-4ea2-ac63-4e179229ff5d"
    }
  ],
  "connections": {
    "Every day at 10": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings": {
      "main": [
        [
          {
            "node": "Tomorrow's appointments",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tomorrow's appointments": {
      "main": [
        [
          {
            "node": "Who gets a reminder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Who gets a reminder": {
      "main": [
        [
          {
            "node": "Send reminder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send reminder": {
      "main": [
        [
          {
            "node": "Summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Summary": {
      "main": [
        [
          {
            "node": "Any not sent?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Try it by hand": {
      "main": [
        [
          {
            "node": "Settings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Any not sent?": {
      "main": [
        [
          {
            "node": "Alert: reminders not sent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "meta": {
    "templateCredsSetupCompleted": false
  }
}
