Skip to main content
Routal

Field service with appointments

For mobile workforces of technicians, installers, home health and equipment maintenance. The unit of work is a service appointment, not a delivery. This recipe covers skill matching, tight appointment windows, multi-task checklists, and the webhook cycle that dispatches technicians on optimization.succeeded and mirrors what they did on site into the customer's ticket on stop.reported.

Who this is for

You run a mobile workforce (technicians, installers, home-care workers, equipment maintenance crews) and your unit of work is a scheduled appointment, not a delivery. Common shapes:

  • Telecom installers connecting new fibre subscribers.
  • HVAC, plumbing, or electrical repair calls.
  • Home health visits to elderly or post-surgery patients.
  • Field maintenance of utility meters, ATMs, vending machines, sanitation equipment.
  • White-glove furniture or appliance installation.

What makes you different from a B2B delivery operation:

  • The time window is a customer appointment ("between 10am and noon"), not a delivery slot. A driver running 30 minutes late on the previous stop affects the next customer's morning, not just their porch.
  • The work itself takes a meaningful amount of time (15 minutes to 3 hours), so on-site duration is the dominant factor in routing.
  • Your technicians have specializations. An A/C specialist can't fix a boiler. A nurse with paediatric certification can't do adult home health visits in some jurisdictions.
  • The proof of work is structured: signed work order, photos of the installation, scanned barcodes of parts used, an explicit checklist of what was done.

If that sounds like your operation, this recipe walks through the four moving parts that distinguish field service from delivery: skill matching, appointment windows, multi-task checklists, and ticket-to-stop mapping.

What the rhythm looks like

Day -2 to -1                            Day 0 (execution)
─────────────────────────────────────   ─────────────────────────────────────
Customer books an appointment            08:00  Technicians open the app
through your scheduling tool                    → routes flip to in_transit
  → window confirmed
                                         09:30  Tech arrives at first appointment
                                                → opens the stop in the app
                                                → ticks tasks one by one
                                                → captures signature + photo
Day -1 evening                                  → submits the report
17:00  Scheduling tool closes books             → stop.reported updates the ticket
       for tomorrow's appointments
                                         11:00  Next appointment
17:30  ⚡ Daily plan job
       1. Create tomorrow's plan         13:00  Lunch break (vehicle break window)
       2. Bulk-add appointments
          with requires, time_windows,   14:30  Afternoon appointments
          duration, tasks
       3. Start optimize/async           18:00  Last appointment
                                                → route.finished
17:32  ⚡ optimization.succeeded                → incomplete visits flagged
       4. Dispatch each technician                for rescheduling
       5. Page the supervisor with
          appointments left unassigned   22:00  Reconciliation job
                                                replays failed webhook
21:00  Supervisor reviews,                      deliveries, checks every
       adjusts manually if needed               ticket has a final state

The daily plan job is essentially the nightly batch B2B pattern. The differences are in the stop payload (the skills, the narrow window, the tasks) and in the webhook handling (the report carries structured task results that have to flow back into the customer's ticket).

Nothing in this loop polls. The plan job ends right after it starts the optimization; the optimization.succeeded webhook dispatches the technicians, and stop.reported updates each ticket as the visits close.

The four moving parts

1. Skill matching: requires on stops, provides on vehicles

Each technician (modelled as a Vehicle) declares provides, a list of strings representing what they can do (sent to POST /v3/vehicles; it reads back as default_provides). Each appointment (modelled as a Stop) declares requires, a list of strings the assigned route must cover.

The optimizer will not assign a stop to a route that doesn't cover its requires. There is no partial match and no warning: it's hard exclusion.

// vehicle (technician's van)
{
  "external_id": "TECH-Maria-AC",
  "label": "María (A/C senior)",
  "provides": ["ac-install", "ac-repair", "ac-maintenance", "language-en"]
}

// stop (appointment)
{
  "external_id": "TICKET-44521",
  "label": "Customer A (A/C install)",
  "requires": ["ac-install", "language-en"]
}

Convention tips:

  • Use stable string identifiers, not human labels. ac-install not "AC installation (residential)". The optimizer treats them as opaque strings.
  • Be precise: ac-install-residential vs ac-install-commercial may matter for routing and definitely matters for SLA and pricing.
  • Stable enums map to your source system: technician certifications and ticket types live there; Routal just reflects them.

2. Appointment windows: narrow time_windows, not delivery slots

A B2B delivery to a restaurant has a window like "between 08:00 and 13:00". A telecom installation has a window like "10:00 to 12:00". Narrower means:

  • The optimizer has less slack, and the same number of appointments needs more technicians.
  • Buffer matters more. A 90-minute appointment scheduled in a 120-minute window leaves 30 minutes for transit + slip. Less than that and a single delay cascades to every later stop.
  • time_windows[] is an array, so you can offer the customer two windows ("morning OR afternoon"), and the optimizer picks the best one.
{
  "external_id": "TICKET-44521",
  "label": "Boiler install for Mr. Pérez",
  "time_windows": [
    [36000, 39600]   // 10:00–11:00 (single offered slot)
  ],
  "duration": 5400   // 90 minutes of on-site work
}

3. Multi-task checklists: POST /v2/task

Once a stop exists, attach tasks: labelled checklist items the technician ticks one by one in the app:

Task patternWhy
"Diagnose problem" + comments carrying the customer's symptomsFirst thing the tech does on arrival.
"Replace part X" + barcode of the SKUTech scans the part as proof it was installed.
"Test pressure / continuity / signal"Functional verification step.
"Review work order" + comments carrying the form templateWalks the customer through the job before they sign.

Tasks are different from a report: a report is the free-form POD (signature image, photos, notes) the tech submits at the end of the visit, and it triggers the routal.planner.2.stop.reported webhook. Tasks are the structured checklist tracked separately and persisted on the stop. Signature and photos are never tasks: you require them in the project's proof-of-delivery settings in the planner.

4. Ticket-to-stop mapping: external_id carries your ticket number

Your source system owns the ticket (job number, work order, customer call reference). Routal owns the stop. The bridge is external_id:

  • Stops get external_id: "TICKET-44521".
  • Vehicles get external_id: "TECH-Maria-AC".
  • Tasks reference your SKU via barcode, and your form fields via custom_fields.

When the stop reports (technician completes / attempts / cancels), the stop.reported webhook's data is the stop itself, so data.external_id is your ticket number. No extra read is needed to join back to the ticket.

Production code

The code below runs the whole cycle for one plan: register the webhook, create appointments with their checklist, start the optimization, dispatch when optimization.succeeded arrives, write each report back into the ticket, and replay missed deliveries at night. For a bulk daily push of many appointments, reuse the chunking and dedup of nightly batch B2B with the field-service stop shape from this page.

# (0) Once, on deploy: register the webhook. Run
#     GET /v2/webhooks?project_id=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=PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '{
    "url": "https://crm.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) Create the appointment on tomorrow's plan. requires + time_windows are
#     the field-service-specific bits.
curl -X POST "https://api.routal.com/v2/stops?private_key=YOUR_KEY&plan_id=PLAN_ID&project_id=PROJECT_ID" \
  -H 'Content-Type: application/json' \
  -d '[
    {
      "external_id": "TICKET-44521",
      "label": "Mr. Pérez (boiler repair)",
      "location": { "lat": 41.20, "lng": 2.05, "address": "Customer address line" },
      "duration": 5400,
      "time_windows": [[36000, 39600]],
      "requires": ["plumbing", "boiler-emergency"],
      "phone": "+10000044521",
      "custom_fields": {
        "ticket_id": "44521",
        "customer_segment": "premium"
      }
    }
  ]'
# → returns the created stop. Save the stop_id.

# (2) Attach checklist tasks. One POST per task.
curl -X POST "https://api.routal.com/v2/task?private_key=YOUR_KEY&stop_id=STOP_ID" \
  -H 'Content-Type: application/json' \
  -d '{
    "label": "Diagnose problem",
    "comments": "Customer reports no hot water since this morning."
  }'

curl -X POST "https://api.routal.com/v2/task?private_key=YOUR_KEY&stop_id=STOP_ID" \
  -H 'Content-Type: application/json' \
  -d '{
    "label": "Replace ignition module",
    "barcode": "PART-IGN-7715",
    "comments": "Part to be scanned from the technician van."
  }'

curl -X POST "https://api.routal.com/v2/task?private_key=YOUR_KEY&stop_id=STOP_ID" \
  -H 'Content-Type: application/json' \
  -d '{
    "label": "Verify pressure",
    "comments": "Hold for 60s at 1.5 bar."
  }'

# (3) Optimize. Returns at once: the routes are ready when the
#     routal.optimizer.2.optimization.succeeded webhook arrives for PLAN_ID.
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 technician 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 yesterday's failed deliveries and resend the ones your
#     CRM 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://crm.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-2) Appointments with their checklist ──────────────────────────────

type Appointment = {
  ticketId: string;
  customerLabel: string;
  lat: number;
  lng: number;
  address?: string;
  phone?: string;
  windowFromSec: number;
  windowToSec: number;
  serviceMinutes: number;
  requiredSkills: string[];        // e.g. ['plumbing', 'boiler-emergency']
  customFields?: Record<string, string>;
  checklist: Array<{
    label: string;
    comments?: string;
    barcode?: string;
  }>;
};

/**
 * Create an appointment as a stop with its task checklist attached.
 * Returns the stop_id; the webhooks carry external_id (= ticket id) back.
 */
export async function createAppointment(
  planId: string,
  appt: Appointment,
): Promise<string> {
  // (1) Create the stop.
  const { data, error } = await routal.POST('/v2/stops', {
    params: { query: { ...key, plan_id: planId, project_id: PROJECT_ID } },
    body: [
      {
        external_id: appt.ticketId,
        label: appt.customerLabel,
        location: { lat: appt.lat, lng: appt.lng, address: appt.address },
        duration: appt.serviceMinutes * 60,
        time_windows: [[appt.windowFromSec, appt.windowToSec]],
        requires: appt.requiredSkills,
        phone: appt.phone,
        custom_fields: appt.customFields,
      },
    ] as never,
  });
  if (error) throw error;
  const stopId = (data as { id: string }[])[0].id;

  // (2) Attach the checklist. One call per task; the app shows them in this order.
  for (const item of appt.checklist) {
    const { error: taskErr } = await routal.POST('/v2/task', {
      params: { query: { ...key, stop_id: stopId } },
      body: {
        label: item.label,
        comments: item.comments,
        barcode: item.barcode,
      } as never,
    });
    if (taskErr) throw taskErr;
  }

  return stopId;
}

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

// ── (3) Plan 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
  }
}

// ── (4-5) 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;
      // A supervisor re-optimizing from the planner fires this too: only act on your runs.
      if (await pendingRuns.remove(planId)) {
        await dispatchRoutes(planId);
        await pageUnassigned(planId);
      }
      break;
    }
    case 'routal.optimizer.2.optimization.failed':
      // The failed event carries no plan id today: alert with every run still pending.
      await alertSupervisor('Routal optimization failed', { error: event.data.error, pending: await pendingRuns.list() });
      break;
    case 'routal.planner.2.stop.reported':
      await updateTicket(event.data);
      break;
    case 'routal.drivers.2.route.finished':
      await flagIncomplete(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; // a technician with no appointments tomorrow
    if (await dispatched.has(route.id)) continue; // dispatch re-sends the technician 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);
  }
}

/** Appointments no technician could take: skills or windows don't fit. */
async function pageUnassigned(planId: string) {
  const unassigned = (await listStops(planId)).filter((s) => !s.route_id);
  if (unassigned.length) {
    await alertSupervisor('Appointments without a technician', {
      tickets: unassigned.map((s) => ({ ticket: s.external_id, requires: s.requires })),
    });
  }
}

const TICKET_STATE = {
  service_report_completed: 'resolved',
  service_report_attempted: 'attempted',  // stop stays pending: the tech may come back
  service_report_canceled: 'canceled',
} as const;

async function updateTicket(stop: any) {
  const report = stop.reports?.at(-1); // data is the stop; its latest report is the new one
  if (!report) return;
  // report.tasks carries task_id + status; the stop's tasks carry the label and barcode.
  const checklist = new Map((stop.tasks ?? []).map((t: any) => [t.id, t]));
  await crm.updateTicket(stop.external_id, {
    state: TICKET_STATE[report.type as keyof typeof TICKET_STATE],
    lines: (report.tasks ?? []).map((t: any) => ({
      label: (checklist.get(t.task_id) as any)?.label,
      status: t.status,               // completed | canceled | pending
      comments: t.comments,
    })),
    signatureUrl: report.signature?.url,  // copy to your storage, don't hot-link
    photoUrls: (report.images ?? []).map((i: { url: string }) => i.url),
    notes: report.comments,
    cancelReason: report.cancel_reason,
  });
}

/** The route ended: appointments it didn't close need a new date. */
async function flagIncomplete(route: any) {
  for (const stop of route.stops ?? []) {
    if (stop.status === 'incomplete') await crm.flagReschedule(stop.external_id);
  }
}

// ── 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://crm.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-2) Appointments with their checklist ──────────────────────────────

def create_appointment(plan_id: str, appt: dict) -> str:
    """
    Create an appointment as a stop with its task checklist attached.
    Returns the stop_id; the webhooks carry external_id (= ticket id) back.
    """
    payload = [{
        "external_id": appt["ticket_id"],
        "label": appt["customer_label"],
        "location": {
            "lat": appt["lat"],
            "lng": appt["lng"],
            "address": appt.get("address"),
        },
        "duration": appt["service_minutes"] * 60,
        "time_windows": [[appt["window_from_sec"], appt["window_to_sec"]]],
        "requires": appt["required_skills"],
        "phone": appt.get("phone"),
        "custom_fields": appt.get("custom_fields"),
    }]
    resp = requests.post(
        f"{BASE}/v2/stops",
        params={**KEY, "plan_id": plan_id, "project_id": PROJECT_ID},
        json=payload,
        timeout=30,
    )
    resp.raise_for_status()
    stop_id = resp.json()[0]["id"]

    # One call per task; the app shows them in this order.
    for item in appt["checklist"]:
        requests.post(
            f"{BASE}/v2/task",
            params={**KEY, "stop_id": stop_id},
            json={
                "label": item["label"],
                "comments": item.get("comments"),
                "barcode": item.get("barcode"),
            },
            timeout=30,
        ).raise_for_status()

    return stop_id


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


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


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


TICKET_STATE = {
    "service_report_completed": "resolved",
    "service_report_attempted": "attempted",  # stop stays pending: the tech may come back
    "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"]
        # A supervisor re-optimizing from the planner fires this too: only act on your runs.
        if pending_runs.remove(plan_id):
            dispatch_routes(plan_id)
            page_unassigned(plan_id)
    elif kind == "routal.optimizer.2.optimization.failed":
        # The failed event carries no plan id today: alert with every run still pending.
        alert_supervisor("Routal optimization failed", error=data.get("error"), pending=pending_runs.list())
    elif kind == "routal.planner.2.stop.reported":
        update_ticket(data)
    elif kind == "routal.drivers.2.route.finished":
        for stop in data.get("stops") or []:
            if stop.get("status") == "incomplete":
                crm.flag_reschedule(stop["external_id"])  # the route ended without closing it

    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  # a technician with no appointments tomorrow
        if dispatched.has(route["id"]):
            continue  # dispatch re-sends the technician email
        requests.post(f"{BASE}/v2/route/{route['id']}/dispatch", params=KEY, timeout=30).raise_for_status()
        dispatched.add(route["id"])


def page_unassigned(plan_id: str) -> None:
    """Appointments no technician could take: skills or windows don't fit."""
    unassigned = [s for s in list_stops(plan_id) if not s.get("route_id")]
    if unassigned:
        alert_supervisor(
            "Appointments without a technician",
            tickets=[{"ticket": s.get("external_id"), "requires": s.get("requires")} for s in unassigned],
        )


def update_ticket(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
    # report["tasks"] carries task_id + status; the stop's tasks carry the label and barcode.
    checklist = {t["id"]: t for t in stop.get("tasks") or []}
    crm.update_ticket(
        stop["external_id"],
        state=TICKET_STATE[report["type"]],
        lines=[
            {
                "label": checklist.get(t["task_id"], {}).get("label"),
                "status": t["status"],  # completed | canceled | pending
                "comments": t.get("comments"),
            }
            for t in report.get("tasks") or []
        ],
        signature_url=(report.get("signature") or {}).get("url"),  # copy to your storage
        photo_urls=[i["url"] for i in report.get("images") or []],
        notes=report.get("comments"),
        cancel_reason=report.get("cancel_reason"),
    )


# ── 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, crm and alertSupervisor stand for your own storage, queue, CRM client and paging. processed and dispatched only need an insert and a lookup by id.

Production hardening

Defining the skill catalog

Skill strings have to be stable and shared between your source system and Routal. The two patterns that work:

  1. Define the catalog in your source system. Your dispatch software / ticketing tool already knows what certifications a technician has and what ticket types exist. Mirror those strings into Routal at vehicle creation time (provides) and stop creation time (requires).
  2. Document a fixed enumeration in a shared registry. A markdown file or a tiny config service that lists every legal skill string. Both teams read from it.

Mixing the two, letting individual technicians declare custom skills in the field, produces a graveyard of typos (acrepair, ac-repair, AC repair) and routes that look fine until the day the optimizer matches them to a stop that misspells the same word.

Custom fields: define them in the dashboard first

Custom fields must be declared in the project settings (planner.routal.com) before you can use them on stops, routes, or vehicles. The dashboard accepts strings, numbers, booleans, dates, and dropdowns. Once defined, reference them by name from the API:

{
  "external_id": "TICKET-44521",
  "custom_fields": {
    "ticket_id": "44521",
    "ticket_priority": "P2",        // dropdown
    "customer_id": "CUST-991",
    "follow_up_required": true      // boolean
  }
}

If you POST a custom field that isn't defined in the project, you get highway.stop.error.custom_fields_invalid and the whole stop fails. Set up the schema once, version it like code in your source repo, and let the integration mirror it.

Tasks vs. report: pick the right tool

Tasks (this recipe) are structured checklist items the technician ticks in the app:

  • Each task has a status (pending / completed / canceled).
  • Tasks persist with the stop.
  • Best for SKU scanning, multi-step procedures, and items where you need a per-line outcome ("part X was installed", "calibration passed").

Reports (delivered via the stop.reported webhook) are the free-form POD at the end of the visit:

  • Carries images, signature, free-text comments, cancel_reason.
  • One per stop completion, attempt, or cancellation.
  • Fires the routal.planner.2.stop.reported webhook.

A typical field service stop produces both: the technician ticks tasks during the visit, then submits a report at the end (with the customer's signature, photos of the completed work, optional notes).

When designing the data flow:

  • Your ticket status in the source system should come from the latest report's type (service_report_completed / service_report_attempted / service_report_canceled).
  • Your per-line outcomes (parts installed, tests passed) should come from the task statuses in that same report.
  • Your photos and signature should be downloaded from the report's images[].url and signature.url to your own storage during webhook processing.

Sequence within an appointment

The driver app shows the task list in the order they were created. If sequence matters ("scan in before you scan out"), create tasks in that order. There is no position field on tasks today: re-ordering after creation requires deleting and recreating.

The "no available technician" scenario

The optimizer can't place an appointment when:

  • The skills it requires aren't provided by any technician scheduled for the day.
  • The total appointment minutes plus driving time exceed the technicians' combined working windows.

The run still ends with optimization.succeeded, and those appointments come back without a route_id. pageUnassigned above lists them with their requires, in the same handler that dispatches. When the run fails outright, optimization.failed arrives instead and the plan keeps the routes it had: don't dispatch, alert, fix the cause and optimize again. Give every pending run a timeout too, say 30 minutes: a run canceled from the planner sends neither event.

For field service this is more common than for delivery: narrow windows and required skills shrink the feasible set sharply. Recovery patterns:

  1. Suggest an alternate day to the customer. Move the ticket's preferred date by one day in your source system.
  2. Add an on-call technician for that day. The page to the supervisor carries the unfittable appointments and the skills they need.
  3. Relax the skill requirement (with the dispatcher's explicit consent, never automatically). A general-purpose technician can sometimes cover a specialist appointment in a pinch.

Webhook handling: task statuses arrive in the latest report

When the technician submits at the end of the visit, the routal.planner.2.stop.reported webhook fires. Its data is the stop, with every report it has received in data.reports. The newest is the last one, data.reports.at(-1), and it carries:

  • tasks[]: one entry per task, with its task_id, final status (completed / canceled / pending) and optional comments filled in by the technician.
  • signature.url / images[].url: the proof-of-work assets.
  • type: overall outcome (service_report_completed / service_report_attempted / service_report_canceled).
  • comments and, on a cancellation, cancel_reason.

The checklist itself (label, barcode) lives on the stop's data.tasks[]. The integration joins the report's tasks[] to it by task_id and writes each line back to your ticket. Skipping a task (status remains pending after the report) usually means the technician deemed it unnecessary or impossible; your ticket logic decides whether that's acceptable.

service_report_attempted leaves the stop pending: the technician may come back later in the day. An appointment the route ended without closing arrives as incomplete in route.finished, which is when flagIncomplete asks for a new date.

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.

Missed events: replay from the delivery log

A deploy at the wrong minute, a CRM 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. See Webhooks → Delivery log.

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

Reschedule, don't recreate

When a customer asks to reschedule:

  • Stop is still pending and has no report → use POST /v2/stop/move to move it to the new day's plan. The external_id (your ticket number) stays the same; everything else carries over.
  • Stop already has a report, or ended incomplete / canceled → create a new stop with a new external_id derived from the same ticket (TICKET-44521-RESCHED-1). Moving a visited stop rewrites its history and breaks the technician's performance metrics for the original day.

Observability: the metrics that matter

MetricWhat it tells you
field_service.appointments_created_total{required_skill}Demand by skill. Spot which certifications you need to hire more of.
field_service.unmatched_appointments_totalrequires strings that no technician provides: typically a typo, or a new ticket type that hasn't been mirrored.
field_service.no_result_found_rateDays where the optimizer couldn't fit every appointment. Spike means understaffing or windows too narrow.
field_service.task_skip_rate{task_label}Tasks the technician marks canceled rather than completed. Investigate the top one; usually a process problem.
field_service.stop_report_latency_minMinutes between appointment end and report submission. A long tail means technicians are submitting in batches; encourage app submission on site.
field_service.webhook_replays_totalDeliveries the nightly job had to resend. Above zero most days = the receiver is dropping events.

Tag every appointment with the source-system ticket id; the dispatcher always needs to grep "where did ticket 44521 end up?".

Common errors

message_idCauseWhat to do
highway.stop.error.custom_fields_invalidStop sent custom_fields with a key that isn't defined in the project.Define the field in the dashboard. Don't create field definitions from the API; set them up once and version them.
highway.optimization.error.no_result_foundNo combination of skills + windows fits all appointments.Page the supervisor; resolve with one of the recovery patterns above.
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.task.error.not_foundPUT /v2/task/{task_id} or DELETE /v2/task/{task_id} referenced a task that's been removed (or never existed).Read the stop's current task list before mutating.
400 Bad Request (no message_id) on POST /v2/taskRequired field missing (label) or a barcode that doesn't fit the expected length.Read the response message, fix the payload.
highway.stop.error.move_not_pending_stopsTried to move a stop that is no longer pending (completed, incomplete or canceled).Create a new stop with a new external_id derived from the same ticket.

Next steps

  • Capacitated distribution: when your technicians also carry inventory (spare parts as requires / van as weight/volume), combine this recipe with capacity constraints.
  • Webhooks: the full cycle, event catalog, retries, delivery log and authentication patterns.
  • Idempotency: reschedule patterns and how to identify a retry vs. a genuine new appointment.
  • API Reference → POST /v2/task: the exact task body schema.