# Llenar una cita cancelada desde una lista de espera por WhatsApp

> Cuando se cancela una cita, ofrece el turno a la lista de espera por WhatsApp, dáselo al primer Sí con un solo UPDATE de Postgres y responde a los toques tardíos.

Published 2026-11-27. Z-API Omni team.

Llenar un turno desde la lista de espera es el flujo que ofrece un turno liberado a los clientes que pidieron enterarse cuando ese servicio tenga lugar, y reserva al primero que acepta. Cuando se cancela una reserva, envía una plantilla con "Yes, book it" (sí, resérvalo) y "No thanks" (no, gracias) a una pequeña tanda de clientes en lista de espera. Dale el turno al primer Sí con un solo `UPDATE` condicional, para que Postgres elija exactamente un ganador. Todos los que tocan Sí después reciben "turno ocupado" dentro de la ventana que abrió su toque.

La cancelación puede venir de cualquier lado. Calendly envía `invitee.canceled` con `rescheduled: false`, como se muestra en [webhooks de Calendly a WhatsApp](/academy/es/articles/calendly-webhook-whatsapp-confirmations-reminders/). Cal.com envía `BOOKING_CANCELLED`, explicado en [webhooks de Cal.com a recordatorios por WhatsApp](/academy/es/articles/cal-com-webhook-whatsapp-booking-reminders/). Este artículo usa tus propias tablas como fuente de verdad, porque una lista de espera tiene que saber quién tiene cada turno.

## El ciclo, de la cancelación al turno ocupado otra vez

1. Tu sistema cancela una reserva y llama al servicio de reasignación, que reabre el turno.
2. El servicio envía la plantilla de oferta a la primera tanda de clientes en lista de espera para ese servicio.
3. Un toque llega como un mensaje `button` con el ID de la oferta en su payload.
4. Un `UPDATE` le da el turno al primer Sí, y en la misma sentencia se escribe una fila de reserva.
5. Los toques posteriores reciben "turno ocupado". Si nadie responde, la siguiente tanda sale después de una ventana de espera.

Las tandas y la ventana de espera son decisiones de diseño. Ninguna fuente da una cifra de cuántas personas responden a una oferta, así que ajusta `WAVE_SIZE` y `HOLD_MINUTES` con tus propios datos.

## En qué categoría cae la oferta

La página de Meta no resuelve este caso, así que diseña para los dos resultados. Una plantilla de utilidad "tiene que ser no promocional" y "tiene que ser TAMBIÉN específica del usuario o solicitada por él (claramente relacionada con su pedido, cuenta, servicios o transacciones)" ([categorización de plantillas](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization.md), consultado el 2026-11-27).

La misma página juega en contra de "lo pidieron, así que es utilidad". Sus ejemplos de marketing incluyen un mensaje de retargeting: "Encontramos un {{car}} que coincide con tu búsqueda guardada. Inicia sesión en nuestra app para verlo". Meta agrega: "Son marketing aunque los soliciten los usuarios". Una lista de espera se parece mucho a una búsqueda guardada. La página no tiene ningún ejemplo de lista de espera.

Nuestra lectura: el caso de utilidad más fuerte ofrece un turno concreto para exactamente el servicio por el que la persona pidió estar en lista de espera, y nada más. Se refiere a un pedido que hizo sobre un servicio que quiere. Si agregas "otros horarios esta semana" o un segundo servicio, se vuelve una recomendación, que se lee como marketing. El contenido mixto es marketing en la página de Meta.

Meta igual puede clasificarla como marketing. Después de una advertencia, "los cambios de categoría de utilidad a marketing pasan a ser inmediatos, sin aviso previo". Luego viene una limitación de frecuencia de utilidad durante al menos 7 días. Sigue una restricción de utilidad, de 7 días o de 30 en caso de reincidencia, y durante ella todas tus plantillas de utilidad pasan a MARKETING. El último paso es una restricción del portfolio de 30 días. Por eso el servicio tiene un interruptor, `OFFER_CATEGORY`, que pones en `MARKETING` si la plantilla se recategoriza.

Con `MARKETING`, el servicio ofrece el turno solo a clientes que además dieron su consentimiento de marketing. Entonces se aplican los límites de marketing por usuario, y Meta puede retener un mensaje con el [error 131049](/academy/es/articles/whatsapp-error-131049-marketing-message-not-delivered/). Algunos destinatarios de una tanda pueden no recibir nada, otro motivo para enviar por tandas. Las reglas generales están en [las categorías de plantillas de WhatsApp](/academy/es/articles/whatsapp-template-categories-marketing-utility-authentication/).

## Guarda la solicitud en la fila de la lista de espera

La fila de la lista de espera es tu prueba de que la persona lo pidió. Guarda el servicio que pidió (`requested_service_id`), cuándo aceptó (`opted_in_at`) y el texto de consentimiento que vio. Un indicador aparte, `marketing_opt_in`, cubre la alternativa de marketing. [Cómo recoger el opt-in de WhatsApp](/academy/es/articles/whatsapp-opt-in-how-to-collect-consent/) cubre qué más registrar.

```sql
-- waitlist-schema.sql: tables for the waitlist refill service. PostgreSQL 13 or later.
CREATE TABLE customers (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text NOT NULL,
  phone text NOT NULL UNIQUE, -- E.164 digits without +
  time_zone text NOT NULL DEFAULT 'UTC'
);

CREATE TABLE services (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  name text NOT NULL
);

CREATE TABLE slots (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  service_id bigint NOT NULL REFERENCES services (id),
  starts_at timestamptz NOT NULL,
  status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'taken')),
  taken_by bigint REFERENCES customers (id),
  refill boolean NOT NULL DEFAULT false, -- true while the waitlist is being offered this slot
  round int NOT NULL DEFAULT 0, -- bumps each time the slot reopens
  wave int NOT NULL DEFAULT 0,
  last_wave_at timestamptz
);

CREATE TABLE bookings (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slot_id bigint NOT NULL REFERENCES slots (id),
  customer_id bigint NOT NULL REFERENCES customers (id),
  status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'cancelled')),
  created_at timestamptz NOT NULL DEFAULT now()
);
-- Safety net: a second active booking for one slot cannot exist, even if code errs.
CREATE UNIQUE INDEX one_active_booking_per_slot ON bookings (slot_id) WHERE status = 'active';

CREATE TABLE waitlist (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers (id),
  requested_service_id bigint NOT NULL REFERENCES services (id),
  opted_in_at timestamptz NOT NULL,
  consent_text text NOT NULL,
  marketing_opt_in boolean NOT NULL DEFAULT false,
  status text NOT NULL DEFAULT 'waiting' CHECK (status IN ('waiting', 'booked', 'opted_out')),
  joined_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (customer_id, requested_service_id)
);

CREATE TABLE offers (
  id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slot_id bigint NOT NULL REFERENCES slots (id),
  round int NOT NULL,
  wave int NOT NULL,
  waitlist_id bigint NOT NULL REFERENCES waitlist (id),
  wamid text UNIQUE,
  status text NOT NULL DEFAULT 'pending'
    CHECK (status IN ('pending', 'won', 'lost', 'declined', 'failed')),
  sent_at timestamptz NOT NULL DEFAULT now(),
  UNIQUE (slot_id, round, waitlist_id)
);

CREATE TABLE inbound_events (
  wamid text PRIMARY KEY,
  received_at timestamptz NOT NULL DEFAULT now()
);
```

Tu flujo normal de reservas debería poner `slots.status` en `taken` cuando escribe una reserva, para que el servicio de reasignación vea el mismo estado.

## Un UPDATE decide el ganador

Dos clientes pueden tocar Sí con milisegundos de diferencia, y dos entregas de webhook pueden correr en dos conexiones a la vez. Postgres lo resuelve sin un `SELECT ... FOR UPDATE`. Con Read Committed, el nivel por defecto, "el que quiere actualizar esperará a que la primera transacción de actualización haga commit o rollback" ([aislamiento de transacciones](https://www.postgresql.org/docs/current/transaction-iso.html), consultado el 2026-11-27). Después, "la condición de búsqueda del comando (la cláusula `WHERE`) se vuelve a evaluar para ver si la versión actualizada de la fila todavía cumple la condición".

Así, `UPDATE slots SET status = 'taken' ... WHERE id = $1 AND status = 'open' AND starts_at > now()` deja que coincida exactamente una transacción. La segunda vuelve a comprobar `status = 'open'` contra la fila confirmada, encuentra `taken` y actualiza cero filas. El servicio escribe la reserva en la misma sentencia, con un CTE que modifica datos, así que un turno nunca queda ocupado sin una reserva. La condición `starts_at > now()` rechaza un Sí tardío para un horario que ya pasó.

Un reintento del webhook puede entregar el mismo toque dos veces. El servicio inserta cada wamid entrante en `inbound_events` con `ON CONFLICT DO NOTHING` y sigue solo cuando vuelve una fila. Postgres advierte que una inserción así "puede no completarse para una fila por el resultado de otra transacción". Una segunda entrega del mismo toque entonces no hace nada. Incluso sin eso, un Sí repetido encuentra el turno ocupado por su propia oferta y no cambia nada.

Si pasas los envíos a un pool de workers, toma los jobs con `SELECT ... FOR UPDATE SKIP LOCKED`, como se explica en [la arquitectura de colas para webhooks de WhatsApp](/academy/es/articles/whatsapp-webhook-queue-architecture-workers/).

## Envía la oferta por tandas

La plantilla nombra el servicio, la fecha y la hora, y dice quién se lo queda. Créala como plantilla de utilidad con dos respuestas rápidas.

| Plantilla | Cuerpo | Botones |
| --- | --- | --- |
| `waitlist_slot_offer` | Hi {{customer_name}}, a {{service}} slot you joined the waitlist for is free on {{date}} at {{time}}. The first person to tap Yes gets it. | Respuestas rápidas "Yes, book it", "No thanks" |

Al enviar, cada botón lleva el ID de la oferta en su payload, como `offer:<id>:yes` y `offer:<id>:no`. El toque vuelve como `type: "button"` con `button.payload`, `button.text` y `context.id`, el wamid de la oferta ([referencia del webhook de botón](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button), consultado el 2026-11-25). El servicio interpreta primero el payload y, si no puede, asocia `context.id` con el wamid guardado.

Ponle un TTL corto a la plantilla. `message_send_ttl_seconds` va de 30 segundos a 12 horas para las plantillas de utilidad y pertenece a la plantilla, no al envío ([tiempo de vida](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live), consultado el 2026-11-25). Mantenlo cerca de tu ventana de espera, para que una oferta que llega tarde a un teléfono se descarte en lugar de llegar cuando el turno ya no existe.

Un toque abre la ventana de 24 horas, así que "Reservado" y "turno ocupado" salen como texto libre. Son mensajes de servicio, y [los cargos por mensajes de servicio de Meta desde octubre de 2026](/academy/es/articles/meta-whatsapp-service-message-charges-october-2026/) explica cómo se cobran. Los clientes que nunca tocan no reciben nada más. Avisarles que el turno ya no está costaría otra plantilla por persona.

## El servicio de reasignación

Este archivo funciona en Node 18 o posterior con Express 4 y node-postgres, sobre el esquema de arriba. Tu sistema de reservas llama a `POST /slots/:id/cancel` después de una cancelación. Un temporizador envía la siguiente tanda cuando pasa la ventana de espera.

```js
// waitlist-refill.js: offer a cancelled slot to the waitlist on WhatsApp; the first Yes wins.
// Node 18+, Express 4 and node-postgres. Run: npm install express pg && node waitlist-refill.js
const crypto = require("crypto");
const express = require("express");
const { Pool } = require("pg");

function env(name, fallback) {
  const value = process.env[name] || fallback;
  if (!value) throw new Error(`Missing environment variable ${name}`);
  return value;
}
const DATABASE_URL = env("DATABASE_URL");
const WA_TOKEN = env("WA_TOKEN");
const PHONE_NUMBER_ID = env("PHONE_NUMBER_ID");
const APP_SECRET = env("APP_SECRET");
const VERIFY_TOKEN = env("VERIFY_TOKEN");
const INTERNAL_TOKEN = env("INTERNAL_TOKEN");
const OFFER_TEMPLATE = env("OFFER_TEMPLATE", "waitlist_slot_offer");
const OFFER_CATEGORY = env("OFFER_CATEGORY", "UTILITY"); // set MARKETING if Meta recategorizes the template
const WAVE_SIZE = Number(env("WAVE_SIZE", "3"));
const HOLD_MINUTES = Number(env("HOLD_MINUTES", "20"));
const CUTOFF_MINUTES = Number(env("CUTOFF_MINUTES", "60")); // stop offering this close to the start
const PORT = Number(env("PORT", "3000"));

const GRAPH_URL = `https://graph.facebook.com/v26.0/${PHONE_NUMBER_ID}/messages`;
const db = new Pool({ connectionString: DATABASE_URL });

const CANCEL_SQL = `
WITH reopened AS (
  UPDATE slots
  SET status = 'open', taken_by = NULL, refill = true, round = round + 1, wave = 0, last_wave_at = NULL
  WHERE id = $1 AND status = 'taken' AND starts_at > now()
  RETURNING id
), cancelled AS (
  UPDATE bookings SET status = 'cancelled'
  WHERE slot_id IN (SELECT id FROM reopened) AND status = 'active'
)
SELECT id FROM reopened`;

// Claims the next wave for one slot. The UPDATE on slots stops two timers from sending the same wave.
const WAVE_SQL = `
WITH s AS (
  UPDATE slots SET wave = wave + 1, last_wave_at = now()
  WHERE id = $1 AND status = 'open' AND refill
    AND starts_at > now() + make_interval(mins => $3::int)
    AND (last_wave_at IS NULL OR last_wave_at < now() - make_interval(mins => $4::int))
  RETURNING id, service_id, round, wave
)
INSERT INTO offers (slot_id, round, wave, waitlist_id)
SELECT s.id, s.round, s.wave, w.id
FROM s
JOIN waitlist w ON w.requested_service_id = s.service_id AND w.status = 'waiting'
WHERE (NOT $5::boolean OR w.marketing_opt_in)
  AND NOT EXISTS (
    SELECT 1 FROM offers o WHERE o.slot_id = s.id AND o.round = s.round AND o.waitlist_id = w.id
  )
ORDER BY w.joined_at
LIMIT $2
ON CONFLICT DO NOTHING
RETURNING id`;

const OFFER_DETAILS_SQL = `
SELECT o.id, c.phone, c.name, c.time_zone, sv.name AS service, sl.starts_at
FROM offers o
JOIN waitlist w ON w.id = o.waitlist_id
JOIN customers c ON c.id = w.customer_id
JOIN slots sl ON sl.id = o.slot_id
JOIN services sv ON sv.id = sl.service_id
WHERE o.id = ANY($1::bigint[])`;

// One statement: take the slot only if it is still open, and write the booking with it.
const CLAIM_SQL = `
WITH o AS (
  SELECT o.id, o.slot_id, o.round, w.customer_id
  FROM offers o JOIN waitlist w ON w.id = o.waitlist_id
  WHERE o.id = $1 AND o.status IN ('pending', 'declined', 'failed')
), claimed AS (
  UPDATE slots s SET status = 'taken', taken_by = o.customer_id, refill = false
  FROM o
  WHERE s.id = o.slot_id AND s.round = o.round AND s.status = 'open' AND s.starts_at > now()
  RETURNING s.id AS slot_id, o.customer_id
)
INSERT INTO bookings (slot_id, customer_id)
SELECT slot_id, customer_id FROM claimed
RETURNING slot_id`;

const SETTLE_SQL = `
WITH won AS (
  UPDATE offers SET status = 'won' WHERE id = $1 RETURNING slot_id, round, waitlist_id
), booked AS (
  UPDATE waitlist SET status = 'booked' WHERE id = (SELECT waitlist_id FROM won)
)
UPDATE offers SET status = 'lost'
WHERE slot_id = (SELECT slot_id FROM won) AND round = (SELECT round FROM won)
  AND status = 'pending' AND id <> $1`;

const STATE_SQL = `
SELECT o.status, sl.starts_at <= now() AS passed
FROM offers o JOIN slots sl ON sl.id = o.slot_id
WHERE o.id = $1`;

function formatWhen(value, timeZone) {
  const d = new Date(value);
  return {
    date: d.toLocaleDateString("en-US", { timeZone, weekday: "long", month: "long", day: "numeric" }),
    time: d.toLocaleTimeString("en-US", { timeZone, hour: "numeric", minute: "2-digit" }),
  };
}

function safeEqual(a, b) {
  const x = Buffer.from(String(a));
  const y = Buffer.from(String(b));
  return x.length === y.length && crypto.timingSafeEqual(x, y);
}

async function sendWhatsApp(message, attempt = 1) {
  let status = 0;
  let data = {};
  try {
    const res = await fetch(GRAPH_URL, {
      method: "POST",
      headers: { Authorization: `Bearer ${WA_TOKEN}`, "Content-Type": "application/json" },
      body: JSON.stringify({ messaging_product: "whatsapp", recipient_type: "individual", ...message }),
    });
    status = res.status;
    data = await res.json().catch(() => ({}));
    if (res.ok) return data.messages[0].id;
  } catch (err) {
    data = { error: String(err) };
  }
  // A network error after Meta accepted the send can duplicate it; lower the attempts if that matters.
  if ((status === 0 || status === 429 || status >= 500) && attempt < 4) {
    await new Promise((resolve) => setTimeout(resolve, 2 ** attempt * 1000));
    return sendWhatsApp(message, attempt + 1);
  }
  throw new Error(`WhatsApp send failed with HTTP ${status}: ${JSON.stringify(data)}`);
}

const sendText = (to, body) => sendWhatsApp({ to, type: "text", text: { body } });

function offerMessage(offer) {
  const when = formatWhen(offer.starts_at, offer.time_zone);
  return {
    to: offer.phone,
    type: "template",
    template: {
      name: OFFER_TEMPLATE,
      language: { code: "en_US" },
      components: [
        {
          type: "body",
          parameters: [
            { type: "text", parameter_name: "customer_name", text: offer.name },
            { type: "text", parameter_name: "service", text: offer.service },
            { type: "text", parameter_name: "date", text: when.date },
            { type: "text", parameter_name: "time", text: when.time },
          ],
        },
        ...["yes", "no"].map((action, index) => ({
          type: "button",
          sub_type: "quick_reply",
          index: String(index),
          parameters: [{ type: "payload", payload: `offer:${offer.id}:${action}` }],
        })),
      ],
    },
  };
}

async function sendWave(slotId) {
  const marketing = OFFER_CATEGORY === "MARKETING"; // then only customers with marketing consent
  const { rows: created } = await db.query(WAVE_SQL, [slotId, WAVE_SIZE, CUTOFF_MINUTES, HOLD_MINUTES, marketing]);
  if (created.length === 0) return 0;
  const { rows } = await db.query(OFFER_DETAILS_SQL, [created.map((row) => row.id)]);
  for (const offer of rows) {
    try {
      const wamid = await sendWhatsApp(offerMessage(offer));
      await db.query("UPDATE offers SET wamid = $2 WHERE id = $1", [offer.id, wamid]);
    } catch (err) {
      await db.query("UPDATE offers SET status = 'failed' WHERE id = $1 AND status = 'pending'", [offer.id]);
      console.error("offer send failed", offer.id, err.message);
    }
  }
  return rows.length;
}

async function onOfferReply(offerId, action, from) {
  if (action === "no") {
    await db.query("UPDATE offers SET status = 'declined' WHERE id = $1 AND status = 'pending'", [offerId]);
    return sendText(from, "No problem. You stay on the waitlist for this service.");
  }
  const claimed = await db.query(CLAIM_SQL, [offerId]);
  if (claimed.rowCount === 1) {
    await db.query(SETTLE_SQL, [offerId]);
    const { rows: [offer] } = await db.query(OFFER_DETAILS_SQL, [[offerId]]);
    const when = formatWhen(offer.starts_at, offer.time_zone);
    return sendText(from, `Booked: ${offer.service} on ${when.date} at ${when.time}. See you then.`);
  }
  const { rows: [state] } = await db.query(STATE_SQL, [offerId]);
  if (!state) return console.warn("unknown offer", offerId);
  if (state.status === "won") return; // a second tap on an offer that already won
  await db.query("UPDATE offers SET status = 'lost' WHERE id = $1 AND status = 'pending'", [offerId]);
  if (state.passed) return sendText(from, "This time has already passed. You stay on the waitlist.");
  return sendText(from, "Sorry, someone else took this slot a moment ago. You stay on the waitlist.");
}

async function handleMessage(msg) {
  const fresh = await db.query(
    "INSERT INTO inbound_events (wamid) VALUES ($1) ON CONFLICT DO NOTHING RETURNING wamid", [msg.id]);
  if (fresh.rowCount === 0) return; // Meta delivered this message before
  if (msg.type === "button") {
    let [prefix, offerId, action] = String(msg.button?.payload || "").split(":");
    if (prefix !== "offer") {
      // Payload not in our format: find the offer this tap belongs to.
      const { rows } = await db.query("SELECT id FROM offers WHERE wamid = $1", [msg.context?.id || null]);
      offerId = rows[0]?.id;
      action = { "Yes, book it": "yes", "No thanks": "no" }[msg.button?.text];
    }
    if (/^\d+$/.test(String(offerId)) && (action === "yes" || action === "no")) {
      return onOfferReply(String(offerId), action, msg.from);
    }
    return console.warn("unmatched tap", msg.id);
  }
  if (msg.type === "text" && msg.from && /^\s*stop\s*$/i.test(msg.text?.body || "")) {
    await db.query(
      `UPDATE waitlist w SET status = 'opted_out' FROM customers c
       WHERE c.id = w.customer_id AND c.phone = $1 AND w.status = 'waiting'`, [msg.from]);
    return sendText(msg.from, "You are off the waitlist and will not get slot offers here anymore.");
  }
}

async function handleStatus(status) {
  if (status.status !== "failed") return;
  const code = status.errors?.[0]?.code;
  await db.query("UPDATE offers SET status = 'failed' WHERE wamid = $1 AND status = 'pending'", [status.id]);
  console.warn(code === 131049 ? "held back by marketing limits" : "offer failed", status.id, code);
}

const app = express();

app.post("/slots/:id/cancel", async (req, res) => {
  if (!safeEqual(req.get("Authorization") || "", `Bearer ${INTERNAL_TOKEN}`)) return res.sendStatus(401);
  if (!/^\d+$/.test(req.params.id)) return res.sendStatus(400);
  try {
    const reopened = await db.query(CANCEL_SQL, [req.params.id]);
    if (reopened.rowCount === 0) {
      return res.status(409).json({ error: "Slot is not taken, was already reopened, or has started" });
    }
    res.json({ reopened: true, offersSent: await sendWave(req.params.id) });
  } catch (err) {
    console.error("cancel", req.params.id, err.message);
    res.sendStatus(500);
  }
});

app.get("/webhook", (req, res) => {
  const ok = req.query["hub.mode"] === "subscribe" && req.query["hub.verify_token"] === VERIFY_TOKEN;
  return ok ? res.send(String(req.query["hub.challenge"])) : res.sendStatus(403);
});

app.post("/webhook", express.raw({ type: "application/json" }), (req, res) => {
  if (!Buffer.isBuffer(req.body)) return res.sendStatus(400);
  const expected = "sha256=" + crypto.createHmac("sha256", APP_SECRET).update(req.body).digest("hex");
  if (!safeEqual(req.get("X-Hub-Signature-256") || "", expected)) return res.sendStatus(401);
  res.sendStatus(200); // answer first, work after
  let body;
  try {
    body = JSON.parse(req.body.toString("utf8"));
  } catch {
    return;
  }
  for (const entry of body.entry || []) {
    for (const change of entry.changes || []) {
      if (change.field !== "messages") continue;
      for (const status of change.value?.statuses || []) {
        handleStatus(status).catch((err) => console.error("status", status.id, err.message));
      }
      for (const msg of change.value?.messages || []) {
        handleMessage(msg).catch((err) => console.error("message", msg.id, err.message));
      }
    }
  }
});

async function tick() {
  const { rows } = await db.query("SELECT id FROM slots WHERE status = 'open' AND refill AND starts_at > now()");
  for (const row of rows) await sendWave(row.id);
}
setInterval(() => tick().catch((err) => console.error("wave timer", err.message)), 60 * 1000);
app.listen(PORT, () => console.log(`listening on ${PORT}`));
```

Los estados de una oferta son `pending`, `won`, `lost`, `declined` y `failed`. Un cliente que tocó "No thanks" todavía puede tocar Sí más tarde y ganar si el turno está libre, porque la toma acepta `declined`. Una respuesta STOP saca al cliente de todas las listas de espera en las que esté.

## Prueba la toma en PGlite, y la carrera en Postgres

PGlite corre Postgres dentro de Node, lo que lo vuelve práctico para revisar SQL en CI. Su documentación también marca el límite de esa prueba: "PGlite tiene una sola conexión exclusiva a la base de datos" ([documentación de PGlite](https://pglite.dev/docs/), consultado el 2026-11-27). Las sentencias corren una después de otra, así que una prueba en PGlite demuestra la lógica de cero o una fila y que un reenvío no hace daño. No puede reproducir dos conexiones esperando un bloqueo de fila.

```js
// waitlist-claim.test.mjs: the claim logic, one call after another, on PGlite.
// Node 18+. Run: npm install @electric-sql/pglite && node waitlist-claim.test.mjs
import assert from "node:assert/strict";
import { PGlite } from "@electric-sql/pglite";

const db = new PGlite(); // in memory, single connection

await db.exec(`
CREATE TABLE customers (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL,
  phone text NOT NULL UNIQUE, time_zone text NOT NULL DEFAULT 'UTC');
CREATE TABLE services (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, name text NOT NULL);
CREATE TABLE slots (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  service_id bigint NOT NULL REFERENCES services (id), starts_at timestamptz NOT NULL,
  status text NOT NULL DEFAULT 'open' CHECK (status IN ('open', 'taken')),
  taken_by bigint REFERENCES customers (id), refill boolean NOT NULL DEFAULT false,
  round int NOT NULL DEFAULT 0, wave int NOT NULL DEFAULT 0, last_wave_at timestamptz);
CREATE TABLE bookings (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slot_id bigint NOT NULL REFERENCES slots (id), customer_id bigint NOT NULL REFERENCES customers (id),
  status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'cancelled')),
  created_at timestamptz NOT NULL DEFAULT now());
CREATE UNIQUE INDEX one_active_booking_per_slot ON bookings (slot_id) WHERE status = 'active';
CREATE TABLE waitlist (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  customer_id bigint NOT NULL REFERENCES customers (id),
  requested_service_id bigint NOT NULL REFERENCES services (id), opted_in_at timestamptz NOT NULL,
  consent_text text NOT NULL, marketing_opt_in boolean NOT NULL DEFAULT false,
  status text NOT NULL DEFAULT 'waiting' CHECK (status IN ('waiting', 'booked', 'opted_out')),
  joined_at timestamptz NOT NULL DEFAULT now(), UNIQUE (customer_id, requested_service_id));
CREATE TABLE offers (id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  slot_id bigint NOT NULL REFERENCES slots (id), round int NOT NULL, wave int NOT NULL,
  waitlist_id bigint NOT NULL REFERENCES waitlist (id), wamid text UNIQUE,
  status text NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'won', 'lost', 'declined', 'failed')),
  sent_at timestamptz NOT NULL DEFAULT now(), UNIQUE (slot_id, round, waitlist_id));
CREATE TABLE inbound_events (wamid text PRIMARY KEY, received_at timestamptz NOT NULL DEFAULT now());
`);

// Same statement as CLAIM_SQL in waitlist-refill.js.
const CLAIM_SQL = `
WITH o AS (
  SELECT o.id, o.slot_id, o.round, w.customer_id
  FROM offers o JOIN waitlist w ON w.id = o.waitlist_id
  WHERE o.id = $1 AND o.status IN ('pending', 'declined', 'failed')
), claimed AS (
  UPDATE slots s SET status = 'taken', taken_by = o.customer_id, refill = false
  FROM o
  WHERE s.id = o.slot_id AND s.round = o.round AND s.status = 'open' AND s.starts_at > now()
  RETURNING s.id AS slot_id, o.customer_id
)
INSERT INTO bookings (slot_id, customer_id)
SELECT slot_id, customer_id FROM claimed
RETURNING slot_id`;

const one = async (sql, params) => (await db.query(sql, params)).rows[0];
const service = await one("INSERT INTO services (name) VALUES ('Haircut') RETURNING id");
const ana = await one("INSERT INTO customers (name, phone) VALUES ('Ana', '16505550001') RETURNING id");
const ben = await one("INSERT INTO customers (name, phone) VALUES ('Ben', '16505550002') RETURNING id");
const slot = await one(
  "INSERT INTO slots (service_id, starts_at, refill, round) VALUES ($1, now() + interval '2 days', true, 1) RETURNING id",
  [service.id]);
const offerFor = async (customer) => {
  const w = await one(
    "INSERT INTO waitlist (customer_id, requested_service_id, opted_in_at, consent_text) VALUES ($1, $2, now(), 'test') RETURNING id",
    [customer.id, service.id]);
  return one("INSERT INTO offers (slot_id, round, wave, waitlist_id) VALUES ($1, 1, 1, $2) RETURNING id", [slot.id, w.id]);
};
const offerAna = await offerFor(ana);
const offerBen = await offerFor(ben);

assert.equal((await db.query(CLAIM_SQL, [offerAna.id])).rows.length, 1, "first Yes takes the slot");
assert.equal((await db.query(CLAIM_SQL, [offerBen.id])).rows.length, 0, "second Yes gets zero rows");
assert.equal((await db.query(CLAIM_SQL, [offerAna.id])).rows.length, 0, "a replayed Yes changes nothing");

const active = await db.query("SELECT customer_id FROM bookings WHERE slot_id = $1 AND status = 'active'", [slot.id]);
assert.equal(active.rows.length, 1);
assert.equal(String(active.rows[0].customer_id), String(ana.id));

const dedupe = "INSERT INTO inbound_events (wamid) VALUES ($1) ON CONFLICT DO NOTHING RETURNING wamid";
assert.equal((await db.query(dedupe, ["wamid.TEST"])).rows.length, 1);
assert.equal((await db.query(dedupe, ["wamid.TEST"])).rows.length, 0, "a retried webhook is skipped");

await assert.rejects(
  db.query("INSERT INTO bookings (slot_id, customer_id) VALUES ($1, $2)", [slot.id, ben.id]),
  "the unique index blocks a second active booking");

console.log("all claim checks passed");
await db.close();
```

Para ver el bloqueo en sí, corre dos conexiones contra un servidor Postgres real. La conexión A toma la fila dentro de una transacción abierta. El `UPDATE` idéntico de la conexión B espera, y después actualiza cero filas cuando A hace commit.

```js
// waitlist-race.test.js: two connections race for one slot on a real Postgres server.
// Node 18+. Run: npm install pg && DATABASE_URL=postgres://USER:PASSWORD@HOST:5432/DB node waitlist-race.test.js
const assert = require("node:assert/strict");
const { Client } = require("pg");

const CLAIM = "UPDATE race_slots SET status = 'taken', taken_by = $1 WHERE id = $2 AND status = 'open' RETURNING id";

async function main() {
  const a = new Client({ connectionString: process.env.DATABASE_URL });
  const b = new Client({ connectionString: process.env.DATABASE_URL });
  await a.connect();
  await b.connect();
  try {
    await a.query("DROP TABLE IF EXISTS race_slots");
    await a.query("CREATE TABLE race_slots (id int PRIMARY KEY, status text NOT NULL, taken_by text)");
    await a.query("INSERT INTO race_slots VALUES (1, 'open', NULL)");

    await a.query("BEGIN");
    const first = await a.query(CLAIM, ["ana", 1]); // A now holds the row lock
    let bFinished = false;
    const second = b.query(CLAIM, ["ben", 1]).then((result) => {
      bFinished = true;
      return result;
    });
    await new Promise((resolve) => setTimeout(resolve, 500));
    assert.equal(bFinished, false, "B should be waiting on A's row lock");
    await a.query("COMMIT");

    const result = await second;
    assert.equal(first.rowCount, 1);
    assert.equal(result.rowCount, 0, "B re-checked status = 'open' against the committed row");
    const { rows } = await a.query("SELECT taken_by FROM race_slots WHERE id = 1");
    assert.equal(rows[0].taken_by, "ana");
    console.log("one winner: ana; ben updated zero rows");
  } finally {
    await a.query("ROLLBACK").catch(() => {});
    await a.query("DROP TABLE IF EXISTS race_slots").catch(() => {});
    await a.end();
    await b.end();
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
```

## Cuando el ciclo se rompe

### Nadie responde

El temporizador envía la siguiente tanda cuando pasan `HOLD_MINUTES`, y se detiene `CUTOFF_MINUTES` antes del inicio. Cuando el último cliente en espera ya recibió una oferta, no sale nada más y el turno queda libre para la reserva normal.

### Dos toques, o un webhook reintentado

La inserción en `inbound_events` omite una entrega que ya vio. Un segundo toque aparte en la misma oferta encuentra el turno ya tomado por esa oferta, y el servicio no responde. Un Sí en otra oferta para el mismo turno recibe "turno ocupado".

### La oferta se retuvo o se descartó

Un estado `failed` marca la oferta como `failed`, y el 131049 se registra como límite de marketing. Una oferta que el TTL descartó nunca llega al teléfono, así que nunca llega un toque, y la siguiente tanda la cubre. Si el envío a Meta vence por timeout después de que Meta lo aceptó, el servicio registra `failed` aunque el cliente igual reciba la oferta. Por eso la toma acepta ofertas `failed`.

### El cliente se da de baja

STOP marca como `opted_out` todas las filas en espera de ese número, y la consulta de tandas las omite. Conserva el texto y la hora del consentimiento en la fila, para poder mostrar qué aceptó el cliente.

## Dónde encaja Z-API Omni

En un canal de la Meta Cloud API, Omni envía la oferta como plantilla personalizada con botones `QUICK_REPLY` por `POST /v1/channels/{channelId}/messages` con `content.type: "TEMPLATE"`. En la conexión por QR y en Telegram, que no tienen ventana de 24 horas, `INTERACTIVE_BUTTON` lleva hasta 3 botones. La documentación no muestra el JSON entrante de un toque de botón, así que prueba primero el mapeo del payload.

Los webhooks tienen hasta 7 intentos de entrega en 23 horas. Deduplica por `x-webhook-delivery-id`, guarda los IDs durante al menos 24 horas y ordena por `metadata.moment`, ya que el orden no está garantizado. La documentación no muestra ningún endpoint de difusión ni ningún planificador, así que tu worker envía cada oferta como una solicitud propia. Los webhooks están incluidos, sin límite.

[Ver la documentación](https://developer.omni.z-api.io/es)

*Equipo de Z-API Omni*
