Skip to main content
Routal

Reverse logistics for pickups and returns

Distributors and retailers that deliver and also pick up. Empty kegs from bars, empty pallets from supermarkets, returned items from customers, malfunctioning equipment from clients. This recipe models each return as a pickup at the customer paired with a delivery at the depot, covers pure return routes and mixed routes with outbound deliveries, the webhook cycle that closes each return on stop.reported and tells you on route.finished what is coming back to the depot, and the operational patterns that prevent drivers from showing up to "pick up" goods the customer never agreed to hand over.

Who this is for

You operate a fleet that picks things up, not just delivers them. Common shapes:

  • A beverage distributor dropping off full kegs / cases of bottled product to bars and restaurants, and picking up the empties at the same visit.
  • A palletized distributor to retail (supermarkets, hardware chains) whose drivers leave loaded pallets and bring back the empty ones for re-use.
  • A B2C e-commerce returns operation sending a van to pick up returned parcels from households after the customer initiated an RMA online.
  • A field service shop that swaps malfunctioning equipment: the technician drops off a working unit and recovers the broken one for repair / refurb.
  • A pure reverse-only specialist (e-waste collection, retail returns consolidator, recycling) where every stop is a pickup.

What makes you different from a forward-only delivery operation:

  • Two shapes on the same plan. An outbound order is a plain delivery stop: "give the customer this thing". A return is a pickup + delivery pair: "take this thing from the customer, then drop it at the depot". Routal has no standalone pickup stop; a pickup always belongs to a delivery.
  • Load grows during the day. A typical delivery van leaves loaded and empties out; a typical reverse-logistics van leaves empty and fills up. A mixed van does both, and the optimizer needs accurate capacity to plan a feasible day.
  • Pickup coordination is a customer-trust failure mode. A driver showing up to "pick up" a pallet the supermarket didn't agree to send back is an escalation. The integration must only push returns your source system confirmed.

What the rhythm looks like

Day -1 (afternoon)                           Day 0 (execution)
─────────────────────────────────            ─────────────────────────────────
14:00  Customer-service team confirms        06:00  Drivers open the app
       tomorrow's pickup requests with              → routes flip in_transit
       customers (call, portal,
       scheduled in ERP)                     08:00-17:00  Outbound deliveries +
                                                    return pickups by sequence
17:30  ERP runs the pickup-list export              → driver scans the RMA label
       → CSV / JSON for the integration             → POD attaches photos
                                                      of collected returns
17:35  ⚡ Nightly job fires
       1. Create tomorrow's plan                    → stop.reported closes
       2. Push outbound orders as                     each collection in the ERP
          plain delivery stops
       3. Push each return as a pair:        17:00  Back at the depot
          pickup at the customer,                   → driver completes each
          delivery at the depot                       return's drop: received
          (chain_id when it shares                  → route.finished: the ERP
           a visit with a delivery)                   checks what is still on
       4. Start optimize/async                        the van, reschedules the
                                                      ones not collected
                                                    → plan flips finished
17:37  ⚡ optimization.succeeded
          webhook                            22:00  Reconciliation job
       5. Dispatch routes                           replays failed webhook
       6. Send unplanned returns                    deliveries, verifies every
          back to customer service                  return has a final state
                                                    in the ERP

Two notes specific to reverse logistics:

  • A return is one pickup + delivery pair. Push it as one POST /v2/stops item: the outer fields are the delivery (the drop at the depot or returns warehouse), the nested pickup is the collection at the customer. The driver visits the pickup first, then the delivery. Pickups have to be enabled in the project's constraints.
  • Chain the outbound delivery and the return when they share a visit. If the bar at Calle Mayor 14 receives 3 kegs of full beer AND returns 5 empty kegs, the full kegs are a plain delivery stop and the empties are a pair whose pickup is at the bar. Give the keg delivery and the nested pickup the same chain_id (delivery chain_position: 0, pickup chain_position: 1) and the optimizer keeps them on the same vehicle in that order.
  • A return's weight and volume go on its delivery leg, as POSITIVE values. The optimizer applies them to both legs: the load comes on board at the pickup and leaves at the depot drop, counted against the vehicle's capacity (max_weight / max_volume on create, default_max_weight / default_max_volume when you read the vehicle).

The integration shape

On deploy (once)
POST /v2/webhook  (+ POST /v2/webhook/{id}/test)   find-or-create on url

Source systems
  ├─ ERP / RMA portal:  confirmed returns for tomorrow
  └─ ERP / OMS:         outbound deliveries for tomorrow (if mixed flow)
     │
     │  (1) map both into tomorrow's plan
     ▼
[ outbound: { external_id, location: CUSTOMER, weight, volume, chain_id? } ]
[ return:   { external_id, location: DEPOT, weight, volume,
              pickup: { external_id, location: CUSTOMER, tasks, chain_id? } } ]
     │
     │  (2) push all stops in one bulk call (a return pair is one item)
     ▼
POST /v2/stops                              (dedup on external_id before pushing)
     │
     │  (3) optimize: returns at once. Capacity tracks the running load:
     │      a return's load rides the van from its pickup to its depot drop.
     ▼
POST /v2/plan/{id}/optimize/async
     │
     │  (4) webhook: optimization.succeeded (data.plan.id)
     ▼
GET /v2/plan/{id}/routes → POST /v2/route/{id}/dispatch  (one call per route)
     │
     │  (5) webhooks during execution
     ▼
stop.reported  → type 'pickup': close the RMA collection in the ERP
                  + attach POD (signed receipt, photos) for chain-of-custody
                 type 'delivery' with pickup_id: the return reached the depot
route.finished → pair the legs by pickup_id: collected but not dropped =
                  still on the van; not collected = back to confirmation
     │
     │  (6) nightly
     ▼
GET /v2/webhook/{id}/events?status=error → resend what you missed

The key fields:

  • pickup: nested in a delivery stop, it turns the stop into a return pair. Reads return two stops, type: "pickup" and type: "delivery"; the delivery carries the pickup's id in pickup_id. Both legs carry the same external_id here (the RMA ticket id), so type is what tells them apart.
  • chain_id: a string ID shared by stops that must end up on the same vehicle. The outbound delivery and the return's nested pickup at the same customer share one chain_id.
  • chain_position: 0-indexed ordering within the chain. The outbound delivery is position 0 (driver arrives, hands off the new stuff), the return's pickup is position 1 (same vehicle, same visit, now collecting empties). The depot drop stays out of the chain: the pair already ties it to the same van, after its pickup.

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

Production code

# (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.planner.2.stop.reported" }'

# (1) Push a mixed batch for one BigMart visit. The loaded pallets are a plain
#     delivery. The empty-pallet return is ONE item: the outer delivery is the
#     drop at the depot, the nested pickup is the collection at BigMart. The
#     delivery and the nested pickup share a chain_id: same van, in that order.
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": "DEL-90100",
      "label": "BigMart, Calle Mayor 14, delivery",
      "location": { "lat": 40.4153, "lng": -3.7079, "address": "Calle Mayor 14, 28013 Madrid" },
      "duration": 900,
      "time_windows": [[28800, 43200]],
      "weight": 320,
      "volume": 2.4,
      "chain_id": "VISIT-BIGMART-MAYOR-14-2026-05-22",
      "chain_position": 0
    },
    {
      "external_id": "RMA-44521",
      "label": "BigMart empty pallets, drop at depot",
      "location": { "lat": 40.3476, "lng": -3.7006, "address": "Calle Laguna 12, 28021 Madrid" },
      "duration": 120,
      "time_windows": [[28800, 68400]],
      "weight": 180,
      "volume": 1.8,
      "pickup": {
        "external_id": "RMA-44521",
        "label": "BigMart, Calle Mayor 14, empty pallets pickup",
        "location": { "lat": 40.4153, "lng": -3.7079, "address": "Calle Mayor 14, 28013 Madrid" },
        "duration": 600,
        "time_windows": [[28800, 43200]],
        "chain_id": "VISIT-BIGMART-MAYOR-14-2026-05-22",
        "chain_position": 1
      }
    }
  ]'

# (2) Optimize. Returns at once: the routes are ready when the
#     routal.optimizer.2.optimization.succeeded webhook arrives for PLAN_ID.
#     The 180 kg of the return ride the van from BigMart to the depot. The
#     vehicle's capacity caps the running load at every point of the day.
curl -X POST "https://api.routal.com/v2/plan/PLAN_ID/optimize/async?private_key=YOUR_KEY"

# (3) On optimization.succeeded: read the routes, then dispatch each one that
#     has stops. Stops left without a route_id did not fit: call those customers.
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"

# (4) Nightly: list yesterday'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.planner.2.stop.reported' },
  });
  if (testErr) throw testErr;
  return hook!.id;
}

// ── (1) Push outbound deliveries + returns ───────────────────────────────

type Place = { lat: number; lng: number; address: string };

/** Where returns are dropped: your depot or returns warehouse. */
const DEPOT: Place = { lat: 40.3476, lng: -3.7006, address: 'Calle Laguna 12, 28021 Madrid' };
const DEPOT_HOURS: [number, number] = [28800, 68400]; // receiving hours, seconds from midnight
const UNLOAD_SEC = 120; // time to unload one return at the depot

type ReverseStop = {
  /** Sales order id (outbound) or RMA ticket id (return). */
  id: string;
  kind: 'delivery' | 'return';
  customer: string;
  lat: number;
  lng: number;
  address: string;
  weightKg: number;
  volumeM3: number;
  windowFromSec: number;
  windowToSec: number;
  durationSec: number;
  /** An outbound delivery and a return at the same customer visit share a chainId. */
  chainId?: string;
  /** Returns only: when the customer confirmed the pickup. Unset = not confirmed. */
  confirmed_at?: string;
};

type StopPayload = {
  external_id: string;
  label: string;
  location: Place;
  duration: number;
  time_windows: [number, number][];
  weight?: number;
  volume?: number;
  chain_id?: string;
  chain_position?: number;
  /** Makes this stop a return pair: the pickup is visited first, then this delivery. */
  pickup?: StopPayload;
};

/** Outbound orders become plain delivery stops; each return becomes a pickup + delivery pair. */
export async function pushDailyMixed(planId: string, stops: ReverseStop[]) {
  // Number each visit's chain: outbound deliveries first, then the returns' pickups.
  const chainPosition = new Map<string, number>();
  const byChain = new Map<string, ReverseStop[]>();
  for (const s of stops) {
    if (s.chainId) byChain.set(s.chainId, [...(byChain.get(s.chainId) ?? []), s]);
  }
  for (const group of byChain.values()) {
    group.sort((a, b) => Number(a.kind === 'return') - Number(b.kind === 'return'));
    group.forEach((s, idx) => chainPosition.set(s.id, idx));
  }

  const payload = stops.map((s) => toPayload(s, chainPosition.get(s.id)));
  for (let i = 0; i < payload.length; i += 250) {
    const chunk = payload.slice(i, i + 250);
    const { error } = await routal.POST('/v2/stops', {
      params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
      body: chunk as never,
    });
    if (error) throw error;
  }
}

function toPayload(s: ReverseStop, chainPosition?: number): StopPayload {
  // The visit at the customer: the whole stop for an outbound order, the nested pickup for a return.
  const atCustomer: StopPayload = {
    external_id: s.id,
    label: `${s.customer}, ${s.kind === 'return' ? 'return pickup' : 'delivery'}`,
    location: { lat: s.lat, lng: s.lng, address: s.address },
    duration: s.durationSec,
    time_windows: [[s.windowFromSec, s.windowToSec]],
    ...(s.chainId ? { chain_id: s.chainId, chain_position: chainPosition } : {}),
  };
  if (s.kind === 'delivery') return { ...atCustomer, weight: s.weightKg, volume: s.volumeM3 };

  return {
    // The delivery leg: the drop at the depot. Same external_id; reads tell the legs apart by `type`.
    external_id: s.id,
    label: `${s.customer}, return drop at depot`,
    location: DEPOT,
    duration: UNLOAD_SEC,
    time_windows: [DEPOT_HOURS],
    // The pair's load: the optimizer counts it on the van from the pickup to this drop.
    weight: s.weightKg,
    volume: s.volumeM3,
    pickup: atCustomer,
  };
}

type PlanStop = { id: string; type: 'pickup' | 'delivery'; pickup_id?: string; external_id?: string; route_id?: string };

async function listStops(planId: string) {
  const { data } = await routal.GET('/v2/plan/{id}/stops', {
    params: { path: { id: planId }, query: key },
  });
  return (data as PlanStop[]) ?? [];
}

// ── (2) Nightly job: start the run and return ────────────────────────────

/** No polling: the optimization.succeeded webhook picks up from here. */
export async function optimizeTomorrow(planId: string) {
  // Insert-if-absent: a cron that fires twice must not start, or forget, a second run.
  if (!(await pendingRuns.addIfAbsent(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);
    throw error; // e.g. sync_optimization_already_progress: wait, don't retry
  }
}

// ── (3) 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 flagUnplanned(planId);
      }
      break;
    }
    case 'routal.optimizer.2.optimization.failed':
      // The failed event carries no plan id today: alert with every run still pending.
      await alertOps('Routal optimization failed', { error: event.data.error, pending: await pendingRuns.list() });
      break;
    case 'routal.planner.2.stop.reported':
      await closeReturn(event.data);
      break;
    case 'routal.drivers.2.route.finished':
      await expectAtDepot(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);
  }
}

/** Orders the run could not place. A customer waiting with packed returns needs a call. */
async function flagUnplanned(planId: string) {
  // A return's depot leg (a delivery with pickup_id) is left out with its pickup: list each order once.
  const unplanned = (await listStops(planId)).filter((s) => !s.route_id && !s.pickup_id);
  if (unplanned.length) await erp.flagUnplanned(unplanned.map((s) => s.external_id!));
}

const RMA_STATE = {
  service_report_completed: 'collected',     // the goods are on the van
  service_report_attempted: 'pickup_failed', // the stop stays pending: the driver may try again
  service_report_canceled: 'pickup_canceled',
} as const;

/** stop.reported: data is the stop, and its latest report is the new one. */
async function closeReturn(stop: any) {
  if (stop.type === 'delivery' && !stop.pickup_id) return; // an outbound order: your delivery flow closes it
  const report = stop.reports?.at(-1);
  if (!report) return;

  if (stop.type === 'delivery') {
    // The return's drop at the depot (it carries pickup_id): the goods reached the warehouse.
    if (report.type === 'service_report_completed') await erp.markReceived(stop.external_id);
    return;
  }

  // type 'pickup': the collection at the customer. external_id is the RMA ticket id.
  const taskLabel = new Map((stop.tasks ?? []).map((t: { id: string; label: string }) => [t.id, t.label]));
  await erp.updateReturn(stop.external_id, {
    state: RMA_STATE[report.type as keyof typeof RMA_STATE],
    signatureUrl: report.signature?.url,
    photoUrls: (report.images ?? []).map((i: { url: string }) => i.url),
    // Report tasks carry task_id, status and comments but no label: join with the stop's tasks.
    taskResults: (report.tasks ?? []).map((t: { task_id: string; status: string; comments?: string }) => ({
      label: taskLabel.get(t.task_id),
      status: t.status,
      comments: t.comments,
    })),
    cancelReason: report.cancel_reason,
    comments: report.comments,
  });
}

/** route.finished: pair each return's two legs through the delivery's pickup_id. */
async function expectAtDepot(route: any) {
  const stops: any[] = route.stops ?? [];
  const byId = new Map(stops.map((s) => [s.id, s] as const));
  const onBoard: string[] = [];
  for (const drop of stops) {
    if (drop.type !== 'delivery' || !drop.pickup_id) continue; // outbound orders, and the pickups themselves
    const pickup = byId.get(drop.pickup_id);
    if (pickup?.status === 'completed') {
      if (drop.status !== 'completed') onBoard.push(drop.external_id); // collected, drop not reported
    } else if (pickup?.status !== 'canceled') {
      await erp.reschedulePickup(drop.external_id); // not collected: back to confirmation
    }
  }
  await erp.expectInbound(route.id, onBoard); // the depot checks the van against this list
}

// ── 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.planner.2.stop.reported"},
        timeout=30,
    ).raise_for_status()
    return hook_id


# ── (1) Push outbound deliveries + returns ───────────────────────────────

# Where returns are dropped: your depot or returns warehouse.
DEPOT = {"lat": 40.3476, "lng": -3.7006, "address": "Calle Laguna 12, 28021 Madrid"}
DEPOT_HOURS = [28800, 68400]  # receiving hours, seconds from midnight
UNLOAD_SEC = 120  # time to unload one return at the depot


def to_payload(s: dict, chain_position: int | None = None) -> dict:
    """s["kind"] is "delivery" (sales order) or "return" (RMA ticket); s["id"] is its id."""
    # The visit at the customer: the whole stop for an outbound order, the nested pickup for a return.
    at_customer = {
        "external_id": s["id"],
        "label": f"{s['customer']}, {'return pickup' if s['kind'] == 'return' else 'delivery'}",
        "location": {"lat": s["lat"], "lng": s["lng"], "address": s["address"]},
        "duration": s["duration_sec"],
        "time_windows": [[s["window_from_sec"], s["window_to_sec"]]],
    }
    if s.get("chain_id"):
        at_customer["chain_id"] = s["chain_id"]
        at_customer["chain_position"] = chain_position
    if s["kind"] == "delivery":
        return {**at_customer, "weight": s["weight_kg"], "volume": s["volume_m3"]}
    return {
        # The delivery leg: the drop at the depot. Same external_id; reads tell the legs apart by `type`.
        "external_id": s["id"],
        "label": f"{s['customer']}, return drop at depot",
        "location": DEPOT,
        "duration": UNLOAD_SEC,
        "time_windows": [DEPOT_HOURS],
        # The pair's load: the optimizer counts it on the van from the pickup to this drop.
        "weight": s["weight_kg"],
        "volume": s["volume_m3"],
        "pickup": at_customer,
    }


def push_daily_mixed(plan_id: str, stops: list[dict]) -> None:
    """Outbound orders become plain delivery stops; each return becomes a pickup + delivery pair."""
    # Number each visit's chain: outbound deliveries first, then the returns' pickups.
    by_chain: dict[str, list[dict]] = {}
    for s in stops:
        if s.get("chain_id"):
            by_chain.setdefault(s["chain_id"], []).append(s)
    chain_position: dict[str, int] = {}
    for group in by_chain.values():
        group.sort(key=lambda x: 1 if x["kind"] == "return" else 0)
        for idx, s in enumerate(group):
            chain_position[s["id"]] = idx

    payload = [to_payload(s, chain_position.get(s["id"])) for s in stops]
    for i in range(0, len(payload), 250):
        chunk = payload[i:i + 250]
        requests.post(
            f"{BASE}/v2/stops",
            params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
            json=chunk,
            timeout=60,
        ).raise_for_status()


def list_stops(plan_id: str) -> list[dict]:
    resp = requests.get(f"{BASE}/v2/plan/{plan_id}/stops", params=KEY, timeout=30)
    resp.raise_for_status()
    return resp.json()


# ── (2) Nightly job: start the run and return ────────────────────────────

def optimize_tomorrow(plan_id: str) -> None:
    """No polling: the optimization.succeeded webhook picks up from here."""
    # Insert-if-absent: a cron that fires twice must not start, or forget, a second run.
    if not pending_runs.add_if_absent(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)
        resp.raise_for_status()  # e.g. sync_optimization_already_progress: wait, don't retry


# ── (3) 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


RMA_STATE = {
    "service_report_completed": "collected",      # the goods are on the van
    "service_report_attempted": "pickup_failed",  # the stop stays pending: the driver may try again
    "service_report_canceled": "pickup_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)
            flag_unplanned(plan_id)
    elif kind == "routal.optimizer.2.optimization.failed":
        # The failed event carries no plan id today: alert with every run still pending.
        alert_ops("Routal optimization failed", error=data.get("error"), pending=pending_runs.list())
    elif kind == "routal.planner.2.stop.reported":
        close_return(data)
    elif kind == "routal.drivers.2.route.finished":
        expect_at_depot(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 flag_unplanned(plan_id: str) -> None:
    """Orders the run could not place. A customer waiting with packed returns needs a call."""
    # A return's depot leg (a delivery with pickup_id) is left out with its pickup: list each order once.
    unplanned = [s for s in list_stops(plan_id) if not s.get("route_id") and not s.get("pickup_id")]
    if unplanned:
        erp.flag_unplanned([s["external_id"] for s in unplanned])


def close_return(stop: dict) -> None:
    """stop.reported: data is the stop, and its latest report is the new one."""
    if stop["type"] == "delivery" and not stop.get("pickup_id"):
        return  # an outbound order: your delivery flow closes it
    reports = stop.get("reports") or []
    if not reports:
        return
    report = reports[-1]

    if stop["type"] == "delivery":
        # The return's drop at the depot (it carries pickup_id): the goods reached the warehouse.
        if report["type"] == "service_report_completed":
            erp.mark_received(stop["external_id"])
        return

    # type "pickup": the collection at the customer. external_id is the RMA ticket id.
    task_label = {t["id"]: t.get("label") for t in stop.get("tasks") or []}
    erp.update_return(
        stop["external_id"],
        state=RMA_STATE[report["type"]],
        signature_url=(report.get("signature") or {}).get("url"),
        photo_urls=[i["url"] for i in report.get("images") or []],
        # Report tasks carry task_id, status and comments but no label: join with the stop's tasks.
        task_results=[
            {"label": task_label.get(t["task_id"]), "status": t.get("status"), "comments": t.get("comments")}
            for t in report.get("tasks") or []
        ],
        cancel_reason=report.get("cancel_reason"),
        comments=report.get("comments"),
    )


def expect_at_depot(route: dict) -> None:
    """route.finished: pair each return's two legs through the delivery's pickup_id."""
    stops = route.get("stops") or []
    by_id = {s["id"]: s for s in stops}
    on_board = []
    for drop in stops:
        if drop["type"] != "delivery" or not drop.get("pickup_id"):
            continue  # outbound orders, and the pickups themselves
        pickup = by_id.get(drop["pickup_id"]) or {}
        if pickup.get("status") == "completed":
            if drop["status"] != "completed":
                on_board.append(drop["external_id"])  # collected, drop not reported
        elif pickup.get("status") != "canceled":
            erp.reschedule_pickup(drop["external_id"])  # not collected: back to confirmation
    erp.expect_inbound(route["id"], on_board)  # the depot checks the van against this list


# ── 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 and erp stand for your own storage, queue and ERP client. Both legs of a return carry the RMA ticket id as external_id, so the handlers pass it straight to the ERP; the stop's type and the delivery's pickup_id say which leg reported, with no lookup. processed and dispatched only need an insert and a lookup by id.

Production hardening

Never push a pickup the customer didn't confirm

The single biggest reverse-logistics escalation is a driver showing up to collect something the customer didn't agree to send back. Treat the pickup record as a two-phase commit:

  1. Phase 1, confirm in your source system (RMA portal acknowledgement, customer service callback, scheduled in the ERP with a confirmed-by user stamp). Set a confirmed_at timestamp on the pickup record.
  2. Phase 2, push to Routal only after confirmed_at is set.
function pickupsReadyForDispatch(allPickups: ReverseStop[]): ReverseStop[] {
  return allPickups.filter((p) => p.kind !== 'return' || p.confirmed_at);
}

Build a daily report in your ERP for unconfirmed pickups so customer service can chase them before tomorrow's push. The same rule applies to a pickup the van didn't collect: reschedulePickup sends it back to phase 1, not straight into tomorrow's plan.

Chain the outbound delivery and the return at the same visit

Use chain_id when a single customer visit has both an outbound delivery and a return. Without chaining, the optimizer is free to assign them to different vehicles that arrive minutes (or hours) apart: two drivers honking and a customer escalating.

The convention used in the code above:

  • chain_id = stable identifier for the visit (VISIT-<CUSTOMER>-<LOCATION>-<DATE>), set on the outbound delivery and on the return's nested pickup
  • chain_position: 0 = the outbound delivery (the driver hands stuff off first)
  • chain_position: 1 = the return's pickup (then collects the empties)

The return's depot drop takes no chain_id. A visit with only a return needs none either: the pair alone keeps the pickup and its drop on one van, in order.

Capacity that GROWS as the day progresses

A van leaves the depot empty (or partially loaded with delivery cargo) and fills up with empties / returns as the day goes on. The vehicle's capacity (max_weight / max_volume on POST /v3/vehicles, default_max_weight / default_max_volume when you read the vehicle) is the maximum simultaneous load. The pair model is what lets the optimizer track it: a return's load comes on board at its pickup and stays until its depot drop, while an outbound delivery's load leaves at its stop. The running load must never exceed the capacity.

The depot drop is a real stop on the route: the driver completes it when unloading, and that report is what tells your ERP the return arrived. Give it a short duration (the time to unload one return) and the depot's receiving hours as its time window. The project's proof-of-delivery settings apply to it like to any other stop.

When a pickup doesn't make it onto a route

The run ends with optimization.succeeded even when some stops didn't fit, so check for leftovers in the same handler that dispatches: flagUnplanned lists the plan's stops with no route_id, skipping the depot legs so each order shows once. For a return, that is a customer with the goods packed and waiting. Have customer service call them today and confirm a new date; don't let them find out when nobody shows up.

When the run itself fails, optimization.failed arrives instead and the plan keeps the routes it had. Don't dispatch: alert, fix the cause (often a vehicle without working hours or a stop without a valid location) and optimize again. Give every pending run a timeout too, say 30 minutes: a run canceled from the planner sends neither event.

Chain-of-custody: photos and signatures on the pickup

For returns / RMA / asset recovery, the POD on a pickup is the legal evidence that the customer handed the goods over. Signature and photos are not tasks: require them in the project's proof-of-delivery settings in the planner (new projects already require a signature and photos on completion), not on each stop. Tasks are the checks the driver ticks off, and they go inside the nested pickup:

{
  external_id: 'RMA-44521',
  // ... the drop at the depot
  pickup: {
    external_id: 'RMA-44521',
    // ... the collection at the customer
    tasks: [
      { label: 'Scan the RMA label', barcode: 'RMA-44521' },
      { label: 'Serial numbers match the RMA ticket' },
    ],
  },
}

stop.reported delivers the stop with all its reports; the newest one is the last. It carries the signature (signature.url), the photos (images[].url) and one result per task in tasks[], with its task_id, status and the driver's comments but no label: join it with the stop's tasks[] by id. Store them against the RMA record in your ERP: closeReturn above does it.

Closing returns from stop.reported

stop.reported fires once per report, for each leg. The stop's type says which one: pickup is the collection at the customer; delivery with a pickup_id is the return's drop at the depot; delivery without one is an outbound order. For the pickup, map the latest report.type into the RMA state machine:

Latest report.typeStop statusERP action
service_report_completedcompletedClose the pickup as collected: the goods are on the van. Attach signature, photos and task results.
service_report_attemptedpendingMark pickup failed, capture the cancel_reason (nobody, wrong_address, …). The driver may try again later in the day, so wait for the next report or route.finished before rescheduling.
service_report_canceledcanceledMark pickup canceled and notify customer service.

A service_report_completed on the depot drop marks the return received at the warehouse. The driver can't report the drop before its pickup.

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.

What comes back to the depot: route.finished

route.finished carries the route with its stops, pickups and deliveries alike, each with its final status. Pair each return's legs through the delivery's pickup_id and you have the van's manifest for the depot:

  • Pickup and drop completed: the return is at the warehouse; stop.reported already marked it received.
  • Pickup completed, drop not: the goods are still on the van. expectAtDepot hands the list to the ERP, so the warehouse checks the unload against it and opens the refurb, restock or scrap flow per RMA.
  • Pickup incomplete or still pending: not collected. Send it back to confirmation. A stop that was already attempted can't be moved (highway.stop.error.move_not_pending_stops): the next try is a new pair with a new external_id derived from the same RMA ticket, which your ERP resolves back to the ticket.

Missed events: replay from the delivery log

A deploy at the wrong minute, an ERP outage longer than the retry window, a bug in the handler: some deliveries end up lost. The nightly replayFailedDeliveries job above reads yesterday's 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.

Close the day with a check that every return of the plan has a final state in the ERP. Anything left is a webhook that never arrived: read it with GET /v2/stop/{stop_id}.

Observability: the metrics that matter

MetricWhat it tells you
reverse.pickups_pushed_total{day}Daily volume of confirmed pickups. Drift down = customer-service team falling behind on confirmations.
reverse.unconfirmed_pickups_totalPickups in the source system without confirmed_at. Trending up = ops backlog.
reverse.chained_stops_totalStops with chain_id. Should match the visits that combine an outbound delivery and a return.
reverse.van_peak_load_pctMax load during the day as a percentage of default_max_weight. >90% sustained = need bigger vans or smaller windows.
reverse.rma_close_lag_secondsTime from stop.reported to RMA closed in ERP. Spikes = webhook handler slow / broken.
reverse.pickups_not_collected_totalPickups still incomplete or pending in route.finished. Trending up = confirmation quality or route capacity problem.
reverse.webhook_replays_totalDeliveries the nightly job had to resend. Above zero most days = the receiver is dropping events.

Common errors

message_idCauseWhat to do
highway.optimization.error.no_result_foundCapacity exhausted considering running load (outbound still on board + returns picked up and not yet dropped at the depot).Reduce load by splitting heavy returns across two vans or two days; relax time windows.
highway.optimization.error.sync_optimization_already_progressAnother optimization is still running for the same plan.Wait for its optimization.succeeded or optimization.failed webhook. Do not retry.
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_invalidPickup-type custom fields (RMA reason, serial number) don't match project schema.Add the field definition in the dashboard, then re-push.
highway.stop.error.move_not_pending_stopsTried to move a pickup that was already attempted / failed.Push a new return pair with a new external_id derived from the same RMA ticket.
400 Bad Request on chain_positionTwo stops on the same chain_id have the same chain_position.Re-number positions starting from 0; each must be unique within a chain.
429 Too Many RequestsPush velocity too high.Chunk by 250 stops per bulk POST.

Next steps

  • Capacitated distribution: the full constraint matrix; reverse logistics shares all the weight / volume / skill mechanics, just with semantics flipped.
  • Package tracking: parcel-level status. packages go on the delivery side only: on a return pair, put them on the depot drop, never inside pickup.
  • Field service with appointments: when your pickups are equipment swaps (technician brings new unit + takes broken one), the field-service template is closer than this one.
  • Webhooks: the full cycle, event catalog, retries, delivery log and authentication patterns.
  • Idempotency: make the nightly push idempotent against cron retries; pickups confirmed twice in the ERP should never become two Routal stops.