# منسوخ شدہ appointment کو WhatsApp waitlist سے دوبارہ بھریں

> Appointment منسوخ ہو تو خالی slot، WhatsApp پر waitlist والے کسٹمرز کو پیش کریں، ایک Postgres UPDATE سے پہلی Yes کو دیں، اور دیر سے آنے والے ٹیپس کا جواب دیں۔

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

Waitlist refill وہ flow ہے جو خالی ہونے والا slot ان کسٹمرز کو پیش کرتا ہے جنہوں نے اس سروس کے کھلنے پر اطلاع مانگی تھی، اور جو پہلے قبول کرے اسے بک کر دیتا ہے۔ جب کوئی booking منسوخ ہو تو waitlist کے کسٹمرز کی ایک چھوٹی لہر کو "Yes, book it" (ہاں، بک کریں) اور "No thanks" (نہیں، شکریہ) والا ٹیمپلیٹ بھیجیں۔ Slot ایک واحد مشروط `UPDATE` سے پہلی Yes کو دیں، تاکہ Postgres ٹھیک ایک جیتنے والا چنے۔ بعد میں Yes ٹیپ کرنے والے ہر شخص کو اس ونڈو میں "slot taken" ملتا ہے جو اس کے ٹیپ نے کھولی۔

Cancellation کہیں سے بھی آ سکتی ہے۔ Calendly، `rescheduled: false` کے ساتھ `invitee.canceled` بھیجتا ہے، جیسا کہ [Calendly webhooks سے WhatsApp](/academy/ur/articles/calendly-webhook-whatsapp-confirmations-reminders/) میں دکھایا گیا ہے۔ Cal.com، `BOOKING_CANCELLED` بھیجتا ہے، جو [Cal.com webhooks سے WhatsApp یاد دہانیاں](/academy/ur/articles/cal-com-webhook-whatsapp-booking-reminders/) میں ہے۔ یہ مضمون آپ کی اپنی tables کو بنیادی ریکارڈ مانتا ہے، کیونکہ waitlist کو معلوم ہونا چاہیے کہ ہر slot کس کے پاس ہے۔

## Cancellation سے دوبارہ بھرے slot تک کا چکر

1. آپ کا سسٹم ایک booking منسوخ کرتا ہے اور refill سروس کو کال کرتا ہے، جو slot دوبارہ کھول دیتی ہے۔
2. سروس اس سروس کی waitlist کے کسٹمرز کی پہلی لہر کو offer ٹیمپلیٹ بھیجتی ہے۔
3. ٹیپ ایک `button` پیغام کے طور پر آتا ہے، جس کے payload میں offer ID ہوتی ہے۔
4. ایک `UPDATE`، slot پہلی Yes کو دیتا ہے، اور اسی statement میں booking row لکھی جاتی ہے۔
5. بعد والے ٹیپس کو "slot taken" ملتا ہے۔ اگر کوئی جواب نہ دے تو hold window کے بعد اگلی لہر جاتی ہے۔

لہریں اور hold window ڈیزائن کے فیصلے ہیں۔ کوئی ذریعہ یہ عدد نہیں دیتا کہ کتنے لوگ offer کا جواب دیتے ہیں، اس لیے `WAVE_SIZE` اور `HOLD_MINUTES` کو اپنے data پر tune کریں۔

## Offer کس category میں آتا ہے

Meta کا صفحہ یہ معاملہ طے نہیں کرتا، اس لیے دونوں نتائج کے لیے ڈیزائن کریں۔ Utility ٹیمپلیٹ کا «غیر تشہیری ہونا لازمی ہے» اور «ساتھ ہی صارف سے مخصوص یا اس کا مانگا ہوا ہونا بھی لازمی ہے (واضح طور پر اس کے آرڈر، اکاؤنٹ، سروسز یا transactions سے متعلق)» ([template categorization](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/template-categorization.md)، رسائی 2026-11-27)۔

یہی صفحہ "انہوں نے مانگا تھا، اس لیے utility ہے" والی دلیل کے خلاف جاتا ہے۔ اس کی مارکیٹنگ مثالوں میں ایک retargeting پیغام ہے: "We found a {{car}} that meets your saved search. Log in to our app to view." Meta مزید کہتی ہے: «یہ مارکیٹنگ ہیں، چاہے صارفین نے مانگے ہوں۔» Waitlist، محفوظ کی گئی search کے قریب ہے۔ صفحے پر waitlist کی کوئی مثال ہے ہی نہیں۔

ہماری رائے: utility کا سب سے مضبوط کیس وہ ہے جو صرف ایک مخصوص slot پیش کرے، ٹھیک اسی سروس کا جس کی waitlist میں شخص شامل ہوا تھا، اور کچھ نہیں۔ یہ اس درخواست کا حوالہ دیتا ہے جو اس نے اپنی پسند کی سروس کے بارے میں کی تھی۔ "اس ہفتے کے دوسرے اوقات" یا کوئی دوسری سروس شامل کریں تو یہ ایک تجویز بن جاتی ہے، جو مارکیٹنگ لگتی ہے۔ Meta کے صفحے پر ملا جلا مواد مارکیٹنگ ہے۔

Meta پھر بھی اسے مارکیٹنگ قرار دے سکتی ہے۔ ایک warning کے بعد «utility سے marketing میں category کی تبدیلیاں بغیر پیشگی اطلاع کے فوری ہو جاتی ہیں۔» اس کے بعد کم از کم 7 دن کے لیے utility rate limiting آتی ہے۔ پھر utility restriction لگتی ہے، 7 دن کی، یا بار بار خلاف ورزی پر 30 دن کی، اور اس دوران آپ کے تمام utility ٹیمپلیٹس MARKETING بن جاتے ہیں۔ آخری قدم 30 دن کی portfolio restriction ہے۔ اس لیے سروس میں ایک switch ہے، `OFFER_CATEGORY`، جسے ٹیمپلیٹ کی category بدلنے پر آپ `MARKETING` کر دیتے ہیں۔

`MARKETING` کے ساتھ سروس slot صرف ان کسٹمرز کو پیش کرتی ہے جنہوں نے مارکیٹنگ کی رضامندی بھی دی ہو۔ پھر فی صارف مارکیٹنگ کی حدیں لاگو ہوتی ہیں، اور Meta کوئی پیغام [error 131049](/academy/ur/articles/whatsapp-error-131049-marketing-message-not-delivered/) کے ساتھ روک سکتی ہے۔ لہر کے کچھ وصول کنندگان کو شاید کچھ نہ ملے، جو لہروں میں بھیجنے کی ایک اور وجہ ہے۔ وسیع تر قواعد [WhatsApp ٹیمپلیٹ categories](/academy/ur/articles/whatsapp-template-categories-marketing-utility-authentication/) میں ہیں۔

## درخواست کو waitlist row کے ساتھ محفوظ کریں

Waitlist row آپ کا ثبوت ہے کہ شخص نے خود مانگا تھا۔ وہ سروس محفوظ کریں جو اس نے مانگی (`requested_service_id`)، اس نے کب رضامندی دی (`opted_in_at`) اور رضامندی کے وہ الفاظ جو اس نے دیکھے۔ ایک الگ `marketing_opt_in` flag، متبادل صورت کے لیے ہے۔ اور کیا ریکارڈ کرنا ہے، یہ [WhatsApp opt-in کیسے جمع کریں](/academy/ur/articles/whatsapp-opt-in-how-to-collect-consent/) میں ہے۔

```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()
);
```

آپ کا معمول کا booking flow، booking لکھتے وقت `slots.status` کو `taken` کرے، تاکہ refill سروس بھی وہی state دیکھے۔

## ایک UPDATE جیتنے والے کا فیصلہ کرتا ہے

دو کسٹمرز چند milliseconds کے فرق سے Yes ٹیپ کر سکتے ہیں، اور دو webhook deliveries ایک ساتھ دو connections پر چل سکتی ہیں۔ Postgres یہ معاملہ `SELECT ... FOR UPDATE` کے بغیر طے کر دیتا ہے۔ Read Committed میں، جو default ہے، «اپ ڈیٹ کرنے والا دوسرا transaction، پہلے اپ ڈیٹ کرنے والے transaction کے commit یا roll back ہونے کا انتظار کرے گا» ([transaction isolation](https://www.postgresql.org/docs/current/transaction-iso.html)، رسائی 2026-11-27)۔ پھر «command کی search condition (`WHERE` clause) دوبارہ جانچی جاتی ہے، یہ دیکھنے کے لیے کہ row کا اپ ڈیٹ شدہ version اب بھی search condition پر پورا اترتا ہے یا نہیں۔»

اس لیے `UPDATE slots SET status = 'taken' ... WHERE id = $1 AND status = 'open' AND starts_at > now()` میں ٹھیک ایک transaction match کرتا ہے۔ دوسرا، commit شدہ row پر `status = 'open'` دوبارہ چیک کرتا ہے، `taken` پاتا ہے، اور صفر rows اپ ڈیٹ کرتا ہے۔ سروس booking اسی statement میں، data بدلنے والے CTE کے ساتھ، لکھتی ہے، اس لیے کوئی slot بغیر booking کے کبھی taken نہیں ہوتا۔ `starts_at > now()` والی شرط ایسے وقت کی دیر سے آنے والی Yes رد کرتی ہے جو گزر چکا ہو۔

Webhook retry ایک ہی ٹیپ دو بار پہنچا سکتا ہے۔ سروس ہر inbound wamid کو `ON CONFLICT DO NOTHING` کے ساتھ `inbound_events` میں insert کرتی ہے اور صرف تب آگے بڑھتی ہے جب ایک row واپس آئے۔ Postgres نوٹ کرتا ہے کہ ایسے insert میں «کسی دوسرے transaction کے نتیجے کی وجہ سے کسی row کا insertion آگے نہیں بڑھ سکتا»۔ تب اسی ٹیپ کی دوسری delivery کچھ نہیں کرتی۔ اس کے بغیر بھی، دہرائی گئی Yes دیکھتی ہے کہ slot اس کے اپنے offer کے پاس ہے، اور کچھ نہیں بدلتی۔

اگر آپ sends کو worker pool میں لے جائیں تو jobs کو `SELECT ... FOR UPDATE SKIP LOCKED` سے claim کریں، جیسا کہ [WhatsApp webhook queue architecture](/academy/ur/articles/whatsapp-webhook-queue-architecture-workers/) میں سمجھایا گیا ہے۔

## Offer لہروں میں بھیجیں

ٹیمپلیٹ میں سروس، تاریخ اور وقت کا نام ہوتا ہے، اور یہ بتاتا ہے کہ slot کسے ملے گا۔ اسے دو quick replies والے utility ٹیمپلیٹ کے طور پر بنائیں۔

| ٹیمپلیٹ | Body | بٹن |
| --- | --- | --- |
| `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. | Quick replies: "Yes, book it"، "No thanks" |

بھیجتے وقت ہر بٹن کے payload میں offer ID ہوتی ہے، `offer:<id>:yes` اور `offer:<id>:no` کی شکل میں۔ ٹیپ `type: "button"` کے طور پر `button.payload`، `button.text` اور `context.id` کے ساتھ واپس آتا ہے، جہاں `context.id` اس offer کا wamid ہے ([button webhook reference](https://developers.facebook.com/documentation/business-messaging/whatsapp/webhooks/reference/messages/button)، رسائی 2026-11-25)۔ سروس پہلے payload پڑھتی ہے، اور ناکامی پر `context.id` کو محفوظ wamid سے ملاتی ہے۔

ٹیمپلیٹ پر مختصر TTL رکھیں۔ Utility ٹیمپلیٹس کے لیے `message_send_ttl_seconds`، 30 سیکنڈ سے 12 گھنٹے تک ہو سکتا ہے، اور یہ ٹیمپلیٹ کا حصہ ہے، send کا نہیں ([time-to-live](https://developers.facebook.com/documentation/business-messaging/whatsapp/templates/time-to-live)، رسائی 2026-11-25)۔ اسے اپنی hold window کے قریب رکھیں، تاکہ جو offer فون تک دیر سے پہنچے وہ slot جانے کے بعد پہنچنے کی بجائے drop ہو جائے۔

ٹیپ 24 گھنٹے کی ونڈو کھول دیتا ہے، اس لیے "Booked" اور "slot taken"، free-form text کے طور پر جاتے ہیں۔ یہ service messages ہیں، اور [اکتوبر 2026 سے Meta کے service message charges](/academy/ur/articles/meta-whatsapp-service-message-charges-october-2026/) ان کی قیمت سمجھاتا ہے۔ جو کسٹمرز کبھی ٹیپ نہیں کرتے انہیں مزید کچھ نہیں جاتا۔ انہیں یہ بتانا کہ slot جا چکا ہے، ہر ایک کے لیے ایک اور ٹیمپلیٹ مانگتا۔

## Refill سروس

یہ فائل Node 18 یا اس سے نئے، Express 4 اور node-postgres پر، اوپر والے schema کے ساتھ چلتی ہے۔ آپ کا booking سسٹم cancellation کے بعد `POST /slots/:id/cancel` کو کال کرتا ہے۔ Hold window گزرنے پر ایک timer اگلی لہر بھیجتا ہے۔

```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}`));
```

Offer کی states یہ ہیں: `pending`، `won`، `lost`، `declined` اور `failed`۔ جس کسٹمر نے "No thanks" ٹیپ کیا ہو وہ بعد میں بھی Yes ٹیپ کر کے جیت سکتا ہے اگر slot کھلا ہو، کیونکہ claim، `declined` کو قبول کرتا ہے۔ STOP والا جواب کسٹمر کو ان تمام waitlists سے نکال دیتا ہے جن میں وہ ہو۔

## Claim کو PGlite پر test کریں، اور race کو Postgres پر

PGlite، Node کے اندر Postgres چلاتا ہے، جو CI میں SQL چیک کرنے کے لیے کارآمد ہے۔ اس کے docs اس چیک کی حد بھی بتاتے ہیں: «PGlite کے پاس database سے صرف ایک exclusive connection ہوتا ہے» ([PGlite docs](https://pglite.dev/docs/)، رسائی 2026-11-27)۔ Statements ایک کے بعد ایک چلتی ہیں، اس لیے PGlite test، صفر یا ایک row والی منطق اور بے ضرر replay ثابت کرتا ہے۔ یہ row lock پر انتظار کرتے دو connections کو دوبارہ پیدا نہیں کر سکتا۔

```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();
```

Lock کو خود دیکھنے کے لیے، ایک اصلی Postgres server کے خلاف دو connections چلائیں۔ Connection A ایک کھلے transaction کے اندر row لیتا ہے۔ Connection B کا بالکل ویسا ہی `UPDATE` انتظار کرتا ہے، اور A کے commit ہوتے ہی صفر rows اپ ڈیٹ کرتا ہے۔

```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);
});
```

## جب چکر ٹوٹ جائے

### کوئی جواب نہیں دیتا

`HOLD_MINUTES` گزرنے پر timer اگلی لہر بھیجتا ہے، اور شروع ہونے سے `CUTOFF_MINUTES` پہلے رک جاتا ہے۔ جب انتظار کرنے والے آخری کسٹمر کو بھی offer مل چکا ہو تو مزید کچھ نہیں جاتا، اور slot معمول کی booking کے لیے کھلا رہتا ہے۔

### دو ٹیپ، یا retry ہوا webhook

`inbound_events` والا insert پہلے دیکھی گئی delivery چھوڑ دیتا ہے۔ اسی offer پر الگ سے کیا گیا دوسرا ٹیپ دیکھتا ہے کہ slot پہلے ہی اسی offer کے پاس ہے، اور سروس خاموش رہتی ہے۔ اسی slot کے کسی دوسرے offer پر Yes کو "slot taken" ملتا ہے۔

### Offer روک لیا گیا یا drop ہو گیا

`failed` status، offer کو `failed` کر دیتا ہے، اور 131049 کو مارکیٹنگ کی حد کے طور پر log کیا جاتا ہے۔ جو offer، TTL نے drop کیا وہ فون تک کبھی نہیں پہنچتا، اس لیے کوئی ٹیپ نہیں آتا، اور اگلی لہر اس کی کمی پوری کرتی ہے۔ اگر Meta کا send قبول ہونے کے بعد time out ہو جائے تو سروس `failed` ریکارڈ کرتی ہے جبکہ کسٹمر کو offer پھر بھی مل سکتا ہے۔ اسی وجہ سے claim، `failed` offers قبول کرتا ہے۔

### کسٹمر opt out کرتا ہے

STOP اس نمبر کی ہر انتظار والی row کو `opted_out` کر دیتا ہے، اور لہر والی query انہیں چھوڑ دیتی ہے۔ رضامندی کا text اور وقت row پر رکھیں، تاکہ آپ دکھا سکیں کہ کسٹمر نے کس چیز پر رضامندی دی تھی۔

## Z-API Omni کہاں کام آتا ہے

Meta Cloud API channel پر Omni، offer کو `QUICK_REPLY` بٹنوں والے custom ٹیمپلیٹ کے طور پر `POST /v1/channels/{channelId}/messages` سے، `content.type: "TEMPLATE"` کے ساتھ، بھیجتا ہے۔ QR connection اور Telegram پر، جہاں 24 گھنٹے کی کوئی ونڈو نہیں، `INTERACTIVE_BUTTON` زیادہ سے زیادہ 3 بٹن رکھتا ہے۔ Docs بٹن ٹیپ کا inbound JSON نہیں دکھاتے، اس لیے پہلے payload mapping test کریں۔

Webhooks کو 23 گھنٹوں کے اندر delivery کی زیادہ سے زیادہ 7 کوششیں ملتی ہیں۔ `x-webhook-delivery-id` پر dedupe کریں، IDs کم از کم 24 گھنٹے رکھیں، اور `metadata.moment` سے ترتیب دیں، کیونکہ ترتیب کی ضمانت نہیں۔ Docs میں نہ کوئی broadcast endpoint ہے اور نہ scheduler، اس لیے آپ کا worker ہر offer الگ request کے طور پر بھیجتا ہے۔ Webhooks بغیر حد کے شامل ہیں۔

[دستاویزات دیکھیں](https://developer.omni.z-api.io/en)

*Z-API Omni ٹیم*
