Labeeny API v1

Full example

A shop's backend in one Node.js file. It does the whole flow: logs in, gets a price, places the order, follows it, receives webhooks, keeps the captain's proof photos and sends your customer a push notification with Firebase Cloud Messaging (FCM) at every step.

Your customer's app  ──►  Your backend (server.js)  ──►  Labeeny API
         ▲                       │      ◄── webhooks ──
         └──── FCM push ◄────────┘

The sections below make up server.js, top to bottom. Your app only ever talks to your backend, and your backend is the only thing that talks to Labeeny. Each step is explained in the guide, and every field is in the reference.

Your app callsYour backend then
POST /api/quotesasks Labeeny for a price (estimateDelivery).
POST /api/ordersplaces the delivery (createDelivery) and keeps the phone's FCM token.
GET /api/orders/:orderIdreturns the status, the captain and where they are.
GET /api/orders/:orderId/photos/:typereturns a proof photo.

Labeeny calls POST /labeeny/webhook. That's where your customer's notifications and the photo downloads start.

1. Setup

You need Node.js 18 or newer, your Labeeny credential (Before you start) and a Firebase project for your app's notifications. The orders are kept in memory so the example runs as it is: use your database instead.

// server.js: a shop's backend that delivers its orders with Labeeny.
// Node.js 18 or newer:  npm install express@5 firebase-admin
const crypto = require("crypto");
const express = require("express");
const admin = require("firebase-admin");

// Your Firebase service account, from GOOGLE_APPLICATION_CREDENTIALS.
admin.initializeApp();
const app = express();

// Your database. In memory here, so the example runs on its own.
// your order id → {labeenyOrderId, deviceToken, status, lastEventAt, tracking, photos}
const orders = new Map();
const handledEvents = new Set(); // webhook ids already handled

// Where your shop's deliveries start. Or save a default pickup on the account page
// and leave pickup out.
const SHOP_PICKUP = {lat: 36.2021, lng: 37.1343, address: "محل ١٢، العزيزية"};

2. Log in

One token for the whole backend, renewed a minute before its hour is up. If Labeeny answers that the token expired anyway, the call logs in again and tries once more.

const {GRAPHQL_URL, STORAGE_URL, LABEENY_CLIENT_ID, LABEENY_CLIENT_SECRET} = process.env;

let cachedToken = null; // {value, expiresAt}: one token for the whole backend

async function labeenyToken() {
  const stillValid = cachedToken && Date.now() < cachedToken.expiresAt - 60_000;
  if (stillValid) return cachedToken.value;

  const response = await fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {"Content-Type": "application/json"}, // no Authorization header to log in
    body: JSON.stringify({
      query: `mutation ($id: String!, $secret: String!) {
        loginClient(clientId: $id, clientSecret: $secret) { accessToken expiresIn }
      }`,
      variables: {id: LABEENY_CLIENT_ID, secret: LABEENY_CLIENT_SECRET},
    }),
  });
  const {data, errors} = await response.json();
  if (errors) throw new Error(`Labeeny login failed: ${errors[0].message}`);

  const {accessToken, expiresIn} = data.loginClient;
  cachedToken = {value: accessToken, expiresAt: Date.now() + expiresIn * 1000};
  return accessToken;
}

class LabeenyError extends Error {}

// Every GraphQL call goes through this. An expired token logs in again once.
async function labeeny(query, variables = {}, isRetry = false) {
  const response = await fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${await labeenyToken()}`,
    },
    body: JSON.stringify({query, variables}),
  });
  const {data, errors} = await response.json();
  if (!errors) return data;

  const tokenExpired = errors[0].extensions?.code === "invalid-jwt";
  if (tokenExpired && !isRetry) {
    cachedToken = null;
    return labeeny(query, variables, true);
  }
  throw new LabeenyError(errors[0].message); // e.g. "estimate-not-found"
}

3. Get a price

The price is valid for 10 minutes. Write addresses in Arabic: the captain reads them.

// Your app asks for a price before the customer confirms.
// In your app, the customer comes from your own login; here it's in the request.
app.post("/api/quotes", express.json(), async (req, res) => {
  const {customer, dropoff} = req.body; // {name, phone}, {lat, lng, address}

  const {estimateDelivery: estimate} = await labeeny(`
    mutation ($customer: ApiCustomerInput!, $pickup: ApiLocationInput,
              $dropoff: ApiLocationInput!) {
      estimateDelivery(customer: $customer, pickup: $pickup, dropoff: $dropoff) {
        estimate_id total_price currency expires_at
      }
    }`, {customer, pickup: SHOP_PICKUP, dropoff});

  res.json({
    estimateId: estimate.estimate_id,
    price: estimate.total_price, // show this to the customer
    currency: estimate.currency,
    expiresAt: estimate.expires_at, // 10 minutes
  });
});

4. Place the order

Your own order id goes to Labeeny as external_reference, and comes back in every webhook. That's how the webhook finds the order below. Your app also sends the customer's FCM token here, so you can notify that phone later.

// The customer accepted the price.
// deviceToken is the FCM token of their phone, sent by your app.
app.post("/api/orders", express.json(), async (req, res) => {
  const {orderId, estimateId, deviceToken, notes} = req.body; // orderId: your own order id

  // Safe to retry: the same estimateId and orderId give back the same Labeeny order.
  const {createDelivery} = await labeeny(`
    mutation ($estimateId: uuid!, $reference: String!, $notes: String) {
      createDelivery(
        estimate_id: $estimateId, external_reference: $reference, notes: $notes
      ) { order_id }
    }`, {estimateId, reference: orderId, notes});

  orders.set(orderId, {
    labeenyOrderId: createDelivery.order_id,
    deviceToken,
    status: "pending_acceptance",
    lastEventAt: "",
    tracking: null, // the last read of the order from Labeeny (below)
    photos: {},     // proof photos by type (below)
  });
  res.status(201).json({orderId, status: "pending_acceptance"});
});

5. Follow the order

Your app asks your backend, never Labeeny. Each order is read from Labeeny at most every 15 seconds, however many times the app asks. Have your app ask every 15 seconds while the captain is moving (on_way, picked_up, in_transit), and stop after that.

const READ_INTERVAL_MS = 15_000; // read an order from Labeeny at most every 15 seconds

// Your app shows the order and the captain on a map. While the status is on_way,
// picked_up or in_transit, it calls this every 15 seconds. However many phones ask,
// each order is read from Labeeny once per 15 seconds.
app.get("/api/orders/:orderId", async (req, res) => {
  const {orderId} = req.params;
  const order = orders.get(orderId);
  if (!order) return res.sendStatus(404);

  const needsFreshRead =
    !order.tracking || Date.now() - order.tracking.readAt >= READ_INTERVAL_MS;
  if (needsFreshRead) {
    const {orders_by_pk: labeenyOrder} = await labeeny(`
      query ($id: uuid!) {
        orders_by_pk(id: $id) {
          status
          captain { displayName phoneNumber avatarUrl }
          captain_location
        }
      }`, {id: order.labeenyOrderId});

    order.status = labeenyOrder.status; // also catches up on a webhook you missed
    order.tracking = {
      readAt: Date.now(),
      captain: labeenyOrder.captain, // null until a captain accepts
      // {lat, lng, updated_at} while the captain is moving, otherwise null
      captainLocation: labeenyOrder.captain_location,
    };
  }

  res.json({
    orderId,
    status: order.status,
    captain: order.tracking.captain,
    captainLocation: order.tracking.captainLocation,
    photos: Object.keys(order.photos), // e.g. ["pickup_proof"]: see /photos/:type below
  });
});

6. Webhook

Check the signature, answer 200 straight away, then do the work. Each event is handled once, and an event older than the last one handled is skipped, because events can arrive out of order.

const {LABEENY_WEBHOOK_SECRET} = process.env; // shown once when you save the webhook URL

function isFromLabeeny(signatureHeader, rawBody) {
  // The header looks like "t=1763460300,v1=5f2c…"
  const parts = Object.fromEntries(
    signatureHeader.split(",").map((part) => part.split("=")),
  );
  const expected = crypto.createHmac("sha256", LABEENY_WEBHOOK_SECRET)
    .update(`${parts.t}.${rawBody}`)
    .digest("hex");

  const signatureMatches = parts.v1?.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
  const isRecent = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
  return signatureMatches && isRecent;
}

// express.raw: the signature is checked on the body exactly as it arrived.
app.post("/labeeny/webhook", express.raw({type: "application/json"}), (req, res) => {
  const rawBody = req.body.toString();
  const signature = req.get("Labeeny-Signature") ?? "";
  if (!isFromLabeeny(signature, rawBody)) return res.sendStatus(401);
  res.sendStatus(200); // answer within 5 seconds, then do the work

  const event = JSON.parse(rawBody);
  if (event.type === "ping" || handledEvents.has(event.id)) return;
  handledEvents.add(event.id);
  handleOrderEvent(event)
    .catch((error) => console.error(`Labeeny event ${event.id}:`, error));
});

async function handleOrderEvent(event) {
  const {external_reference: orderId, status} = event.data;
  const order = orders.get(orderId);
  if (!order) return;

  // Events can arrive out of order: skip one older than the last handled.
  const arrivedLate = event.created_at < order.lastEventAt;
  if (arrivedLate) return;
  order.lastEventAt = event.created_at;
  order.status = status;
  order.tracking = null; // the next read gets the new captain details

  await notifyCustomer(order, orderId, event.data);

  if (status === "picked_up" || status === "delivered") {
    await saveProofPhotos(order);
    // A photo can arrive a little after the status: look once more a minute later.
    setTimeout(() => saveProofPhotos(order).catch(console.error), 60_000);
  }
}

7. Proof photos

The captain photographs the item at pickup (pickup_proof) and at your customer's door (delivery_proof). The webhook saves them when it receives picked_up and delivered, and your app gets them from your backend, because the Labeeny download needs your token.

async function saveProofPhotos(order) {
  const {orders_by_pk: labeenyOrder} = await labeeny(`
    query ($id: uuid!) {
      orders_by_pk(id: $id) {
        order_files(where: {type: {_in: ["pickup_proof", "delivery_proof"]}}) {
          type file_id
        }
      }
    }`, {id: order.labeenyOrderId});

  for (const file of labeenyOrder.order_files) {
    if (order.photos[file.type]) continue; // already saved
    order.photos[file.type] = await downloadOrderFile(file.file_id);
  }
}

async function downloadOrderFile(fileId) {
  const response = await fetch(`${STORAGE_URL}/files/${fileId}`, {
    headers: {"Authorization": `Bearer ${await labeenyToken()}`},
  });
  if (!response.ok) throw new Error(`Labeeny file ${fileId}: ${response.status}`);
  return {
    contentType: response.headers.get("content-type"), // e.g. "image/jpeg"
    bytes: Buffer.from(await response.arrayBuffer()),
  };
}

// Your app shows the photo from your backend: the Labeeny download needs your token.
// In production, save the bytes to your own storage instead of memory.
app.get("/api/orders/:orderId/photos/:type", (req, res) => {
  const photo = orders.get(req.params.orderId)?.photos[req.params.type];
  if (!photo) return res.sendStatus(404);
  res.type(photo.contentType).send(photo.bytes);
});

8. Notify your customer

We don't text your customer: you tell them. Here each status sends a notification to the phone that placed the order, with firebase-admin. Write the messages in your customers' language. If the app was removed from the phone, its token is dropped.

// What the customer reads for each status. Statuses with no message send no notification.
function customerMessage({status, previous_status: previousStatus, captain}) {
  switch (status) {
    case "pending_acceptance":
      // Back to pending: the captain dropped it. Just placed: no notification.
      return previousStatus ? "نبحث عن كابتن جديد لطلبك" : null;
    case "accepted_by_driver":
      return captain
        ? `الكابتن ${captain.name} قبل طلبك`
        : "وجدنا كابتن لطلبك";
    case "on_way":
      return "الكابتن في طريقه لاستلام طلبك";
    case "picked_up":
      return "استلم الكابتن طلبك";
    case "in_transit":
      return "طلبك في الطريق إليك";
    case "delivered":
      return "تم توصيل طلبك";
    case "cancelled":
      return "تم إلغاء طلبك";
    default:
      return null;
  }
}

async function notifyCustomer(order, orderId, eventData) {
  const body = customerMessage(eventData);
  if (!body || !order.deviceToken) return;

  try {
    await admin.messaging().send({
      token: order.deviceToken,
      notification: {title: `طلب ${orderId}`, body},
      // Your app opens the order from these. FCM data values are strings only.
      data: {orderId, status: eventData.status},
    });
  } catch (error) {
    const appRemoved = error.code === "messaging/registration-token-not-registered";
    if (!appRemoved) throw error;
    order.deviceToken = null;
  }
}

9. Errors and start

An expired price tells your app to ask for a new one. Any other failure is a 502.

// Labeeny errors your app can act on; everything else is "try again later".
app.use((error, req, res, next) => {
  if (error instanceof LabeenyError && error.message === "estimate-not-found") {
    return res.status(409).json({error: "price_expired"}); // ask for a new price
  }
  console.error(error);
  res.status(502).json({error: "delivery_unavailable"});
});

app.listen(process.env.PORT ?? 3000);

Try it

These are real deliveries. Every order you place sends a real captain. Cancel a test order straight away (Cancel).
npm install express@5 firebase-admin

export GRAPHQL_URL=""
export STORAGE_URL=""
export LABEENY_CLIENT_ID="cid_…"
export LABEENY_CLIENT_SECRET="csk_…"
export LABEENY_WEBHOOK_SECRET="lab_…"
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/firebase-service-account.json"

node server.js

In another terminal, do what your app would do:

# 1. A price
curl -s localhost:3000/api/quotes \
  -H "Content-Type: application/json" \
  -d '{"customer": {"name": "Rami Haddad", "phone": "0933123456"},
       "dropoff": {"lat": 36.2105, "lng": 37.1550, "address": "بناء ٤، الطابق الثاني"}}'

# {"estimateId": "8f14e45f-…", "price": 15000, "currency": "SYP", "expiresAt": "…"}

# 2. The order, with the FCM token of your test phone
curl -s localhost:3000/api/orders \
  -H "Content-Type: application/json" \
  -d '{"orderId": "ORDER-1042", "estimateId": "8f14e45f-…", "deviceToken": "…"}'

# 3. Follow it
curl -s localhost:3000/api/orders/ORDER-1042

# {"orderId": "ORDER-1042", "status": "on_way", "captain": {"displayName": "Ahmad", …},
#  "captainLocation": {"lat": 36.2051, "lng": 37.1402, "updated_at": "…"}, "photos": []}

# 4. After pickup, the photo
curl -s localhost:3000/api/orders/ORDER-1042/photos/pickup_proof -o pickup_proof.jpg

Webhooks need a public https address: Labeeny can't call localhost. Put your machine behind an https tunnel (cloudflared, ngrok…), save https://…/labeeny/webhook on the account page, put the secret it shows in LABEENY_WEBHOOK_SECRET, and restart. Saving sends a ping, which this example answers with 200.

The whole file

All the sections above as one file, to copy.

server.js
// server.js: a shop's backend that delivers its orders with Labeeny.
// Node.js 18 or newer:  npm install express@5 firebase-admin
const crypto = require("crypto");
const express = require("express");
const admin = require("firebase-admin");

// Your Firebase service account, from GOOGLE_APPLICATION_CREDENTIALS.
admin.initializeApp();
const app = express();

// Your database. In memory here, so the example runs on its own.
// your order id → {labeenyOrderId, deviceToken, status, lastEventAt, tracking, photos}
const orders = new Map();
const handledEvents = new Set(); // webhook ids already handled

// Where your shop's deliveries start. Or save a default pickup on the account page
// and leave pickup out.
const SHOP_PICKUP = {lat: 36.2021, lng: 37.1343, address: "محل ١٢، العزيزية"};

const {GRAPHQL_URL, STORAGE_URL, LABEENY_CLIENT_ID, LABEENY_CLIENT_SECRET} = process.env;

let cachedToken = null; // {value, expiresAt}: one token for the whole backend

async function labeenyToken() {
  const stillValid = cachedToken && Date.now() < cachedToken.expiresAt - 60_000;
  if (stillValid) return cachedToken.value;

  const response = await fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {"Content-Type": "application/json"}, // no Authorization header to log in
    body: JSON.stringify({
      query: `mutation ($id: String!, $secret: String!) {
        loginClient(clientId: $id, clientSecret: $secret) { accessToken expiresIn }
      }`,
      variables: {id: LABEENY_CLIENT_ID, secret: LABEENY_CLIENT_SECRET},
    }),
  });
  const {data, errors} = await response.json();
  if (errors) throw new Error(`Labeeny login failed: ${errors[0].message}`);

  const {accessToken, expiresIn} = data.loginClient;
  cachedToken = {value: accessToken, expiresAt: Date.now() + expiresIn * 1000};
  return accessToken;
}

class LabeenyError extends Error {}

// Every GraphQL call goes through this. An expired token logs in again once.
async function labeeny(query, variables = {}, isRetry = false) {
  const response = await fetch(GRAPHQL_URL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "Authorization": `Bearer ${await labeenyToken()}`,
    },
    body: JSON.stringify({query, variables}),
  });
  const {data, errors} = await response.json();
  if (!errors) return data;

  const tokenExpired = errors[0].extensions?.code === "invalid-jwt";
  if (tokenExpired && !isRetry) {
    cachedToken = null;
    return labeeny(query, variables, true);
  }
  throw new LabeenyError(errors[0].message); // e.g. "estimate-not-found"
}

// Your app asks for a price before the customer confirms.
// In your app, the customer comes from your own login; here it's in the request.
app.post("/api/quotes", express.json(), async (req, res) => {
  const {customer, dropoff} = req.body; // {name, phone}, {lat, lng, address}

  const {estimateDelivery: estimate} = await labeeny(`
    mutation ($customer: ApiCustomerInput!, $pickup: ApiLocationInput,
              $dropoff: ApiLocationInput!) {
      estimateDelivery(customer: $customer, pickup: $pickup, dropoff: $dropoff) {
        estimate_id total_price currency expires_at
      }
    }`, {customer, pickup: SHOP_PICKUP, dropoff});

  res.json({
    estimateId: estimate.estimate_id,
    price: estimate.total_price, // show this to the customer
    currency: estimate.currency,
    expiresAt: estimate.expires_at, // 10 minutes
  });
});

// The customer accepted the price.
// deviceToken is the FCM token of their phone, sent by your app.
app.post("/api/orders", express.json(), async (req, res) => {
  const {orderId, estimateId, deviceToken, notes} = req.body; // orderId: your own order id

  // Safe to retry: the same estimateId and orderId give back the same Labeeny order.
  const {createDelivery} = await labeeny(`
    mutation ($estimateId: uuid!, $reference: String!, $notes: String) {
      createDelivery(
        estimate_id: $estimateId, external_reference: $reference, notes: $notes
      ) { order_id }
    }`, {estimateId, reference: orderId, notes});

  orders.set(orderId, {
    labeenyOrderId: createDelivery.order_id,
    deviceToken,
    status: "pending_acceptance",
    lastEventAt: "",
    tracking: null, // the last read of the order from Labeeny (below)
    photos: {},     // proof photos by type (below)
  });
  res.status(201).json({orderId, status: "pending_acceptance"});
});

const READ_INTERVAL_MS = 15_000; // read an order from Labeeny at most every 15 seconds

// Your app shows the order and the captain on a map. While the status is on_way,
// picked_up or in_transit, it calls this every 15 seconds. However many phones ask,
// each order is read from Labeeny once per 15 seconds.
app.get("/api/orders/:orderId", async (req, res) => {
  const {orderId} = req.params;
  const order = orders.get(orderId);
  if (!order) return res.sendStatus(404);

  const needsFreshRead =
    !order.tracking || Date.now() - order.tracking.readAt >= READ_INTERVAL_MS;
  if (needsFreshRead) {
    const {orders_by_pk: labeenyOrder} = await labeeny(`
      query ($id: uuid!) {
        orders_by_pk(id: $id) {
          status
          captain { displayName phoneNumber avatarUrl }
          captain_location
        }
      }`, {id: order.labeenyOrderId});

    order.status = labeenyOrder.status; // also catches up on a webhook you missed
    order.tracking = {
      readAt: Date.now(),
      captain: labeenyOrder.captain, // null until a captain accepts
      // {lat, lng, updated_at} while the captain is moving, otherwise null
      captainLocation: labeenyOrder.captain_location,
    };
  }

  res.json({
    orderId,
    status: order.status,
    captain: order.tracking.captain,
    captainLocation: order.tracking.captainLocation,
    photos: Object.keys(order.photos), // e.g. ["pickup_proof"]: see /photos/:type below
  });
});

const {LABEENY_WEBHOOK_SECRET} = process.env; // shown once when you save the webhook URL

function isFromLabeeny(signatureHeader, rawBody) {
  // The header looks like "t=1763460300,v1=5f2c…"
  const parts = Object.fromEntries(
    signatureHeader.split(",").map((part) => part.split("=")),
  );
  const expected = crypto.createHmac("sha256", LABEENY_WEBHOOK_SECRET)
    .update(`${parts.t}.${rawBody}`)
    .digest("hex");

  const signatureMatches = parts.v1?.length === expected.length &&
    crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(parts.v1));
  const isRecent = Math.abs(Date.now() / 1000 - Number(parts.t)) < 300;
  return signatureMatches && isRecent;
}

// express.raw: the signature is checked on the body exactly as it arrived.
app.post("/labeeny/webhook", express.raw({type: "application/json"}), (req, res) => {
  const rawBody = req.body.toString();
  const signature = req.get("Labeeny-Signature") ?? "";
  if (!isFromLabeeny(signature, rawBody)) return res.sendStatus(401);
  res.sendStatus(200); // answer within 5 seconds, then do the work

  const event = JSON.parse(rawBody);
  if (event.type === "ping" || handledEvents.has(event.id)) return;
  handledEvents.add(event.id);
  handleOrderEvent(event)
    .catch((error) => console.error(`Labeeny event ${event.id}:`, error));
});

async function handleOrderEvent(event) {
  const {external_reference: orderId, status} = event.data;
  const order = orders.get(orderId);
  if (!order) return;

  // Events can arrive out of order: skip one older than the last handled.
  const arrivedLate = event.created_at < order.lastEventAt;
  if (arrivedLate) return;
  order.lastEventAt = event.created_at;
  order.status = status;
  order.tracking = null; // the next read gets the new captain details

  await notifyCustomer(order, orderId, event.data);

  if (status === "picked_up" || status === "delivered") {
    await saveProofPhotos(order);
    // A photo can arrive a little after the status: look once more a minute later.
    setTimeout(() => saveProofPhotos(order).catch(console.error), 60_000);
  }
}

async function saveProofPhotos(order) {
  const {orders_by_pk: labeenyOrder} = await labeeny(`
    query ($id: uuid!) {
      orders_by_pk(id: $id) {
        order_files(where: {type: {_in: ["pickup_proof", "delivery_proof"]}}) {
          type file_id
        }
      }
    }`, {id: order.labeenyOrderId});

  for (const file of labeenyOrder.order_files) {
    if (order.photos[file.type]) continue; // already saved
    order.photos[file.type] = await downloadOrderFile(file.file_id);
  }
}

async function downloadOrderFile(fileId) {
  const response = await fetch(`${STORAGE_URL}/files/${fileId}`, {
    headers: {"Authorization": `Bearer ${await labeenyToken()}`},
  });
  if (!response.ok) throw new Error(`Labeeny file ${fileId}: ${response.status}`);
  return {
    contentType: response.headers.get("content-type"), // e.g. "image/jpeg"
    bytes: Buffer.from(await response.arrayBuffer()),
  };
}

// Your app shows the photo from your backend: the Labeeny download needs your token.
// In production, save the bytes to your own storage instead of memory.
app.get("/api/orders/:orderId/photos/:type", (req, res) => {
  const photo = orders.get(req.params.orderId)?.photos[req.params.type];
  if (!photo) return res.sendStatus(404);
  res.type(photo.contentType).send(photo.bytes);
});

// What the customer reads for each status. Statuses with no message send no notification.
function customerMessage({status, previous_status: previousStatus, captain}) {
  switch (status) {
    case "pending_acceptance":
      // Back to pending: the captain dropped it. Just placed: no notification.
      return previousStatus ? "نبحث عن كابتن جديد لطلبك" : null;
    case "accepted_by_driver":
      return captain
        ? `الكابتن ${captain.name} قبل طلبك`
        : "وجدنا كابتن لطلبك";
    case "on_way":
      return "الكابتن في طريقه لاستلام طلبك";
    case "picked_up":
      return "استلم الكابتن طلبك";
    case "in_transit":
      return "طلبك في الطريق إليك";
    case "delivered":
      return "تم توصيل طلبك";
    case "cancelled":
      return "تم إلغاء طلبك";
    default:
      return null;
  }
}

async function notifyCustomer(order, orderId, eventData) {
  const body = customerMessage(eventData);
  if (!body || !order.deviceToken) return;

  try {
    await admin.messaging().send({
      token: order.deviceToken,
      notification: {title: `طلب ${orderId}`, body},
      // Your app opens the order from these. FCM data values are strings only.
      data: {orderId, status: eventData.status},
    });
  } catch (error) {
    const appRemoved = error.code === "messaging/registration-token-not-registered";
    if (!appRemoved) throw error;
    order.deviceToken = null;
  }
}

// Labeeny errors your app can act on; everything else is "try again later".
app.use((error, req, res, next) => {
  if (error instanceof LabeenyError && error.message === "estimate-not-found") {
    return res.status(409).json({error: "price_expired"}); // ask for a new price
  }
  console.error(error);
  res.status(502).json({error: "delivery_unavailable"});
});

app.listen(process.env.PORT ?? 3000);