Skip to main content
Routal

Nightly batch for B2B distribution

The default mode for B2B distributors. Orders close at 18:00, optimization runs overnight, the fleet rolls out at dawn. This recipe walks the full nightly job and its webhook cycle, from registering the webhook to writing stop.reported and route.finished back into the ERP, plus how to make it idempotent against a daily cron and recover when something misses the window.

Who this is for

You run a B2B distribution operation that serves the same network of customers (restaurants, supermarkets, bakeries, hospitals, industrial facilities, hotel chains) on a roughly fixed weekly rhythm. Your customers place orders the day before delivery, you close the order book at a fixed hour (typically 16:00–18:00), and your drivers leave the depot at dawn the next morning.

Routal sits between your order management system (an ERP, a WMS, a home-grown order portal) and your drivers. Every night the integration pushes the day's orders, runs the optimizer, and emails the resulting routes to each driver so they can open the app before they get in the van.

If that sounds like your operation, this is your recipe. If you take orders throughout the day and have to slot them into routes that have already left the depot, jump to Nightly batch + live dispatch.

What the rhythm looks like

Day -1                                  Day 0 (execution)
─────────────────────────────────────   ─────────────────────────────────────
08:00  Sales team takes orders          05:00  Drivers open the app
       throughout the day                      → routes flip to in_transit
                                               → plan flips to in_progress

17:50  Sales team finishes              08:00  First deliveries land
                                               ⚡ stop.reported writes each
18:00  ORDER BOOK CLOSES                         outcome + POD into the ERP

18:05  ⚡ Nightly batch fires            13:00  Mid-day check (any straggler?)
       1. Create tomorrow's plan
       2. Bulk-add the day's stops      18:00  Last delivery
       3. Start optimize/async                 ⚡ route.finished per route
          (returns at once)                    → plan flips to finished

18:07  ⚡ optimization.succeeded         22:00  ⚡ Reconciliation job
       4. Dispatch each route                  replays failed webhook
          (driver gets a magic-link            deliveries, checks every stop
          email)                               has a final state in the ERP

22:00  Operations supervisor reviews
       in planner.routal.com,
       tweaks if needed

The integration runs once per business day at the cutoff hour. If it fires twice (deploy, manual retry, scheduler hiccup) it must be a no-op the second time. If it never fires (cron host down, network blip) the supervisor must be able to run it manually from the dashboard or by hitting the same endpoint.

Nothing in this loop polls. The nightly job ends right after it starts the optimization; the optimization.succeeded webhook picks up from there.

What this recipe builds

A webhook registered once on deploy, a nightly job idempotent on (project_id, execution_date), and a worker that reacts to Routal's events:

  1. Registers the webhook (find-or-create on its URL, then a test call).
  2. Pulls today's order book from your source system.
  3. Ensures the plan exists for tomorrow's execution_date.
  4. Reconciles by external_id so stops already pushed aren't duplicated.
  5. Bulk-creates the missing stops with locations, time windows, and capacity.
  6. Starts the optimizer and returns.
  7. Dispatches each route when optimization.succeeded arrives (sends the magic-link email).
  8. Writes stop.reported and route.finished back into the ERP, and replays missed deliveries every night.

It's the canonical daily-orders flow specialized for the cutoff-at-18:00 cadence, with the cron, the rolling window, and the recovery logic that production crews actually need. The event-by-event view is in Webhooks → The full cycle.

Production code

runNightlyBatch is what your scheduler calls at the cutoff hour. It assumes your source system gives you the list of orders for a specific execution_date. The webhook receiver and handleRoutalEvent do the rest.

# The cURL form is useful for debugging individual steps. For the full nightly
# job and the webhook worker, see the TS or Python tabs.

# (0) Once, on deploy: register the webhook. Run
#     GET /v2/webhooks?project_id=YOUR_PROJECT_ID first and PUT /v2/webhook/{id}
#     instead when your url is already there, so redeploys don't add a second one.
curl -X POST "https://api.routal.com/v2/webhook?private_key=YOUR_KEY&project_id=YOUR_PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://erp.example.com/webhooks/routal?token=LONG_RANDOM_TOKEN",
    "enabled_events": [
      "routal.optimizer.2.optimization.succeeded",
      "routal.optimizer.2.optimization.failed",
      "routal.planner.2.stop.reported",
      "routal.drivers.2.route.finished"
    ],
    "enabled": true
  }'

#     Check the endpoint answers (2xx within 10 s) before relying on it.
curl -X POST "https://api.routal.com/v2/webhook/WEBHOOK_ID/test?private_key=YOUR_KEY" \
  -H 'Content-Type: application/json' \
  -d '{ "event_type": "routal.optimizer.2.optimization.succeeded" }'

# Run (1)-(3) at 18:05 against tomorrow's execution_date.
EXEC_DATE="2026-05-22"     # tomorrow, in the project's local time zone

# (1) Create tomorrow's plan (or fetch it if it already exists from a retry).
curl -X POST "https://api.routal.com/v2/plan?private_key=YOUR_KEY&project_id=YOUR_PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d "{ \"label\": \"${EXEC_DATE} nightly\", \"execution_date\": \"${EXEC_DATE}\" }"
# → { "id": "PLAN_ID", "status": "planning", "total_stops": 0, ... }

# (2) Bulk-add the day's orders. Each one carries the source order number as
#     external_id so a retry of step 2 is a no-op for stops already created.
curl -X POST "https://api.routal.com/v2/stops?private_key=YOUR_KEY&plan_id=PLAN_ID&project_id=YOUR_PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "external_id": "ORDER-9001",
      "label": "Acme Restaurant Centre",
      "location": { "lat": 41.20, "lng": 2.05, "address": "123 Industrial Park, Unit B" },
      "duration": 600,
      "time_windows": [[28800, 43200]],
      "weight": 32,
      "volume": 0.4,
      "phone": "+10000000001"
    },
    {
      "external_id": "ORDER-9002",
      "label": "Beta Bakery Supply",
      "location": { "lat": 41.25, "lng": 2.10 },
      "duration": 480,
      "time_windows": [[32400, 50400]],
      "weight": 12,
      "volume": 0.15
    }
  ]'

# (3) Optimize. Returns at once: the routes are ready when the
#     routal.optimizer.2.optimization.succeeded webhook arrives for PLAN_ID.
#     Not safe to retry blindly. See Production hardening.
curl -X POST "https://api.routal.com/v2/plan/PLAN_ID/optimize/async?private_key=YOUR_KEY"

# (4) On optimization.succeeded: read the routes, then dispatch each one that
#     has stops. The driver gets a magic-link email.
curl "https://api.routal.com/v2/plan/PLAN_ID/routes?private_key=YOUR_KEY"
curl -X POST "https://api.routal.com/v2/route/ROUTE_ID/dispatch?private_key=YOUR_KEY"

# (5) Nightly: list the execution day's failed deliveries and resend the ones
#     your ERP never processed. The resent payload keeps its original id.
curl "https://api.routal.com/v2/webhook/WEBHOOK_ID/events?private_key=YOUR_KEY&status=error&date=2026-05-22&limit=100"
curl -X POST "https://api.routal.com/v2/webhook/event/LOG_ENTRY_ID/resend?private_key=YOUR_KEY"
import createClient from 'openapi-fetch';
import express from 'express';
import type { paths } from './routal';

const routal = createClient<paths>({ baseUrl: 'https://api.routal.com' });
const ROUTAL_API_KEY = process.env.ROUTAL_API_KEY!;
const PROJECT_ID = process.env.ROUTAL_PROJECT_ID!;
const WEBHOOK_TOKEN = process.env.ROUTAL_WEBHOOK_TOKEN!; // long random string
const WEBHOOK_URL = `https://erp.example.com/webhooks/routal?token=${WEBHOOK_TOKEN}`;
const key = { private_key: ROUTAL_API_KEY };

const EVENTS = [
  'routal.optimizer.2.optimization.succeeded',
  'routal.optimizer.2.optimization.failed',
  'routal.planner.2.stop.reported',
  'routal.drivers.2.route.finished',
] as const;

// ── (0) Webhook setup: run on every deploy ───────────────────────────────

/** Find-or-update on url, so a redeploy never adds a second webhook. */
export async function ensureWebhook(): Promise<string> {
  const { data: hooks, error } = await routal.GET('/v2/webhooks', {
    params: { query: { ...key, project_id: PROJECT_ID } },
  });
  if (error) throw error;

  const body = { url: WEBHOOK_URL, enabled_events: [...EVENTS], enabled: true };
  const existing = (hooks ?? []).find((h) => h.url === WEBHOOK_URL);
  const { data: hook, error: saveErr } = existing
    ? await routal.PUT('/v2/webhook/{id}', { params: { path: { id: existing.id }, query: key }, body })
    : await routal.POST('/v2/webhook', { params: { query: { ...key, project_id: PROJECT_ID } }, body });
  if (saveErr) throw saveErr;

  // Fails unless the endpoint answers 2xx within 10 seconds.
  const { error: testErr } = await routal.POST('/v2/webhook/{id}/test', {
    params: { path: { id: hook!.id }, query: key },
    body: { event_type: 'routal.optimizer.2.optimization.succeeded' },
  });
  if (testErr) throw testErr;
  return hook!.id;
}

// ── (1-3) Nightly job: push, start the run, return ───────────────────────

type SourceOrder = {
  id: string;            // order number from your ERP/WMS
  customer: string;
  lat: number;
  lng: number;
  address?: string;
  serviceMinutes: number;
  windowFromSec: number;
  windowToSec: number;
  weightKg?: number;
  volumeM3?: number;
  phone?: string;
};

/**
 * Run the nightly batch for a given execution date.
 * Designed to be called from a scheduler at the order cutoff hour.
 * Idempotent on (PROJECT_ID, executionDate). Dispatch happens in the
 * webhook worker, when optimization.succeeded arrives.
 */
export async function runNightlyBatch(
  executionDate: string,                      // 'YYYY-MM-DD'
  orders: SourceOrder[],
  log = console,
): Promise<{ planId: string; stopsCreated: number }> {
  const label = `${executionDate} nightly`;
  const planId = await ensurePlan(executionDate, label);
  log.info('nightly_batch.plan_ready', { planId, executionDate, orderCount: orders.length });

  // Reconcile: only push stops whose external_id is not already on the plan.
  const alreadyThere = await findExistingExternalIds(planId, orders.map((o) => o.id));
  const newOrders = orders.filter((o) => !alreadyThere.has(o.id));
  if (newOrders.length > 0) {
    await bulkAddStops(planId, newOrders);
  }
  log.info('nightly_batch.stops_added', {
    planId,
    new: newOrders.length,
    skipped: orders.length - newOrders.length,
  });

  await startOptimization(planId);
  log.info('nightly_batch.optimization_started', { planId });

  return { planId, stopsCreated: newOrders.length };
}

async function ensurePlan(executionDate: string, label: string): Promise<string> {
  // Plans are listed in reverse chrono, so paginate just enough to find today's.
  // If your project produces many plans/day, narrow with a search by label.
  const { data, error } = await routal.GET('/v2/plans', {
    params: { query: { ...key, project_id: PROJECT_ID, limit: 50, sort: 'created_at:desc' } },
  });
  if (error) throw error;
  const existing = data!.docs?.find(
    (p) => p.label === label && p.execution_date?.startsWith(executionDate),
  );
  if (existing) return existing.id!;

  const { data: created, error: createErr } = await routal.POST('/v2/plan', {
    params: { query: { ...key, project_id: PROJECT_ID } },
    body: { label, execution_date: executionDate } as never,
  });
  if (createErr) throw createErr;
  return created!.id!;
}

async function findExistingExternalIds(planId: string, orderIds: string[]): Promise<Set<string>> {
  if (orderIds.length === 0) return new Set();
  const { data, error } = await routal.POST('/v2/stops/search', {
    params: { query: { ...key, project_id: PROJECT_ID } },
    body: {
      limit: 1000,
      predicates: [
        { field: 'plan_id', operator: 'eq', value: planId, type: 'string' },
        { field: 'external_id', operator: 'in', value: orderIds, type: 'string' },
      ],
    } as never,
  });
  if (error) throw error;
  return new Set((data!.docs ?? []).map((s) => s.external_id!).filter(Boolean));
}

async function bulkAddStops(planId: string, orders: SourceOrder[]): Promise<void> {
  const { error } = await routal.POST('/v2/stops', {
    params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
    body: orders.map((o) => ({
      external_id: o.id,
      label: o.customer,
      location: { lat: o.lat, lng: o.lng, address: o.address },
      duration: o.serviceMinutes * 60,
      time_windows: [[o.windowFromSec, o.windowToSec]],
      weight: o.weightKg,
      volume: o.volumeM3,
      phone: o.phone,
    })) as never,
  });
  if (error) throw error;
}

/** No polling: the optimization.succeeded webhook dispatches from here. */
async function startOptimization(planId: string): Promise<void> {
  // Insert-if-absent: false when this plan already waits on a run of yours
  // (a double-fire of the cron). That run's webhook does the rest.
  if (!(await pendingRuns.add(planId, new Date()))) return;

  const { error } = await routal.POST('/v2/plan/{id}/optimize/async', {
    params: { path: { id: planId }, query: key },
  });
  if (error) {
    await pendingRuns.remove(planId);
    // sync_optimization_already_progress: someone started a run from the
    // planner. Don't retry blindly (see Common errors).
    throw error;
  }
}

// ── (4) Webhook receiver ─────────────────────────────────────────────────

type RoutalEvent = { id?: string; event_id: string; project_id: string; created_at: string; data: any };

const app = express();
app.post('/webhooks/routal', express.json({ limit: '10mb' }), async (req, res) => {
  if (req.query.token !== WEBHOOK_TOKEN) return res.sendStatus(401); // not retried
  const event = req.body as RoutalEvent;
  if (!event.id) return res.sendStatus(200); // test event from /v2/webhook/{id}/test
  await jobs.enqueue('routal-event', event); // durable queue; a throw here → 500 → Routal retries
  res.sendStatus(200);                        // within 10 s, or it counts as a failure
});

/** Worker. Deliveries are at-least-once: the envelope id drops duplicates. */
export async function handleRoutalEvent(event: RoutalEvent) {
  if (await processed.has(event.id!)) return;

  switch (event.event_id) {
    case 'routal.optimizer.2.optimization.succeeded': {
      const planId: string = event.data.plan.id;
      // Runs started from the planner fire this too: only dispatch yours.
      if (await pendingRuns.remove(planId)) {
        await dispatchRoutes(planId);
        await reportUnassigned(planId);
      }
      break;
    }
    case 'routal.optimizer.2.optimization.failed':
      // The failed event carries no plan id today: page with every run still pending.
      await pageSupervisor('Routal optimization failed', { error: event.data.error, pending: await pendingRuns.list() });
      break;
    case 'routal.planner.2.stop.reported':
      await recordDelivery(event.data);
      break;
    case 'routal.drivers.2.route.finished':
      await reconcileRoute(event.data);
      break;
  }
  await processed.add(event.id!);
}

async function dispatchRoutes(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/routes', {
    params: { path: { id: planId }, query: key },
  });
  for (const route of (data as Array<{ id: string; stops?: unknown[] }>) ?? []) {
    if (!route.stops?.length) continue; // an empty route has nothing to dispatch
    if (await dispatched.has(route.id)) continue; // dispatch re-sends the driver email
    const { error } = await routal.POST('/v2/route/{id}/dispatch', {
      params: { path: { id: route.id }, query: key },
    });
    if (error) throw error;
    await dispatched.add(route.id);
  }
}

/** Stops the run could not place: the supervisor decides (see "no feasible window" below). */
async function reportUnassigned(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/stops', {
    params: { path: { id: planId }, query: key },
  });
  const unassigned = ((data as Array<{ external_id?: string; route_id?: string }>) ?? []).filter((s) => !s.route_id);
  if (unassigned.length) {
    await pageSupervisor('Stops without a route', { planId, orders: unassigned.map((s) => s.external_id) });
  }
}

const ERP_STATE = {
  service_report_completed: 'delivered',
  service_report_attempted: 'attempt_failed',
  service_report_canceled: 'canceled',
} as const;

async function recordDelivery(stop: any) {
  const report = stop.reports?.at(-1); // data is the stop; its latest report is the new one
  if (!report) return;
  await erp.upsertDelivery(stop.external_id, {
    state: ERP_STATE[report.type as keyof typeof ERP_STATE],
    signatureUrl: report.signature?.url,
    photoUrls: (report.images ?? []).map((i: { url: string }) => i.url),
    cancelReason: report.cancel_reason,
    comments: report.comments,
  });
}

/** The route's last word on each stop. Also catches a stop.reported that never got through. */
async function reconcileRoute(route: any) {
  for (const stop of route.stops ?? []) {
    await erp.upsertOrderStatus(stop.external_id, stop.status);
  }
}

// ── (5) Nightly: replay what the receiver missed ─────────────────────────

export async function replayFailedDeliveries(webhookId: string, date: string) {
  for (let offset = 0; ; offset += 100) {
    const { data, error } = await routal.GET('/v2/webhook/{id}/events', {
      params: { path: { id: webhookId }, query: { ...key, status: 'error', date, offset, limit: 100 } },
    });
    if (error) throw error;
    for (const entry of data!.events as Array<{ id: string; data?: any }>) {
      const payloadId = entry.data?.payload_sent?.id;
      if (payloadId && (await processed.has(payloadId))) continue; // a retry got through
      await routal.POST('/v2/webhook/event/{event_id}/resend', {
        params: { path: { event_id: entry.id }, query: key },
      });
    }
    if (!data!.hasNextPage) break;
  }
}
import os, requests
from flask import Flask, request

ROUTAL_API_KEY = os.environ["ROUTAL_API_KEY"]
PROJECT_ID = os.environ["ROUTAL_PROJECT_ID"]
WEBHOOK_TOKEN = os.environ["ROUTAL_WEBHOOK_TOKEN"]  # long random string
WEBHOOK_URL = f"https://erp.example.com/webhooks/routal?token={WEBHOOK_TOKEN}"
BASE = "https://api.routal.com"
KEY = {"private_key": ROUTAL_API_KEY}

EVENTS = [
    "routal.optimizer.2.optimization.succeeded",
    "routal.optimizer.2.optimization.failed",
    "routal.planner.2.stop.reported",
    "routal.drivers.2.route.finished",
]


# ── (0) Webhook setup: run on every deploy ───────────────────────────────

def ensure_webhook() -> str:
    """Find-or-update on url, so a redeploy never adds a second webhook."""
    hooks = requests.get(f"{BASE}/v2/webhooks", params={**KEY, "project_id": PROJECT_ID}, timeout=30)
    hooks.raise_for_status()
    body = {"url": WEBHOOK_URL, "enabled_events": EVENTS, "enabled": True}
    existing = next((h for h in hooks.json() if h["url"] == WEBHOOK_URL), None)
    if existing:
        resp = requests.put(f"{BASE}/v2/webhook/{existing['id']}", params=KEY, json=body, timeout=30)
    else:
        resp = requests.post(f"{BASE}/v2/webhook", params={**KEY, "project_id": PROJECT_ID}, json=body, timeout=30)
    resp.raise_for_status()
    hook_id = resp.json()["id"]

    # Fails unless the endpoint answers 2xx within 10 seconds.
    requests.post(
        f"{BASE}/v2/webhook/{hook_id}/test",
        params=KEY,
        json={"event_type": "routal.optimizer.2.optimization.succeeded"},
        timeout=30,
    ).raise_for_status()
    return hook_id


# ── (1-3) Nightly job: push, start the run, return ───────────────────────

def run_nightly_batch(execution_date: str, orders: list[dict]) -> dict:
    """
    Run the nightly batch for a given execution date.
    Designed to be called from a scheduler at the order cutoff hour.
    Idempotent on (PROJECT_ID, execution_date). Dispatch happens in the
    webhook worker, when optimization.succeeded arrives.
    """
    label = f"{execution_date} nightly"
    plan_id = ensure_plan(execution_date, label)

    already = find_existing_external_ids(plan_id, [o["id"] for o in orders])
    new_orders = [o for o in orders if o["id"] not in already]
    if new_orders:
        bulk_add_stops(plan_id, new_orders)

    start_optimization(plan_id)
    return {"plan_id": plan_id, "stops_created": len(new_orders)}


def ensure_plan(execution_date: str, label: str) -> str:
    resp = requests.get(
        f"{BASE}/v2/plans",
        params={**KEY, "project_id": PROJECT_ID, "limit": 50, "sort": "created_at:desc"},
        timeout=30,
    )
    resp.raise_for_status()
    for p in resp.json().get("docs", []):
        if p.get("label") == label and (p.get("execution_date") or "").startswith(execution_date):
            return p["id"]
    created = requests.post(
        f"{BASE}/v2/plan",
        params={**KEY, "project_id": PROJECT_ID},
        json={"label": label, "execution_date": execution_date},
        timeout=30,
    )
    created.raise_for_status()
    return created.json()["id"]


def find_existing_external_ids(plan_id: str, order_ids: list[str]) -> set[str]:
    if not order_ids:
        return set()
    resp = requests.post(
        f"{BASE}/v2/stops/search",
        params={**KEY, "project_id": PROJECT_ID},
        json={
            "limit": 1000,
            "predicates": [
                {"field": "plan_id", "operator": "eq", "value": plan_id, "type": "string"},
                {"field": "external_id", "operator": "in", "value": order_ids, "type": "string"},
            ],
        },
        timeout=30,
    )
    resp.raise_for_status()
    return {s["external_id"] for s in resp.json().get("docs", []) if s.get("external_id")}


def bulk_add_stops(plan_id: str, orders: list[dict]) -> None:
    payload = [
        {
            "external_id": o["id"],
            "label": o["customer"],
            "location": {"lat": o["lat"], "lng": o["lng"], "address": o.get("address")},
            "duration": o["service_minutes"] * 60,
            "time_windows": [[o["window_from_sec"], o["window_to_sec"]]],
            "weight": o.get("weight_kg"),
            "volume": o.get("volume_m3"),
            "phone": o.get("phone"),
        }
        for o in orders
    ]
    resp = requests.post(
        f"{BASE}/v2/stops",
        params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
        json=payload,
        timeout=60,
    )
    resp.raise_for_status()


def start_optimization(plan_id: str) -> None:
    """No polling: the optimization.succeeded webhook dispatches from here."""
    # Insert-if-absent: False when this plan already waits on a run of yours
    # (a double-fire of the cron). That run's webhook does the rest.
    if not pending_runs.add(plan_id):
        return
    resp = requests.post(f"{BASE}/v2/plan/{plan_id}/optimize/async", params=KEY, timeout=60)
    if not resp.ok:
        pending_runs.remove(plan_id)
        # sync_optimization_already_progress: someone started a run from the
        # planner. Don't retry blindly (see Common errors).
        resp.raise_for_status()


# ── (4) Webhook receiver ─────────────────────────────────────────────────

app = Flask(__name__)


@app.post("/webhooks/routal")
def routal_webhook():
    if request.args.get("token") != WEBHOOK_TOKEN:
        return "", 401  # not retried
    event = request.get_json()
    if not event.get("id"):
        return "", 200  # test event from /v2/webhook/{id}/test
    jobs.enqueue("routal-event", event)  # durable queue; an exception here → 500 → Routal retries
    return "", 200  # within 10 s, or it counts as a failure


ERP_STATE = {
    "service_report_completed": "delivered",
    "service_report_attempted": "attempt_failed",
    "service_report_canceled": "canceled",
}


def handle_routal_event(event: dict) -> None:
    """Worker. Deliveries are at-least-once: the envelope id drops duplicates."""
    if processed.has(event["id"]):
        return
    kind, data = event["event_id"], event["data"]

    if kind == "routal.optimizer.2.optimization.succeeded":
        plan_id = data["plan"]["id"]
        # Runs started from the planner fire this too: only dispatch yours.
        if pending_runs.remove(plan_id):
            dispatch_routes(plan_id)
            report_unassigned(plan_id)
    elif kind == "routal.optimizer.2.optimization.failed":
        # The failed event carries no plan id today: page with every run still pending.
        page_supervisor("Routal optimization failed", error=data.get("error"), pending=pending_runs.list())
    elif kind == "routal.planner.2.stop.reported":
        record_delivery(data)
    elif kind == "routal.drivers.2.route.finished":
        reconcile_route(data)

    processed.add(event["id"])


def dispatch_routes(plan_id: str) -> None:
    routes = requests.get(f"{BASE}/v2/plan/{plan_id}/routes", params=KEY, timeout=30).json()
    for route in routes:
        if not route.get("stops"):
            continue  # an empty route has nothing to dispatch
        if dispatched.has(route["id"]):
            continue  # dispatch re-sends the driver email
        requests.post(f"{BASE}/v2/route/{route['id']}/dispatch", params=KEY, timeout=30).raise_for_status()
        dispatched.add(route["id"])


def report_unassigned(plan_id: str) -> None:
    """Stops the run could not place: the supervisor decides (see "no feasible window" below)."""
    stops = requests.get(f"{BASE}/v2/plan/{plan_id}/stops", params=KEY, timeout=30).json()
    unassigned = [s.get("external_id") for s in stops if not s.get("route_id")]
    if unassigned:
        page_supervisor("Stops without a route", plan_id=plan_id, orders=unassigned)


def record_delivery(stop: dict) -> None:
    reports = stop.get("reports") or []
    if not reports:
        return
    report = reports[-1]  # data is the stop; its latest report is the new one
    erp.upsert_delivery(
        stop["external_id"],
        state=ERP_STATE[report["type"]],
        signature_url=(report.get("signature") or {}).get("url"),
        photo_urls=[i["url"] for i in report.get("images") or []],
        cancel_reason=report.get("cancel_reason"),
        comments=report.get("comments"),
    )


def reconcile_route(route: dict) -> None:
    """The route's last word on each stop. Also catches a stop.reported that never got through."""
    for stop in route.get("stops") or []:
        erp.upsert_order_status(stop["external_id"], stop["status"])


# ── (5) Nightly: replay what the receiver missed ─────────────────────────

def replay_failed_deliveries(webhook_id: str, date: str) -> None:
    offset = 0
    while True:
        resp = requests.get(
            f"{BASE}/v2/webhook/{webhook_id}/events",
            params={**KEY, "status": "error", "date": date, "offset": offset, "limit": 100},
            timeout=30,
        )
        resp.raise_for_status()
        page = resp.json()
        for entry in page["events"]:
            payload_id = ((entry.get("data") or {}).get("payload_sent") or {}).get("id")
            if payload_id and processed.has(payload_id):
                continue  # a retry got through
            requests.post(f"{BASE}/v2/webhook/event/{entry['id']}/resend", params=KEY, timeout=30).raise_for_status()
        if not page["hasNextPage"]:
            break
        offset += 100

pendingRuns, processed, dispatched, jobs, erp and pageSupervisor stand for your own storage, queue, ERP client and alerting. pendingRuns.add is an insert-if-absent that returns false when the plan is already there; processed and dispatched only need an insert and a lookup by id.

If the supervisor re-optimizes from the planner at 22:00, optimization.succeeded fires again, but the plan is no longer in pendingRuns, so the worker leaves it alone. Re-dispatch from the planner if the routes changed.

Production hardening

Scheduling: fire from a real scheduler, not from cron

Two reasons:

  • Idempotency on accidental double-fires. Cloud schedulers (Cloud Scheduler, EventBridge, GitHub Actions cron, Temporal, Airflow) call your endpoint instead of running locally. The endpoint is the natural place to add the "already ran today?" check.
  • Visibility. Cron in a single host fails silently if the host is down. A scheduler at least logs the missed window and lets you alert on it.

Trigger pattern:

18:05 every working day  →  HTTPS POST /internal/run-nightly-batch
                            with body { "execution_date": "<tomorrow ISO>" }

Your endpoint loads the orders for that date, calls runNightlyBatch, and returns the summary. Wrap the whole thing in a "if I already wrote to my own DB that the batch ran for this date, return early" guard. A second fire while the first run is still going is already a no-op: pendingRuns.add returns false and no second optimization starts. The guard covers a fire after the routes were dispatched, when a new run would rebuild routes the drivers already have.

Time zones: the cutoff is local, not UTC

If your scheduler runs in UTC and the operation is in a different time zone, "18:00 cutoff" depends on which 18:00 you mean. Two patterns that work:

  1. Schedule in local time. Most cloud schedulers accept a time zone. Use the depot's time zone so 18:00 always means "18:00 at the depot".
  2. Schedule in UTC and compute the local date inside the job. Useful if you operate across multiple time zones from a single job runner.
// pattern 2: compute tomorrow in the depot's TZ from UTC
const depotTz = 'America/Mexico_City';
const tomorrowLocal = new Date().toLocaleDateString('en-CA', { timeZone: depotTz });
// → '2026-05-22' regardless of what the runner host thinks the date is

Avoid using Date.now() and adding 24h: daylight saving will burn you twice a year.

Rolling window: keep 14 days of plans, archive the rest

Plans accumulate. After a year of daily plans you have ~250 plans per project and GET /v2/plans pagination becomes a real cost when the integration boots. Two operational patterns:

  • Don't list, search by execution date. POST /v2/stops/search is for stops, but the equivalent for plans is GET /v2/plans with the date already encoded in the label. Cache the plan id locally after creation; only call ensurePlan when the cache misses.
  • Soft-delete old plans. DELETE /v2/plan/{id} removes plans you no longer need to query (stops and routes cascade-soft-delete). Routal is a planning tool, not a system of record: your ERP should keep the authoritative copy of every order's outcome via webhooks.

Recover from a missed window

If 18:05 came and went without the batch firing (cron host down, deploy collision, network), the supervisor on call needs to be able to run it manually. Three options, cheapest first:

  1. Re-trigger the same endpoint. Idempotency on (project_id, execution_date) means a manual POST does the right thing.
  2. Run from a CLI. Ship a small script that calls the same runNightlyBatch function locally. Useful when the network from the runner host to your ERP is down but the supervisor's laptop is fine.
  3. Plan it in the dashboard. Worst case the supervisor opens planner.routal.com and creates the plan manually. Stops can be uploaded from a CSV. This is the always-available escape hatch.

Add a heartbeat: at 18:35 every working day, an alerting job checks that the day's plan exists with stops, that it is no longer in pendingRuns, and that at least one route was dispatched. If not, page the on-call supervisor. A plan still in pendingRuns means no optimization webhook arrived: a run canceled from the planner sends neither event.

Daily quota: stay under the rate limit

The nightly batch tends to spike right after the cutoff hour. A 2,000-stop import as 4 chunks of 500 + one optimize + N dispatches stays well under the 2,000 requests/minute cap. If you're operating multiple projects from the same credential, stagger them:

18:05  Project A: run batch
18:10  Project B: run batch
18:15  Project C: run batch

Don't have all projects fire at the exact same minute: that's the fastest way to get rate-limited at midnight.

What happens when a stop has no feasible window

When the constraints can't be satisfied, the optimizer can't place every stop. The most common cause in a B2B nightly batch is a time window narrower than the driving time from the depot. Either the run fails and optimization.failed arrives with the reason in data.error (the plan keeps the routes it had), or the run succeeds and some stops stay without a route: reportUnassigned above lists them.

Recovery path:

  1. Log the optimization request (stops + vehicles + their constraints).
  2. Email the supervisor with the plan id and a list of "stops with windows shorter than 60 min" or other diagnostic flags.
  3. The supervisor relaxes constraints in the dashboard, manually adds a vehicle, or moves the impossible stop to the next day.
  4. Re-run the optimizer (this time without the offending stop or with the relaxed window).

Don't auto-relax constraints in the integration. The integrator is not the one who decides whether "deliver to Acme Restaurant before 9am" can slip.

Observability: the metrics that matter

These counters cover 95% of the production support load:

MetricWhat it tells you
routal.nightly_batch.runs_total{outcome}Did the nightly job actually run? Alert on outcome=missing for >1h after the cutoff.
routal.nightly_batch.stops_createdVolume sanity check. Alert if today's count is <50% or >200% of the 7-day rolling average.
routal.nightly_batch.routes_dispatchedDid each route get its email? Should equal the count of routes with stops after optimization.succeeded.
routal.nightly_batch.errors_total{message_id}Cumulative highway.* codes hit. Investigate any new code.
routal.nightly_batch.webhook_replays_totalDeliveries the nightly job had to resend. Above zero most days = the receiver is dropping events.

Tag every log line with plan_id and execution_date so the supervisor can grep "what happened with tomorrow's plan" without a war room.

The reconciliation job: replay missed events

The nightly batch is push. The execution day is react: drivers open the app, stop.reported brings each outcome with its proof of delivery, and route.finished gives the final status of every stop on the route. The worker above writes both into the ERP as upserts, so the same stop arriving twice does no harm. See Webhooks.

Authenticate the webhook handler with a URL token, drop duplicates by the envelope id, and answer 2xx within 10 seconds. Timeouts and 5xx are retried 1, 5 and 30 minutes later; Routal disables the webhook after 50 lost events in a row. See Webhooks → Retries.

Retries cover short outages. For the rest, run replayFailedDeliveries every night for the execution day: it reads the failed attempts from GET /v2/webhook/{id}/events?status=error, skips the ones your processed table already has (a later retry got through) and resends the rest. A resent payload keeps its id, so running the job twice is harmless. See Webhooks → Delivery log.

Then check that every stop of the day's plan has a final state in the ERP. Anything left is an event that never arrived at all: read it with GET /v2/stop/{stop_id}. Cheap to build, expensive when missing.

Common errors

message_idCauseWhat to do
highway.optimization.error.sync_optimization_already_progressAnother optimization for the same plan is still running, usually one started from the planner.Do not retry. Wait for its optimization.succeeded or optimization.failed webhook. A double-fire of your own cron never gets here: pendingRuns.add stops it first.
highway.optimization.error.no_result_foundThe optimizer can't fit all stops to the available vehicles under the declared constraints.Page the supervisor with diagnostic data. Don't auto-relax.
highway.optimization.error.too_much_requestsThe optimizer backend itself was rate-limited. Separate from the public 429.Wait 60–90 seconds, re-fire once. If persistent, check statuspage.
highway.webhook.error.invalid_urlThe webhook url is not public: localhost, a private IP, an internal host, or credentials in the URL.Use a public HTTPS URL; a tunnel such as ngrok for local development.
highway.webhook.error.send_testPOST /v2/webhook/{id}/test got no 2xx from your endpoint within 10 seconds.Fix the endpoint before the first real event: check the token, the route and the response time.
highway.stop.error.custom_fields_invalidA stop sent custom fields that don't match the project definitions.Fetch the project's custom-field schema, fix the payload, usually a typo in a field name.
400 Bad Request (no message_id)Payload validation failure, most commonly a missing label or time_windows outside [0, 172800].Read message for the offending field, fix the source data.
429 Too Many RequestsToo many projects firing the nightly batch at the same minute.Stagger schedules; bulk-create in chunks of 500 instead of looping.

Next steps