End-to-end example: reminder service

A complete appointment-reminder service in one file, in Python or Node.js.

A complete reminder service, in one file
Schedule, cancel, track, and handle replies, with OAuth tokens, safe retries, at-most-once sends, and a reconciliation job already wired in. Run it, then make it yours.
PythonNode.js~300 lines

The use-case guides show one feature at a time. This page is the whole thing: a small, complete appointment reminder service you can run as-is, then adapt. One file, no framework beyond a web server and SQLite, every production concern handled in the simplest way that's still correct.

When to use this guide

Use it when…Use something else when…
You want a working starting point with tokens, retries, webhooks, and reconciliation already handled.You're learning one feature at a time → the individual use case guides, starting with Appointment reminders
You just want to send a first text → Quickstart

What it does

  • POST /appointments: records consent, upserts the contact in EZ Texting, stores the appointment, and schedules a reminder 24 hours before (with sendAt).
  • DELETE /appointments/{id}: cancels the pending reminder.
  • GET /appointments/{id}: returns the appointment and the reminder's delivery report.
  • POST /webhooks/eztexting: verifies the signature, stores the event, acknowledges, then processes, matching a reply to its reminder by the message ID it carries: C confirms, R flags for rescheduling, STOP is recorded.
  • POST /admin/reconcile: resolves sends whose outcome was unknown by looking them up, never by resending.

Under the hood: OAuth 2.0 tokens created once and refreshed, retries only where EZ Texting has confirmed nothing was accepted, an at-most-once-per-key send table, and redacted diagnostics.


Run it

  1. Set credentials:
export EZTEXTING_USERNAME="[email protected]"
export EZTEXTING_PASSWORD="your-password"
export EZTEXTING_WEBHOOK_SECRET="$(openssl rand -hex 32)"
# your service's own token for every endpoint except the webhook
export APP_API_TOKEN="$(openssl rand -hex 32)"
  1. Start the service (pick a language below), then expose it for webhooks during development:
ngrok http 3000

Only /webhooks/eztexting is public, and it checks EZ Texting's signature. Every other endpoint requires Authorization: Bearer $APP_API_TOKEN, so the tunnel exposes nothing else.

  1. Subscribe the webhook once, using the tunnel URL and the same secret:
curl -X POST https://a.eztexting.com/v1/webhooks/subscriptions \
  -u "$EZTEXTING_USERNAME:$EZTEXTING_PASSWORD" \
  -H "Content-Type: application/json" \
  -d "{\"type\": \"inbound_text.received\", \"callbackUrl\": \"https://a1b2c3d4.ngrok.app/webhooks/eztexting\", \"secret\": \"$EZTEXTING_WEBHOOK_SECRET\"}"
  1. Book an appointment for your own phone, with a start time more than 24 hours out. smsConsent is the record that the person agreed to reminders when they booked. The service schedules a text only when it is the JSON boolean true; anything else gets a 400:
curl -X POST http://localhost:3000/appointments \
  -H "Authorization: Bearer $APP_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"bookingId": "bk-1001", "phone": "(555) 123-4567", "firstName": "Jane", "service": "cleaning", "startsAt": "2027-11-19T09:00:00-08:00", "smsConsent": true}'
# → {"id": 1, "phone": "15551234567", "reminder": "scheduled"}

reminder says what happened to the text:

  • scheduled: EZ Texting accepted it.
  • unknown: the request timed out or failed in a way that may still have queued it. The response is 202, and POST /admin/reconcile settles it.
  • failed: EZ Texting rejected the send.
  • not_scheduled: no reminder was scheduled, for example because the reminder time has already passed (reason says so).

bookingId is your own system's ID for the booking. Sending the same request again (a retry, a double-click) returns the same appointment and schedules no second reminder; a different bookingId for the same phone is a separate appointment.

The reminder is now queued in EZ Texting (GET /v1/campaign-info shows it). Every call to the service carries the same Authorization header. Cancel it with DELETE /appointments/1, or wait for it, reply C, and watch GET /appointments/1 flip to confirmed. A reply counts only if it's exactly C or R (any case); anything else leaves the appointment as it is. If EZ Texting can't confirm a cancellation, DELETE /appointments/1 returns 502 and keeps the reminder ID so you can try again. If the reminder's outcome is still unknown, it returns 202 with status cancel_pending, and the next reconcile finishes the job: it cancels the reminder if it's still scheduled (reminderCancelled), or marks the appointment cancelled and lists it under reminderAlreadySent if the text already went out, so staff know the customer got it. A reminder that has already gone out is left alone: deleting it wouldn't unsend it, only remove it from the account's message history.


Design decisions

Which failures get retried. A 429 means EZ Texting did not accept the request, so the client waits and retries. A 5xx or a timeout on a read, an upsert, or a delete is retried with backoff because repeating those is harmless. A 5xx or timeout on POST /v1/messages is ambiguous (the message may already be queued), so the client raises AmbiguousOutcome, the send row is marked unknown, and nothing is retried. Errors explains the reasoning.

How an unknown send gets resolved. POST /admin/reconcile lists sends that are unknown (or pending for more than two minutes, which means a crash between the API call and the database write), and looks each one up with GET /v1/messages filtered by recipient and time. If a matching outbound message exists, the row is marked sent with its ID. A scheduled send isn't in that list until it goes out, so for a send scheduled in the future it also checks GET /v1/campaign-info for sends scheduled around that day and GET /v1/message-details/{id} for each one's recipient. Exactly one match counts; none, or two sends to the same number that day, and the key is reported as unresolved and a person decides. If the appointment was cancelled while the reminder was unknown, a reminder found still scheduled is cancelled (reminderCancelled); one that already went out is listed under reminderAlreadySent. The job never sends.

Which appointment a reply belongs to. One phone number can have several appointments booked. When the webhook carries the reminder's message ID in id, the reply goes to that appointment. Without it, a C or R is applied only if exactly one booked appointment for that number has had its reminder go out; otherwise the service texts back asking the person to call the office, rather than guessing. If you need stronger matching, put a reply code in the reminder (Reply C2 to confirm) and parse it.


The code

"""
Appointment reminder service on the EZ Texting API — single-file reference implementation.

    pip install flask requests
    export EZTEXTING_USERNAME=... EZTEXTING_PASSWORD=... EZTEXTING_WEBHOOK_SECRET=... APP_API_TOKEN=...
    python reminders.py

Endpoints:
    POST   /appointments            create an appointment → schedules a reminder 24h before
    DELETE /appointments/<id>       cancel → deletes the pending reminder
    GET    /appointments/<id>       status, including the reminder's delivery report
    POST   /webhooks/eztexting      inbound texts: C = confirm, R = reschedule
    POST   /admin/reconcile         resolve sends whose outcome was unknown (no automatic resend)

Only /webhooks/eztexting is public; it checks EZ Texting's signature. Every other endpoint
requires `Authorization: Bearer <APP_API_TOKEN>`.
"""
import base64, hashlib, hmac, json, os, sqlite3, threading, time
from datetime import datetime, timedelta, timezone

import requests
from flask import Flask, abort, jsonify, request

BASE = os.environ.get("EZTEXTING_BASE_URL", "https://a.eztexting.com")
COMPANY = "Harbor Dental"
WEBHOOK_SECRET = os.environ["EZTEXTING_WEBHOOK_SECRET"].encode()
# your app's own token for the appointment and admin endpoints
APP_API_TOKEN = os.environ["APP_API_TOKEN"]


class AmbiguousOutcome(Exception):
    """The request may or may not have been accepted (timeout or 5xx on a non-idempotent call)."""


# ---------------------------------------------------------------------------
# 1. API client: OAuth2 tokens (create once, refresh before expiry) + retry rules
#    - 429: never accepted → wait the server-specified time and retry
#    - 5xx / timeout on an idempotent call (GET, upsert, DELETE): retry with backoff
#    - 5xx / timeout on POST /v1/messages: AMBIGUOUS → raise, caller records 'unknown'
# ---------------------------------------------------------------------------
class EzTexting:
    def __init__(self):
        self._lock = threading.Lock()
        self._access = self._refresh = None
        self._expires_at = 0

    def _login(self):
        r = requests.post(f"{BASE}/v1/tokens/create", json={
            "appKey": os.environ["EZTEXTING_USERNAME"],
            "appSecret": os.environ["EZTEXTING_PASSWORD"]}, timeout=30)
        r.raise_for_status(); self._store(r.json())

    def _refresh_tokens(self):
        r = requests.post(f"{BASE}/v1/tokens/refresh", json={"refreshToken": self._refresh}, timeout=30)
        # refresh token expired/revoked → log in again
        if r.status_code == 401:
            return self._login()
        r.raise_for_status(); self._store(r.json())

    def _store(self, t):
        self._access, self._refresh = t["accessToken"], t["refreshToken"]
        # refresh 5 min early
        self._expires_at = time.time() + t["expiresInSeconds"] - 300

    def _token(self):
        with self._lock:
            if not self._access:
                self._login()
            elif time.time() >= self._expires_at:
                self._refresh_tokens()
            return self._access

    def request(self, method, path, *, idempotent, **kw):
        for attempt in range(5):
            try:
                r = requests.request(method, BASE + path, timeout=30,
                                     headers={"Authorization": f"Bearer {self._token()}"}, **kw)
            except requests.RequestException:
                if idempotent and attempt < 4:
                    time.sleep(2 ** attempt); continue
                raise AmbiguousOutcome()
            if r.status_code == 401 and attempt == 0:
                with self._lock: self._refresh_tokens()
                continue
            # confirmed not accepted
            if r.status_code == 429:
                time.sleep(int(r.headers.get("X-Rate-Limit-Retry-After-Milliseconds", 1000)) / 1000)
                continue
            if r.status_code >= 500:
                if idempotent and attempt < 4:
                    time.sleep(2 ** attempt); continue
                raise AmbiguousOutcome()
            return r
        raise AmbiguousOutcome()

ez = EzTexting()

# ---------------------------------------------------------------------------
# 2. Storage: appointments, an at-most-once table for sends, and a webhook inbox
# ---------------------------------------------------------------------------
db = sqlite3.connect(os.environ.get("REMINDERS_DB", "reminders.db"), check_same_thread=False, isolation_level=None)
db.execute("""CREATE TABLE IF NOT EXISTS appointments (
    id INTEGER PRIMARY KEY, booking_id TEXT UNIQUE, phone TEXT, first_name TEXT, service TEXT, starts_at TEXT,
    status TEXT DEFAULT 'booked', reminder_message_id TEXT, reminder_sent_at TEXT)""")
db.execute("""CREATE TABLE IF NOT EXISTS sms_sends (
    key TEXT PRIMARY KEY, status TEXT, message_id TEXT, payload TEXT, created_at REAL)""")
db.execute("""CREATE TABLE IF NOT EXISTS webhook_events (
    id INTEGER PRIMARY KEY AUTOINCREMENT, reply_to TEXT, body TEXT, received_at REAL, processed INTEGER DEFAULT 0)""")

def normalize(raw):
    digits = "".join(ch for ch in raw if ch.isdigit())
    if len(digits) == 10: digits = "1" + digits
    return digits if len(digits) == 11 and digits[0] == "1" else None

def parse_ts(s):
    return datetime.fromisoformat(s.replace("Z", "+00:00"))

def reminder_state(appt_id):
    """scheduled, unknown (outcome not known yet), failed, or not_scheduled"""
    row = db.execute("SELECT status FROM sms_sends WHERE key=?", (f"appt:{appt_id}:reminder",)).fetchone()
    if not row:
        return "not_scheduled"
    return {"sent": "scheduled", "failed": "failed"}.get(row[0], "unknown")

def send_once(key, payload):
    """At most one send per key. Returns the message id, None if the key was already claimed,
    or raises AmbiguousOutcome — in which case the row is left as 'unknown' for reconciliation.
    Never retries a send whose outcome is unknown."""
    try:
        db.execute("INSERT INTO sms_sends (key, status, payload, created_at) VALUES (?, 'pending', ?, ?)",
                   (key, json.dumps(payload), time.time()))
    except sqlite3.IntegrityError:
        # already sent, failed, or in flight
        return None
    try:
        r = ez.request("POST", "/v1/messages", idempotent=False, json=payload)
    except AmbiguousOutcome:
        db.execute("UPDATE sms_sends SET status='unknown' WHERE key=?", (key,))
        raise
    if r.status_code == 201:
        mid = r.json()["id"]
        db.execute("UPDATE sms_sends SET status='sent', message_id=? WHERE key=?", (mid, key))
        return mid
    # 4xx: confirmed not sent
    db.execute("UPDATE sms_sends SET status='failed' WHERE key=?", (key,))
    raise RuntimeError(f"EZ Texting {r.status_code}: {r.text}")

# ---------------------------------------------------------------------------
# 3. HTTP API for your app
# ---------------------------------------------------------------------------
app = Flask(__name__)

@app.before_request
def require_app_token():
    # The webhook is public and checks EZ Texting's signature itself. Everything else is your app's
    # own API and needs your token, so exposing the port for webhooks doesn't expose it.
    if request.path == "/webhooks/eztexting":
        return None
    if not hmac.compare_digest(request.headers.get("Authorization", ""), f"Bearer {APP_API_TOKEN}"):
        abort(401)

def booking_response(appt_id, phone, reason=None):
    """Every booking response says what happened to the reminder."""
    state = reminder_state(appt_id)
    body = {"id": appt_id, "phone": phone, "reminder": state}
    if state == "unknown":
        body["reason"] = "reminder outcome unknown; will reconcile"
    elif reason:
        body["reason"] = reason
    return jsonify(body), 202 if state == "unknown" else 201

@app.post("/appointments")
def create_appointment():
    body = request.get_json()
    # your system's stable ID for this booking: a retried request reuses it, so it can't book twice
    booking_id = body.get("bookingId")
    if not booking_id:
        return jsonify(error="bookingId is required"), 400
    phone = normalize(body["phone"])
    if not phone:
        return jsonify(error="invalid phone"), 400
    # recorded at booking, never assumed: only the JSON boolean true counts
    if body.get("smsConsent") is not True:
        return jsonify(error="smsConsent must be true (a JSON boolean) to schedule a text reminder"), 400
    # must include an offset, e.g. 2026-11-21T09:00:00-08:00
    starts_at = datetime.fromisoformat(body["startsAt"])
    if starts_at.tzinfo is None:
        return jsonify(error="startsAt needs a UTC offset"), 400

    # Keep the contact in EZ Texting in sync (idempotent upsert by phone number)
    ez.request("POST", "/v1/contacts", idempotent=True, json={"phoneNumber": phone, "firstName": body["firstName"]})

    # one appointment per booking ID; a retry finds the existing row
    cur = db.execute("INSERT OR IGNORE INTO appointments (booking_id, phone, first_name, service, starts_at) VALUES (?,?,?,?,?)",
                     (booking_id, phone, body["firstName"], body["service"], starts_at.isoformat()))
    appt_id = db.execute("SELECT id FROM appointments WHERE booking_id=?", (booking_id,)).fetchone()[0]
    # a retry after a send was attempted: report that result instead of sending again
    if cur.rowcount == 0 and reminder_state(appt_id) != "not_scheduled":
        return booking_response(appt_id, phone)

    send_at = starts_at - timedelta(hours=24)
    # quiet hours: confirm the window for your jurisdictions
    if send_at.hour < 8: send_at = send_at.replace(hour=8, minute=0)
    # only schedule future reminders
    if send_at <= datetime.now(timezone.utc):
        return booking_response(appt_id, phone, reason="the reminder time has already passed")
    try:
        mid = send_once(f"appt:{appt_id}:reminder", {
            "toNumbers": [phone],
            "companyName": COMPANY,
            "message": (f"Reminder: your {body['service']} is tomorrow, {starts_at:%b %-d at %-I:%M %p}. "
                        "Reply C to confirm or R to reschedule. Reply STOP to opt out."),
            "sendAt": send_at.isoformat(),
            "strictValidation": True,
        })
    except AmbiguousOutcome:
        # recorded as 'unknown'; /admin/reconcile resolves it
        mid = None
    except RuntimeError as e:
        # confirmed not sent, e.g. a 400 because the number opted out or the account is out of credits
        return booking_response(appt_id, phone, reason=str(e))
    if mid:
        db.execute("UPDATE appointments SET reminder_message_id=?, reminder_sent_at=? WHERE id=?",
                   (mid, send_at.isoformat(), appt_id))
    return booking_response(appt_id, phone)

def cancel_reminder(appt_id):
    """Cancel the appointment, deleting its reminder if it hasn't gone out. Returns an error, or None."""
    row = db.execute("SELECT reminder_message_id, reminder_sent_at FROM appointments WHERE id=?", (appt_id,)).fetchone()
    # Only a reminder that hasn't gone out yet is deleted. Deleting one that was already sent
    # wouldn't unsend it; it would only remove it from the account's message history.
    if row[0] and row[1] and parse_ts(row[1]) > datetime.now(timezone.utc):
        # keep the reminder ID unless EZ Texting confirms the cancellation
        try:
            r = ez.request("DELETE", "/v1/messages", idempotent=True, json={"ids": [row[0]]})
        except AmbiguousOutcome:
            return "reminder cancellation outcome unknown; try again"
        if not r.ok:
            return f"reminder not cancelled: EZ Texting {r.status_code}: {r.text}"
        db.execute("UPDATE appointments SET reminder_message_id=NULL WHERE id=?", (appt_id,))
    db.execute("UPDATE appointments SET status='cancelled' WHERE id=?", (appt_id,))
    return None

@app.delete("/appointments/<int:appt_id>")
def cancel_appointment(appt_id):
    row = db.execute("SELECT reminder_message_id FROM appointments WHERE id=?", (appt_id,)).fetchone()
    if not row: abort(404)
    # The reminder may or may not exist yet, so there's nothing to delete: record the request.
    # /admin/reconcile finishes the cancellation once the reminder's outcome is known.
    if reminder_state(appt_id) == "unknown":
        db.execute("UPDATE appointments SET status='cancel_pending' WHERE id=?", (appt_id,))
        return jsonify(status="cancel_pending", reason="reminder outcome unknown; /admin/reconcile cancels it if it is still scheduled"), 202
    error = cancel_reminder(appt_id)
    if error:
        return jsonify(error=error, reminderMessageId=row[0]), 502
    return "", 204

@app.get("/appointments/<int:appt_id>")
def appointment_status(appt_id):
    row = db.execute("SELECT phone, status, reminder_message_id FROM appointments WHERE id=?", (appt_id,)).fetchone()
    if not row: abort(404)
    delivery = None
    if row[2]:
        r = ez.request("GET", f"/v1/message-reports/{row[2]}", idempotent=True)
        delivery = r.json().get("delivery") if r.ok else None
    return jsonify(phone=row[0], status=row[1], reminder=reminder_state(appt_id), reminderMessageId=row[2], reminderDelivery=delivery)

# ---------------------------------------------------------------------------
# 4. Webhook: verify raw bytes → store → 2xx → process afterwards
#    (subscribe once: POST /v1/webhooks/subscriptions)
# ---------------------------------------------------------------------------
@app.post("/webhooks/eztexting")
def inbound():
    raw = request.get_data()
    expected = base64.b64encode(hmac.new(WEBHOOK_SECRET, raw, hashlib.sha256).digest()).decode()
    if not hmac.compare_digest(expected, request.headers.get("X-Signature-256", "")):
        app.logger.warning("webhook signature mismatch: %d bytes, sha256=%s",
                           # diagnostics without the payload
                           len(raw), hashlib.sha256(raw).hexdigest()[:12])
        abort(401)
    event = json.loads(raw)
    # Inbound texts have no unique ID. `id`, when present, is the send this text replies to
    # (within 12 hours), so it's kept as reply_to, not used as a key.
    cur = db.execute("INSERT INTO webhook_events (reply_to, body, received_at) VALUES (?, ?, ?)",
                     (event.get("id"), raw.decode(), time.time()))
    # or a real queue
    threading.Thread(target=process_event, args=(cur.lastrowid,), daemon=True).start()
    return "", 204

def process_event(event_id):
    row = db.execute("SELECT body FROM webhook_events WHERE id=? AND processed=0", (event_id,)).fetchone()
    if not row: return
    event = json.loads(row[0])
    if event.get("type") == "inbound_text.received":
        handle_reply(event_id, event)
    db.execute("UPDATE webhook_events SET processed=1 WHERE id=?", (event_id,))

def handle_reply(event_id, event):
    phone, text = event["fromNumber"], (event.get("message") or "").strip().upper()
    # EZ Texting already blocked future sends
    if event.get("optOut"):
        db.execute("UPDATE appointments SET status='opted_out' WHERE phone=? AND status='booked'", (phone,))
        return
    if text not in ("C", "R"):
        return
    # A reply carries the reminder's message ID in `id` when there is one: use it.
    appt_id = None
    if event.get("id"):
        hit = db.execute("SELECT id FROM appointments WHERE reminder_message_id=?", (event["id"],)).fetchone()
        appt_id = hit[0] if hit else None
    if appt_id is None:
        # No ID: only a booking whose reminder has already gone out can be the one they mean
        # (reminder_sent_at is the scheduled time, so a future one hasn't been seen yet).
        now = datetime.now(timezone.utc)
        seen = [i for i, at in db.execute("""SELECT id, reminder_sent_at FROM appointments
                                             WHERE phone=? AND status='booked' AND reminder_sent_at IS NOT NULL""", (phone,))
                if parse_ts(at) <= now]
        if len(seen) != 1:
            # none or several: don't guess, ask
            send_once(f"reply:{event_id}:unclear", {"toNumbers": [phone], "companyName": COMPANY,
                      "message": "Sorry, we couldn't tell which appointment you mean. Please call the office to confirm or reschedule."})
            return
        appt_id = seen[0]
    if text == "C":
        db.execute("UPDATE appointments SET status='confirmed' WHERE id=?", (appt_id,))
        send_once(f"appt:{appt_id}:confirm-ack", {"toNumbers": [phone], "companyName": COMPANY,
                  "message": "Thanks, you're confirmed. See you then!"})
    else:
        db.execute("UPDATE appointments SET status='reschedule_requested' WHERE id=?", (appt_id,))
        send_once(f"appt:{appt_id}:resched-ack", {"toNumbers": [phone], "companyName": COMPANY,
                  "message": "No problem — we'll call you shortly to find a new time."})

# ---------------------------------------------------------------------------
# 5. Reconciliation: resolve 'unknown' / stale 'pending' sends by LOOKING, never by resending
# ---------------------------------------------------------------------------
def find_scheduled(phone, send_at):
    """A scheduled send isn't in GET /v1/messages until it goes out. campaign-info lists
    scheduled sends by day (IDs only), and message-details gives each one's recipients.
    Returns the one unlinked send scheduled to this phone around send_at, or None."""
    day = parse_ts(send_at).astimezone(timezone.utc)
    # the day filter's time zone isn't specified, so include a day either side
    params = {"filters[sentAt][gte]": (day - timedelta(days=1)).strftime("%m-%d-%Y"),
              "filters[sentAt][lte]": (day + timedelta(days=1)).strftime("%m-%d-%Y"), "size": 200}
    known = {row[0] for row in db.execute("SELECT message_id FROM sms_sends WHERE message_id IS NOT NULL")}
    found, page = [], 0
    while True:
        r = ez.request("GET", "/v1/campaign-info", idempotent=True, params={**params, "page": page})
        rows = r.json().get("content", []) if r.ok else []
        for row in rows:
            mid = str(row["id"])
            if mid in known:
                continue
            d = ez.request("GET", f"/v1/message-details/{mid}", idempotent=True)
            if d.ok and any(c.get("phoneNumber", "")[-10:] == phone[-10:] for c in d.json().get("contacts", [])):
                found.append(mid)
        if len(rows) < 200:
            break
        page += 1
    # two scheduled sends to the same number in that window can't be told apart: leave it to a person
    return found[0] if len(found) == 1 else None

@app.post("/admin/reconcile")
def reconcile():
    resolved, unresolved, cancelled, already_sent = [], [], [], []
    rows = db.execute("""SELECT key, payload, created_at FROM sms_sends
                         WHERE status='unknown' OR (status='pending' AND created_at < ?)""",
                      (time.time() - 120,)).fetchall()
    for key, payload, created_at in rows:
        p = json.loads(payload)
        since = datetime.fromtimestamp(created_at - 60, timezone.utc).isoformat()
        r = ez.request("GET", "/v1/messages", idempotent=True, params={
            "filters[incoming][eq]": "false", "filters[contactNumber][eq]": p["toNumbers"][0],
            "filters[sentAt][gte]": since, "size": 50})
        match = next((m for m in r.json().get("content", []) if not m.get("inbound") and m.get("message") == p["message"]), None) if r.ok else None
        if match:
            db.execute("UPDATE sms_sends SET status='sent', message_id=? WHERE key=?", (match["messageGroupId"], key))
            # a reminder: link it to its appointment so cancel and reply matching work
            if key.endswith(":reminder"):
                appt_id = int(key.split(":")[1])
                db.execute("UPDATE appointments SET reminder_message_id=?, reminder_sent_at=? WHERE id=?",
                           (match["messageGroupId"], match.get("sentAt"), appt_id))
                # Cancelled while the outcome was unknown. Message history lists a reminder only
                # after it goes out, so it was already sent: cancel the appointment and report it.
                status = db.execute("SELECT status FROM appointments WHERE id=?", (appt_id,)).fetchone()[0]
                if status == "cancel_pending":
                    db.execute("UPDATE appointments SET status='cancelled' WHERE id=?", (appt_id,))
                    already_sent.append(appt_id)
            resolved.append(key)
            continue
        # not sent yet: look for it among scheduled sends
        mid = None
        if p.get("sendAt") and parse_ts(p["sendAt"]) > datetime.now(timezone.utc):
            mid = find_scheduled(p["toNumbers"][0], p["sendAt"])
        if mid:
            db.execute("UPDATE sms_sends SET status='sent', message_id=? WHERE key=?", (mid, key))
            if key.endswith(":reminder"):
                appt_id = int(key.split(":")[1])
                db.execute("UPDATE appointments SET reminder_message_id=?, reminder_sent_at=? WHERE id=?",
                           (mid, p["sendAt"], appt_id))
                # cancelled while the outcome was unknown: the reminder hasn't gone out, so cancel it
                status = db.execute("SELECT status FROM appointments WHERE id=?", (appt_id,)).fetchone()[0]
                if status == "cancel_pending" and cancel_reminder(appt_id) is None:
                    cancelled.append(appt_id)
            resolved.append(key)
        else:
            # Not found, or more than one candidate: a person checks before anything is sent again.
            unresolved.append(key)
    return jsonify(resolved=resolved, unresolved=unresolved,
                   reminderCancelled=cancelled, reminderAlreadySent=already_sent)

if __name__ == "__main__":
    app.run(port=int(os.environ.get("PORT", 3000)))
// Appointment reminder service on the EZ Texting API — single-file reference implementation.
//
//     npm install express better-sqlite3
//     export EZTEXTING_USERNAME=... EZTEXTING_PASSWORD=... EZTEXTING_WEBHOOK_SECRET=... APP_API_TOKEN=...
//     node reminders.mjs
//
// Endpoints:
//     POST   /appointments            create an appointment → schedules a reminder 24h before
//     DELETE /appointments/:id        cancel → deletes the pending reminder
//     GET    /appointments/:id        status, including the reminder's delivery report
//     POST   /webhooks/eztexting      inbound texts: C = confirm, R = reschedule
//     POST   /admin/reconcile         resolve sends whose outcome was unknown (no automatic resend)
//
// Only /webhooks/eztexting is public; it checks EZ Texting's signature. Every other endpoint
// requires `Authorization: Bearer <APP_API_TOKEN>`.
import crypto from "node:crypto";
import express from "express";
import Database from "better-sqlite3";

const BASE = process.env.EZTEXTING_BASE_URL || "https://a.eztexting.com";
const COMPANY = "Harbor Dental";
const WEBHOOK_SECRET = process.env.EZTEXTING_WEBHOOK_SECRET;
// your app's own token for the appointment and admin endpoints
const APP_API_TOKEN = process.env.APP_API_TOKEN;
if (!APP_API_TOKEN) throw new Error("APP_API_TOKEN is required");
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

// The request may or may not have been accepted (timeout or 5xx on a non-idempotent call).
class AmbiguousOutcome extends Error {}

// ---------------------------------------------------------------------------
// 1. API client: OAuth2 tokens (create once, refresh before expiry) + retry rules
//    - 429: never accepted → wait the server-specified time and retry
//    - 5xx / timeout on an idempotent call (GET, upsert, DELETE): retry with backoff
//    - 5xx / timeout on POST /v1/messages: AMBIGUOUS → throw, caller records 'unknown'
// ---------------------------------------------------------------------------
class EzTexting {
  #access; #refresh; #expiresAt = 0; #inflight = null;

  async #login() {
    const r = await fetch(`${BASE}/v1/tokens/create`, {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ appKey: process.env.EZTEXTING_USERNAME, appSecret: process.env.EZTEXTING_PASSWORD }),
    });
    if (!r.ok) throw new Error(`login ${r.status}`);
    this.#store(await r.json());
  }

  async #refreshTokens() {
    const r = await fetch(`${BASE}/v1/tokens/refresh`, {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ refreshToken: this.#refresh }),
    });
    // refresh token expired/revoked → log in again
    if (r.status === 401) return this.#login();
    if (!r.ok) throw new Error(`refresh ${r.status}`);
    this.#store(await r.json());
  }

  #store(t) {
    this.#access = t.accessToken; this.#refresh = t.refreshToken;
    // refresh 5 min early
    this.#expiresAt = Date.now() + (t.expiresInSeconds - 300) * 1000;
  }

  async #token() {
    // serialize concurrent refreshes
    if (this.#inflight) await this.#inflight;
    if (!this.#access) this.#inflight = this.#login();
    else if (Date.now() >= this.#expiresAt) this.#inflight = this.#refreshTokens();
    if (this.#inflight) { try { await this.#inflight; } finally { this.#inflight = null; } }
    return this.#access;
  }

  async request(method, path, { idempotent, body, query } = {}) {
    const url = BASE + path + (query ? "?" + new URLSearchParams(query) : "");
    for (let attempt = 0; attempt < 5; attempt++) {
      let res;
      try {
        res = await fetch(url, {
          method,
          headers: { Authorization: `Bearer ${await this.#token()}`, "Content-Type": "application/json" },
          body: body === undefined ? undefined : JSON.stringify(body),
          signal: AbortSignal.timeout(30_000),
        });
      } catch (err) {
        if (idempotent && attempt < 4) { await sleep(2 ** attempt * 1000); continue; }
        throw new AmbiguousOutcome(String(err));
      }
      if (res.status === 401 && attempt === 0) { this.#inflight = this.#refreshTokens(); continue; }
      // confirmed not accepted
      if (res.status === 429) {
        await sleep(Number(res.headers.get("X-Rate-Limit-Retry-After-Milliseconds") ?? 1000)); continue;
      }
      if (res.status >= 500) {
        if (idempotent && attempt < 4) { await sleep(2 ** attempt * 1000); continue; }
        throw new AmbiguousOutcome(`HTTP ${res.status}`);
      }
      return res;
    }
    throw new AmbiguousOutcome("retries exhausted");
  }
}
const ez = new EzTexting();

// ---------------------------------------------------------------------------
// 2. Storage: appointments, an at-most-once table for sends, and a webhook inbox
// ---------------------------------------------------------------------------
const db = new Database(process.env.REMINDERS_DB || "reminders.db");
db.exec(`CREATE TABLE IF NOT EXISTS appointments (
  id INTEGER PRIMARY KEY, booking_id TEXT UNIQUE, phone TEXT, first_name TEXT, service TEXT, starts_at TEXT,
  status TEXT DEFAULT 'booked', reminder_message_id TEXT, reminder_sent_at TEXT);
CREATE TABLE IF NOT EXISTS sms_sends (key TEXT PRIMARY KEY, status TEXT, message_id TEXT, payload TEXT, created_at REAL);
CREATE TABLE IF NOT EXISTS webhook_events (id INTEGER PRIMARY KEY AUTOINCREMENT, reply_to TEXT, body TEXT, received_at REAL, processed INTEGER DEFAULT 0);`);

function normalize(raw) {
  let d = String(raw).replace(/\D/g, "");
  if (d.length === 10) d = "1" + d;
  return d.length === 11 && d[0] === "1" ? d : null;
}

// scheduled, unknown (outcome not known yet), failed, or not_scheduled
function reminderState(apptId) {
  const row = db.prepare("SELECT status FROM sms_sends WHERE key=?").get(`appt:${apptId}:reminder`);
  if (!row) return "not_scheduled";
  return { sent: "scheduled", failed: "failed" }[row.status] ?? "unknown";
}

// At most one send per key. Returns the message id, null if the key was already claimed, or throws
// AmbiguousOutcome — in which case the row is left as 'unknown' for reconciliation. Never retries a
// send whose outcome is unknown.
async function sendOnce(key, payload) {
  const claimed = db.prepare("INSERT OR IGNORE INTO sms_sends (key, status, payload, created_at) VALUES (?, 'pending', ?, ?)")
    .run(key, JSON.stringify(payload), Date.now() / 1000);
  // already sent, failed, or in flight
  if (claimed.changes === 0) return null;
  let r;
  try {
    r = await ez.request("POST", "/v1/messages", { idempotent: false, body: payload });
  } catch (err) {
    if (err instanceof AmbiguousOutcome) db.prepare("UPDATE sms_sends SET status='unknown' WHERE key=?").run(key);
    throw err;
  }
  if (r.status === 201) {
    const { id } = await r.json();
    db.prepare("UPDATE sms_sends SET status='sent', message_id=? WHERE key=?").run(id, key);
    return id;
  }
  // 4xx: confirmed not sent
  db.prepare("UPDATE sms_sends SET status='failed' WHERE key=?").run(key);
  throw new Error(`EZ Texting ${r.status}: ${await r.text()}`);
}

// Appointment times are handled in their own UTC offset, never the server's time zone.
// "2026-11-21T09:00:00-08:00" → { local: wall-clock time (read with getUTC*), offset: "-08:00" }
function inOwnOffset(iso) {
  const m = /([+-])(\d\d):(\d\d)$/.exec(iso);
  const offset = m ? m[0] : "+00:00";
  const minutes = m ? (m[1] === "-" ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3])) : 0;
  return { local: new Date(Date.parse(iso) + minutes * 60000), offset };
}
const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
// "Nov 21 at 9:00 AM"
const fmt = (local) => `${MONTHS[local.getUTCMonth()]} ${local.getUTCDate()} at ${local.getUTCHours() % 12 || 12}:` +
  `${String(local.getUTCMinutes()).padStart(2, "0")} ${local.getUTCHours() < 12 ? "AM" : "PM"}`;

// ---------------------------------------------------------------------------
// 3. HTTP API for your app
// ---------------------------------------------------------------------------
const app = express();

// The webhook is public and checks EZ Texting's signature itself. Everything else is your app's
// own API and needs your token, so exposing the port for webhooks doesn't expose it.
app.use((req, res, next) => {
  if (req.path === "/webhooks/eztexting") return next();
  const given = Buffer.from(req.get("Authorization") || "");
  const expected = Buffer.from(`Bearer ${APP_API_TOKEN}`);
  if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) return res.sendStatus(401);
  next();
});

// Every booking response says what happened to the reminder.
function bookingResponse(res, id, phone, reason) {
  const reminder = reminderState(id);
  const body = { id, phone, reminder };
  if (reminder === "unknown") body.reason = "reminder outcome unknown; will reconcile";
  else if (reason) body.reason = reason;
  return res.status(reminder === "unknown" ? 202 : 201).json(body);
}

app.post("/appointments", express.json(), async (req, res) => {
  const { bookingId, firstName, service, startsAt, smsConsent } = req.body;
  // your system's stable ID for this booking: a retried request reuses it, so it can't book twice
  if (!bookingId) return res.status(400).json({ error: "bookingId is required" });
  const phone = normalize(req.body.phone);
  if (!phone) return res.status(400).json({ error: "invalid phone" });
  // recorded at booking, never assumed: only the JSON boolean true counts
  if (smsConsent !== true) return res.status(400).json({ error: "smsConsent must be true (a JSON boolean) to schedule a text reminder" });
  if (!/[+-]\d\d:\d\d$|Z$/.test(startsAt)) return res.status(400).json({ error: "startsAt needs a UTC offset" });
  // e.g. 2026-11-21T09:00:00-08:00
  const { local: startsLocal, offset } = inOwnOffset(startsAt);

  // idempotent upsert
  await ez.request("POST", "/v1/contacts", { idempotent: true, body: { phoneNumber: phone, firstName } });

  // one appointment per booking ID; a retry finds the existing row
  const inserted = db.prepare("INSERT OR IGNORE INTO appointments (booking_id, phone, first_name, service, starts_at) VALUES (?,?,?,?,?)")
    .run(bookingId, phone, firstName, service, startsAt);
  const { id } = db.prepare("SELECT id FROM appointments WHERE booking_id=?").get(bookingId);
  // a retry after a send was attempted: report that result instead of sending again
  if (inserted.changes === 0 && reminderState(id) !== "not_scheduled") return bookingResponse(res, id, phone);

  const sendLocal = new Date(startsLocal.getTime() - 24 * 3600 * 1000);
  // quiet hours: confirm the window for your jurisdictions
  if (sendLocal.getUTCHours() < 8) sendLocal.setUTCHours(8, 0, 0, 0);
  // e.g. "2026-11-20T09:00:00-08:00", in the appointment's own offset
  const sendAtIso = sendLocal.toISOString().slice(0, 19) + offset;
  // only schedule future reminders
  if (new Date(sendAtIso) <= new Date()) return bookingResponse(res, id, phone, "the reminder time has already passed");
  let mid = null;
  try {
    mid = await sendOnce(`appt:${id}:reminder`, {
      toNumbers: [phone],
      companyName: COMPANY,
      message: `Reminder: your ${service} is tomorrow, ${fmt(startsLocal)}. Reply C to confirm or R to reschedule. Reply STOP to opt out.`,
      sendAt: sendAtIso,
      strictValidation: true,
    });
  } catch (err) {
    // AmbiguousOutcome is recorded as 'unknown'; /admin/reconcile resolves it
    if (!(err instanceof AmbiguousOutcome)) {
      // confirmed not sent, e.g. a 400 because the number opted out or the account is out of credits
      return bookingResponse(res, id, phone, err.message);
    }
  }
  if (mid) db.prepare("UPDATE appointments SET reminder_message_id=?, reminder_sent_at=? WHERE id=?").run(mid, sendAtIso, id);
  bookingResponse(res, id, phone);
});

// Cancel the appointment, deleting its reminder if it hasn't gone out. Returns an error, or null.
async function cancelReminder(id) {
  const row = db.prepare("SELECT reminder_message_id, reminder_sent_at FROM appointments WHERE id=?").get(id);
  // Only a reminder that hasn't gone out yet is deleted. Deleting one that was already sent
  // wouldn't unsend it; it would only remove it from the account's message history.
  if (row.reminder_message_id && row.reminder_sent_at && new Date(row.reminder_sent_at) > new Date()) {
    // keep the reminder ID unless EZ Texting confirms the cancellation
    let r;
    try {
      r = await ez.request("DELETE", "/v1/messages", { idempotent: true, body: { ids: [row.reminder_message_id] } });
    } catch (err) {
      if (err instanceof AmbiguousOutcome) return "reminder cancellation outcome unknown; try again";
      throw err;
    }
    if (!r.ok) return `reminder not cancelled: EZ Texting ${r.status}: ${await r.text()}`;
    db.prepare("UPDATE appointments SET reminder_message_id=NULL WHERE id=?").run(id);
  }
  db.prepare("UPDATE appointments SET status='cancelled' WHERE id=?").run(id);
  return null;
}

app.delete("/appointments/:id", async (req, res) => {
  const row = db.prepare("SELECT reminder_message_id FROM appointments WHERE id=?").get(req.params.id);
  if (!row) return res.sendStatus(404);
  // The reminder may or may not exist yet, so there's nothing to delete: record the request.
  // /admin/reconcile finishes the cancellation once the reminder's outcome is known.
  if (reminderState(req.params.id) === "unknown") {
    db.prepare("UPDATE appointments SET status='cancel_pending' WHERE id=?").run(req.params.id);
    return res.status(202).json({ status: "cancel_pending", reason: "reminder outcome unknown; /admin/reconcile cancels it if it is still scheduled" });
  }
  const error = await cancelReminder(req.params.id);
  if (error) return res.status(502).json({ error, reminderMessageId: row.reminder_message_id });
  res.sendStatus(204);
});

app.get("/appointments/:id", async (req, res) => {
  const row = db.prepare("SELECT phone, status, reminder_message_id FROM appointments WHERE id=?").get(req.params.id);
  if (!row) return res.sendStatus(404);
  let delivery = null;
  if (row.reminder_message_id) {
    const r = await ez.request("GET", `/v1/message-reports/${row.reminder_message_id}`, { idempotent: true });
    if (r.ok) delivery = (await r.json()).delivery;
  }
  res.json({ phone: row.phone, status: row.status, reminder: reminderState(req.params.id), reminderMessageId: row.reminder_message_id, reminderDelivery: delivery });
});

// ---------------------------------------------------------------------------
// 4. Webhook: verify raw bytes → store → 2xx → process afterwards
//    (subscribe once: POST /v1/webhooks/subscriptions)
// ---------------------------------------------------------------------------
app.post("/webhooks/eztexting", express.raw({ type: "application/json" }), (req, res) => {
  const raw = req.body;
  const expected = crypto.createHmac("sha256", WEBHOOK_SECRET).update(raw).digest("base64");
  const given = req.get("X-Signature-256") || "";
  if (expected.length !== given.length || !crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(given))) {
    // diagnostics without the payload
    console.warn("webhook signature mismatch:", raw.length, "bytes, sha256=", crypto.createHash("sha256").update(raw).digest("hex").slice(0, 12));
    return res.sendStatus(401);
  }
  const event = JSON.parse(raw);
  // Inbound texts have no unique ID. `id`, when present, is the send this text replies to
  // (within 12 hours), so it's kept as reply_to, not used as a key.
  const stored = db.prepare("INSERT INTO webhook_events (reply_to, body, received_at) VALUES (?, ?, ?)").run(event.id ?? null, raw.toString(), Date.now() / 1000);
  // or a real queue
  setImmediate(() => processEvent(stored.lastInsertRowid).catch(console.error));
  res.sendStatus(204);
});

async function processEvent(eventId) {
  const row = db.prepare("SELECT body FROM webhook_events WHERE id=? AND processed=0").get(eventId);
  if (!row) return;
  const event = JSON.parse(row.body);
  if (event.type === "inbound_text.received") await handleReply(eventId, event);
  db.prepare("UPDATE webhook_events SET processed=1 WHERE id=?").run(eventId);
}

async function handleReply(eventId, event) {
  const phone = event.fromNumber;
  const text = (event.message || "").trim().toUpperCase();
  // EZ Texting already blocked future sends
  if (event.optOut) {
    db.prepare("UPDATE appointments SET status='opted_out' WHERE phone=? AND status='booked'").run(phone);
    return;
  }
  if (text !== "C" && text !== "R") return;
  // A reply carries the reminder's message ID in `id` when there is one: use it.
  let apptId = event.id ? db.prepare("SELECT id FROM appointments WHERE reminder_message_id=?").get(event.id)?.id : undefined;
  if (apptId === undefined) {
    // No ID: only a booking whose reminder has already gone out can be the one they mean
    // (reminder_sent_at is the scheduled time, so a future one hasn't been seen yet).
    const seen = db.prepare("SELECT id, reminder_sent_at FROM appointments WHERE phone=? AND status='booked' AND reminder_sent_at IS NOT NULL")
      .all(phone).filter((a) => new Date(a.reminder_sent_at) <= new Date());
    if (seen.length !== 1) {
      // none or several: don't guess, ask
      await sendOnce(`reply:${eventId}:unclear`, { toNumbers: [phone], companyName: COMPANY,
        message: "Sorry, we couldn't tell which appointment you mean. Please call the office to confirm or reschedule." });
      return;
    }
    apptId = seen[0].id;
  }
  if (text === "C") {
    db.prepare("UPDATE appointments SET status='confirmed' WHERE id=?").run(apptId);
    await sendOnce(`appt:${apptId}:confirm-ack`, { toNumbers: [phone], companyName: COMPANY, message: "Thanks, you're confirmed. See you then!" });
  } else {
    db.prepare("UPDATE appointments SET status='reschedule_requested' WHERE id=?").run(apptId);
    await sendOnce(`appt:${apptId}:resched-ack`, { toNumbers: [phone], companyName: COMPANY, message: "No problem — we'll call you shortly to find a new time." });
  }
}

// ---------------------------------------------------------------------------
// 5. Reconciliation: resolve 'unknown' / stale 'pending' sends by LOOKING, never by resending
// ---------------------------------------------------------------------------
// A scheduled send isn't in GET /v1/messages until it goes out. campaign-info lists
// scheduled sends by day (IDs only), and message-details gives each one's recipients.
// Returns the one unlinked send scheduled to this phone around sendAt, or null.
async function findScheduled(phone, sendAt) {
  const mdy = (d) => `${String(d.getUTCMonth() + 1).padStart(2, "0")}-${String(d.getUTCDate()).padStart(2, "0")}-${d.getUTCFullYear()}`;
  const day = new Date(sendAt).getTime();
  // the day filter's time zone isn't specified, so include a day either side
  const query = {
    "filters[sentAt][gte]": mdy(new Date(day - 86_400_000)),
    "filters[sentAt][lte]": mdy(new Date(day + 86_400_000)),
    size: 200,
  };
  const known = new Set(db.prepare("SELECT message_id FROM sms_sends WHERE message_id IS NOT NULL").all().map((r) => r.message_id));
  const found = [];
  for (let page = 0; ; page++) {
    const r = await ez.request("GET", "/v1/campaign-info", { idempotent: true, query: { ...query, page } });
    const rows = r.ok ? (await r.json()).content || [] : [];
    for (const row of rows) {
      const mid = String(row.id);
      if (known.has(mid)) continue;
      const d = await ez.request("GET", `/v1/message-details/${mid}`, { idempotent: true });
      if (d.ok && ((await d.json()).contacts || []).some((c) => (c.phoneNumber || "").slice(-10) === phone.slice(-10))) found.push(mid);
    }
    if (rows.length < 200) break;
  }
  // two scheduled sends to the same number in that window can't be told apart: leave it to a person
  return found.length === 1 ? found[0] : null;
}

app.post("/admin/reconcile", async (req, res) => {
  const resolved = [], unresolved = [], cancelled = [], alreadySent = [];
  const rows = db.prepare("SELECT key, payload, created_at FROM sms_sends WHERE status='unknown' OR (status='pending' AND created_at < ?)")
    .all(Date.now() / 1000 - 120);
  for (const { key, payload, created_at } of rows) {
    const p = JSON.parse(payload);
    const r = await ez.request("GET", "/v1/messages", { idempotent: true, query: {
      "filters[incoming][eq]": "false",
      "filters[contactNumber][eq]": p.toNumbers[0],
      "filters[sentAt][gte]": new Date((created_at - 60) * 1000).toISOString(),
      size: 50,
    } });
    const match = r.ok ? ((await r.json()).content || []).find((m) => !m.inbound && m.message === p.message) : null;
    if (match) {
      db.prepare("UPDATE sms_sends SET status='sent', message_id=? WHERE key=?").run(match.messageGroupId, key);
      // a reminder: link it to its appointment so cancel and reply matching work
      if (key.endsWith(":reminder")) {
        const apptId = Number(key.split(":")[1]);
        db.prepare("UPDATE appointments SET reminder_message_id=?, reminder_sent_at=? WHERE id=?")
          .run(match.messageGroupId, match.sentAt ?? null, apptId);
        // Cancelled while the outcome was unknown. Message history lists a reminder only
        // after it goes out, so it was already sent: cancel the appointment and report it.
        const { status } = db.prepare("SELECT status FROM appointments WHERE id=?").get(apptId);
        if (status === "cancel_pending") {
          db.prepare("UPDATE appointments SET status='cancelled' WHERE id=?").run(apptId);
          alreadySent.push(apptId);
        }
      }
      resolved.push(key);
      continue;
    }
    // not sent yet: look for it among scheduled sends
    const mid = p.sendAt && new Date(p.sendAt) > new Date() ? await findScheduled(p.toNumbers[0], p.sendAt) : null;
    if (mid) {
      db.prepare("UPDATE sms_sends SET status='sent', message_id=? WHERE key=?").run(mid, key);
      if (key.endsWith(":reminder")) {
        const apptId = Number(key.split(":")[1]);
        db.prepare("UPDATE appointments SET reminder_message_id=?, reminder_sent_at=? WHERE id=?").run(mid, p.sendAt, apptId);
        // cancelled while the outcome was unknown: the reminder hasn't gone out, so cancel it
        const { status } = db.prepare("SELECT status FROM appointments WHERE id=?").get(apptId);
        if (status === "cancel_pending" && (await cancelReminder(apptId)) === null) cancelled.push(apptId);
      }
      resolved.push(key);
    } else {
      // Not found, or more than one candidate: a person checks before anything is sent again.
      unresolved.push(key);
    }
  }
  res.json({ resolved, unresolved, reminderCancelled: cancelled, reminderAlreadySent: alreadySent });
});

app.listen(Number(process.env.PORT || 3000), () => console.log("reminder service on :" + (process.env.PORT || 3000)));

What to change for production

  • Storage. SQLite is for the example. Point the tables at your real database; sms_sends (the at-most-once table) and webhook_events (the inbox) are the ones that matter.
  • Background work. The webhook handler uses a thread / setImmediate after acknowledging. Replace with your queue; the important property (stored before the 2xx) stays the same.
  • Time zones and quiet hours. The example trusts the offset in startsAt and nudges sends after 8am in that offset. Store a time zone per customer and apply the quiet-hours rules for the jurisdictions you serve, and confirm those with compliance.
  • Reconciliation on a schedule. Call /admin/reconcile from a cron job every few minutes, and alert on unresolved.
  • Polling fallback for inbound. If the webhook endpoint is down, replies wait in GET /v1/conversations?filters[unread][eq]=true. A sweep that writes into the same webhook_events table catches them. See Two-way conversations.
  • Consent record. smsConsent: true is a stand-in for a real record: when, where, and what disclosure the person saw. → Compliance

Related


Did this page help you?