Delivery Tracking Build

Stage 04 · Advanced — Final Stage

Home › Apps › Delivery Tracking › Stage 04
Stage 04 · 3–4 hours · FINAL

Make it a real system.
Proof. Retry. Bulk. Reports.

The final layer. A proof of delivery table as the sixth and last schema addition - photo, signature, or OTP evidence, one row per completed delivery. A failed-delivery retry workflow that keeps one delivery through multiple attempts. Bulk dispatch as a single transaction - 20 assignments or none. Live map polling every 30 seconds from the dispatcher dashboard. A notification queue that records intent without sending. And three reports that answer the dispatcher's daily questions.

This is the final stage. After it, the Delivery Tracking build is complete: four stages, six tables, an event log, a state machine, a public tracking page, proof of delivery, retry, bulk dispatch, and reports. No Stage 05.

3–4 hours Intermediate SQL · Flask · transactions · reports
Delivery hub Proof of delivery Failed retry Bulk dispatch Live map polling Notification queue Reports Run it Done — next steps

Short answer: Add two tables — proof_of_delivery (UNIQUE delivery_id, method, reference, captured_at, captured_by) and notifications (delivery_id, type, recipient, status, created_at). Adjust the state machine so failed can transition back to assigned or out_for_delivery. Add three endpoints: POST /api/deliveries/<id>/proof, POST /api/dispatch/bulk, GET /api/deliveries/active (already exists, now polled). Add three report endpoints: GET /api/reports/by-courier, GET /api/reports/delivery-time, GET /api/reports/failure-rate. The frontend adds a proof modal on delivered, a retry button on failed, and a batch-select for bulk dispatch.

Proof of delivery — the sixth table

Evidence is a distinct fact. It gets its own table.

A delivery can have zero or one proof-of-delivery record. Photo, signature, or OTP - each is a different way of proving the same thing: the parcel was handed to the customer (or someone at the destination). Putting this in its own table keeps the deliveries table operational and the evidence table focused.

schema.sql backend/schema.sql · lines 88–112
CREATE TABLE proof_of_delivery (
  id             INTEGER PRIMARY KEY AUTOINCREMENT,
  delivery_id    INTEGER NOT NULL UNIQUE,
  method         TEXT NOT NULL
                 CHECK (method IN ('photo', 'signature', 'otp')),
  reference      TEXT NOT NULL,
  note           TEXT,
  captured_at    TEXT NOT NULL,
  captured_by    TEXT NOT NULL DEFAULT 'courier',
  FOREIGN KEY (delivery_id) REFERENCES deliveries(id) ON DELETE CASCADE
);

CREATE TABLE notifications (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  delivery_id INTEGER NOT NULL,
  type        TEXT NOT NULL
              CHECK (type IN ('out_for_delivery', 'delivered', 'failed')),
  recipient   TEXT NOT NULL,
  status      TEXT NOT NULL DEFAULT 'pending'
              CHECK (status IN ('pending', 'sent', 'failed')),
  created_at  TEXT NOT NULL,
  sent_at     TEXT,
  FOREIGN KEY (delivery_id) REFERENCES deliveries(id) ON DELETE CASCADE
);

CREATE INDEX idx_proof_delivery     ON proof_of_delivery(delivery_id);
CREATE INDEX idx_notif_status       ON notifications(status);
CREATE INDEX idx_notif_delivery     ON notifications(delivery_id);
CREATE TABLE proof_of_delivery (
  id             INTEGER PRIMARY KEY AUTOINCREMENT,
  delivery_id    INTEGER NOT NULL UNIQUE,
  method         TEXT NOT NULL
                 CHECK (method IN ('photo', 'signature', 'otp')),
  reference      TEXT NOT NULL,
  note           TEXT,
  captured_at    TEXT NOT NULL,
  captured_by    TEXT NOT NULL DEFAULT 'courier',
  FOREIGN KEY (delivery_id) REFERENCES deliveries(id) ON DELETE CASCADE
);

CREATE TABLE notifications (
  id          INTEGER PRIMARY KEY AUTOINCREMENT,
  delivery_id INTEGER NOT NULL,
  type        TEXT NOT NULL
              CHECK (type IN ('out_for_delivery', 'delivered', 'failed')),
  recipient   TEXT NOT NULL,
  status      TEXT NOT NULL DEFAULT 'pending'
              CHECK (status IN ('pending', 'sent', 'failed')),
  created_at  TEXT NOT NULL,
  sent_at     TEXT,
  FOREIGN KEY (delivery_id) REFERENCES deliveries(id) ON DELETE CASCADE
);

CREATE INDEX idx_proof_delivery     ON proof_of_delivery(delivery_id);
CREATE INDEX idx_notif_status       ON notifications(status);
CREATE INDEX idx_notif_delivery     ON notifications(delivery_id);
Why UNIQUE delivery_id on proof:

  The relationship is 1:1 - one delivery,
  one proof. The UNIQUE constraint enforces
  it at the schema level.

  Without it, a buggy code path could insert
  two proof rows for the same delivery. Which
  one is "the" proof? The first? The latest?
  The one with the matching method? The
  ambiguity is a bug waiting to happen.

  With UNIQUE, the second insert fails. The
  code must decide: does it update the
  existing proof, or reject the new one? The
  constraint forces that decision to be made
  explicitly.

Why 'reference' is a generic TEXT:

  Different methods use different reference
  types:
    - photo: a file path or base64 payload
    - signature: an SVG string or data URI
    - otp: the 6-digit code the customer
           typed (for verification, the code
           isn't stored long-term, but the
           fact that OTP was used is)

  Making the column TEXT with a method field
  lets the caller decide how to interpret
  the reference based on the method. A
  dedicated blob column for photos, plus
  a code column for OTPs, would be over-
  engineered for Stage 04.

  Stage 04 stores the reference as a short
  string (photo path, OTP code). A real
  system with large photos would use a
  separate object store and keep the URL
  in this column. The schema is honest
  about both.

Why captured_by defaults to 'courier':

  In the happy path, the courier taps
  'delivered' and the proof is their
  action. But a dispatcher could also
  capture proof (customer called in and
  confirmed the OTP was used), and the
  value would be 'dispatcher'.

  The default reflects the common case;
  the field allows the exception. Same
  pattern as 'created_by' on delivery_events.

Why notifications has a 'pending' status:

  The notification queue is a contract:
  "this message should be sent". Whether
  it has been sent is tracked separately.

  If the app inserted rows with
  status='sent' immediately, it would be
  lying - the sending hasn't happened. If
  it omitted the status entirely, the
  notification worker couldn't tell which
  rows to process.

  status='pending' means "queued, not yet
  processed". A worker reads pending rows,
  sends them, updates status. The queue
  is durable; the worker is idempotent;
  the two are decoupled.

  This is the same pattern as an email
  outbox in any production system. Stage 04
  queues; the worker is a concept course.

Failed retry — one delivery, many attempts

The delivery stays. The attempt is the event.

A delivery fails. The customer isn't home. The dispatcher doesn't create a new delivery - the customer would have to be told a new code, and the tracking history would fragment. Instead, the original delivery is retried: the state machine allows a transition from failed back to assigned, and a new leg starts.

retry.py backend/app.py · lines 68–92
TRANSITIONS = {
    "assigned":         {"pending", "failed"},
    "picked_up":        {"assigned"},
    "in_transit":       {"picked_up"},
    "out_for_delivery": {"in_transit", "failed"},
    "delivered":        {"out_for_delivery"},
    "failed":           {"assigned", "picked_up", "in_transit", "out_for_delivery"},
}

def record_event(did, event_type, note, courier_id):
    # ... validation ...
    if not can_transition(delivery["status"], event_type):
        return jsonify({
            "error": "Cannot " + event_type + " from '" + delivery["status"] + "'."
        }), 409

    ts = now_iso()
    conn.execute(
        """INSERT INTO delivery_events
           (delivery_id, type, note, occurred_at, created_at, created_by)
           VALUES (?, ?, ?, ?, ?, 'api')""",
        (did, event_type, note, ts, ts),
    )

    if event_type == "failed":
        conn.execute(
            "UPDATE deliveries SET status = 'failed', updated_at = ? WHERE id = ?",
            (ts, did),
        )
    else:
        conn.execute(
            "UPDATE deliveries SET status = ?, updated_at = ? WHERE id = ?",
            (EVENT_RESULT[event_type], ts, did),
        )

    # ... courier status, leg refresh, notification queue, commit ...
TRANSITIONS = {
    "assigned":         {"pending", "failed"},
    "picked_up":        {"assigned"},
    "in_transit":       {"picked_up"},
    "out_for_delivery": {"in_transit", "failed"},
    "delivered":        {"out_for_delivery"},
    "failed":           {"assigned", "picked_up", "in_transit", "out_for_delivery"},
}

def record_event(did, event_type, note, courier_id):
    # ... validation ...
    if not can_transition(delivery["status"], event_type):
        return jsonify({
            "error": "Cannot " + event_type + " from '" + delivery["status"] + "'."
        }), 409

    ts = now_iso()
    conn.execute(
        """INSERT INTO delivery_events
           (delivery_id, type, note, occurred_at, created_at, created_by)
           VALUES (?, ?, ?, ?, ?, 'api')""",
        (did, event_type, note, ts, ts),
    )

    if event_type == "failed":
        conn.execute(
            "UPDATE deliveries SET status = 'failed', updated_at = ? WHERE id = ?",
            (ts, did),
        )
    else:
        conn.execute(
            "UPDATE deliveries SET status = ?, updated_at = ? WHERE id = ?",
            (EVENT_RESULT[event_type], ts, did),
        )

    # ... courier status, leg refresh, notification queue, commit ...
Why 'failed' appears in two transition lists:

  In Stage 03, the graph was strictly forward:
    pending -> assigned -> picked_up ->
    in_transit -> out_for_delivery -> delivered

  Stage 04 adds a retry edge. From 'failed',
  the dispatcher can re-assign (assigned) or
  skip directly to out_for_delivery (if the
  customer is now home and the courier is
  already on the way).

  The TRANSITIONS map gains two entries:
    'assigned' can come from 'failed'
    'out_for_delivery' can come from 'failed'

  The retry is a new event, not an edit.
  The delivery_events table records 'failed
  at 3pm' and 'assigned at 4pm'. Both rows
  exist. The timeline shows both. The
  history is preserved.

Why we don't create a new delivery on retry:

  The customer has one parcel. If we created
  delivery #47 to retry delivery #42, the
  customer would have two tracking codes
  and one package. Confusing, and a support
  burden.

  One delivery, multiple attempts. The
  tracking code stays. The timeline shows
  the failed attempt and the successful one.
  The customer tracks one thing.

  This is the same principle as a POS refund:
  the original sale is not deleted, a reversal
  is added. For delivery retries, the original
  delivery is not replaced, an additional
  attempt is recorded.

The state machine encodes the retry policy:

  Some retries are allowed from 'failed'
  (re-assign, out_for_delivery), some are
  not (you can't go from 'failed' to
  'picked_up' directly - the parcel would
  have to be re-picked-up).

  The policy is in the TRANSITIONS map.
  Changing the policy (e.g., allow
  'picked_up' from 'failed' for a
  re-pickup scenario) is one line. The
  code that uses the map doesn't change.

Bulk dispatch — 20 assignments, one transaction

All succeed, or none do.

The dispatcher selects 20 pending deliveries, picks a courier, and clicks "Assign selected". Twenty sequential API calls would fail halfway if any one of them fails, leaving 11 assignments and 9 failures. One bulk endpoint with one transaction is atomic.

bulk.py backend/app.py · lines 145–175
@app.route("/api/dispatch/bulk", methods=["POST"])
def bulk_dispatch():
    data = request.get_json(silent=True) or {}
    delivery_ids = data.get("deliveryIds") or []
    courier_id = data.get("courierId")

    if not delivery_ids or not courier_id:
        return jsonify({"error": "deliveryIds and courierId required."}), 400

    with get_db() as conn:
        courier = conn.execute(
            "SELECT * FROM couriers WHERE id = ?", (courier_id,)
        ).fetchone()
        if not courier:
            return jsonify({"error": "Courier not found."}), 404

        # Validate all deliveries BEFORE any write
        for did in delivery_ids:
            d = conn.execute(
                "SELECT * FROM deliveries WHERE id = ?", (did,)
            ).fetchone()
            if not d:
                return jsonify({"error": "Delivery " + str(did) + " not found."}), 404
            if d["status"] != "pending":
                return jsonify({
                    "error": "Delivery " + str(did) + " is " + d["status"] +
                             ", not pending. Bulk dispatch requires all pending."
                }), 409

        # All valid - do all writes in one pass
        ts = now_iso()
        for did in delivery_ids:
            conn.execute(
                "INSERT INTO delivery_events (delivery_id, type, note, occurred_at, created_at, created_by) VALUES (?, 'assigned', ?, ?, ?, 'api')",
                (did, "Bulk dispatch to " + courier["name"], ts, ts),
            )
            conn.execute(
                "UPDATE deliveries SET status = 'assigned', courier_id = ?, updated_at = ? WHERE id = ?",
                (courier_id, ts, did),
            )
            _refresh_current_leg(conn, did, "assigned", ts)

        conn.execute(
            "UPDATE couriers SET status = 'on_delivery' WHERE id = ?", (courier_id,)
        )
        conn.commit()

    return jsonify({"ok": True, "count": len(delivery_ids)}), 200
Why validate first, write second:

  The two-pass structure is the key. Pass 1
  reads every delivery and checks it can be
  assigned. Pass 2 does the writes.

  If pass 1 finds an invalid delivery, it
  returns 409 BEFORE any writes. The
  transaction is never started.

  If pass 2 hits a surprise failure (disk
  error, constraint violation on a
  delivery_id that was deleted mid-loop by
  another request), the transaction rolls
  back all 20 writes. The dispatcher sees
  500, retries the whole batch, and the
  system is in the state it was before the
  first request.

  The alternative - validate-then-write per
  delivery - would be 20 separate
  mini-transactions. Each could succeed or
  fail independently, and the dispatcher
  would need to parse a per-delivery result
  to know what to retry. Much worse.

Why the whole batch requires status='pending':

  Bulk dispatch is for "assign these pending
  deliveries to a courier". If any delivery
  is already assigned to someone else, the
  bulk operation is ambiguous: overwrite the
  existing assignment? Skip that one? Fail
  the whole batch?

  Stage 04 chooses "fail the whole batch".
  It's the strictest interpretation and the
  easiest to reason about. If the dispatcher
  wants to reassign, that's a different
  action (per-delivery, with a note).

  This is a policy choice, not a technical
  one. The transaction is the mechanism;
  the "all pending" rule is the policy.

Why the courier status flips inside the
transaction:

  When 20 deliveries are assigned, the
  courier becomes 'on_delivery'. If the
  bulk operation fails, the courier must
  stay 'available' (or whatever they were).

  The UPDATE couriers line is inside the
  `with get_db()` block. If the loop above
  raised, this line wouldn't run, and the
  rollback would restore the courier's
  previous status.

  The courier status is a derived-ish
  cache. It's updated when assignments
  happen, not on read. Same pattern as
  products.quantity in Inventory - the
  cache follows the writes, always.

Live map polling — 30 seconds, one endpoint

The dashboard refreshes without the complexity of WebSockets.

The dispatcher dashboard needs to feel live. Not sub-second live - the dispatcher isn't watching a race car. Thirty seconds is fine. The client polls GET /api/deliveries/active on a timer and re-renders the map markers and the table.

poll.js backend/static/delivery-stage-04.html · lines 780–805
var pollTimer = null;

function startPolling() {
  stopPolling();
  pollTimer = setInterval(refreshActiveDeliveries, 30000);
}

function stopPolling() {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
}

function refreshActiveDeliveries() {
  if (state.view !== 'dispatcher') return;
  if (document.hidden) return;

  api('/api/deliveries/active').then(function (r) {
    if (!r.ok) return;
    state.activeDeliveries = r.body;
    renderDispatcherMap();
    renderDispatcherTable();
  }).catch(function () { /* network hiccup - try again next tick */ });
}

document.addEventListener('visibilitychange', function () {
  if (document.hidden) stopPolling();
  else if (state.view === 'dispatcher') startPolling();
});
var pollTimer = null;

function startPolling() {
  stopPolling();
  pollTimer = setInterval(refreshActiveDeliveries, 30000);
}

function stopPolling() {
  if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
}

function refreshActiveDeliveries() {
  if (state.view !== 'dispatcher') return;
  if (document.hidden) return;

  api('/api/deliveries/active').then(function (r) {
    if (!r.ok) return;
    state.activeDeliveries = r.body;
    renderDispatcherMap();
    renderDispatcherTable();
  }).catch(function () { /* network hiccup - try again next tick */ });
}

document.addEventListener('visibilitychange', function () {
  if (document.hidden) stopPolling();
  else if (state.view === 'dispatcher') startPolling();
});
Why 30 seconds, not 5:

  A dispatcher checking the dashboard wants
  to know "is anything stuck?" - which
  requires updates in the tens-of-seconds
  range, not sub-second. A 5-second poll
  would be 12 requests per minute per open
  dashboard, 720 per hour, 17k per day.
  That's 12x the server load for a level of
  freshness the dispatcher can't perceive.

  30 seconds is the sweet spot: fresh enough
  to catch "courier has been at the same
  point for 10 minutes", cheap enough to run
  on a small server.

Why check document.hidden:

  A dispatcher might leave the dashboard open
  in a background tab for hours. Polling
  every 30 seconds from a background tab
  wastes server resources and the browser's
  connection slots.

  The visibilitychange listener stops polling
  when the tab is hidden and resumes when
  it's visible. Same pattern as the live
  clock in HR Stage 02.

Why check state.view:

  The dashboard is one of three views. If
  the dispatcher switches to the customer
  view to look something up, polling should
  stop - they're not looking at the
  dashboard. When they switch back, polling
  resumes.

  The interval keeps running during the view
  change (it was set up once), but the
  callback checks view and returns early.
  The cost is a function call every 30
  seconds - negligible. The alternative
  (start/stop on every view switch) would
  work too but adds more state to track.

Why the catch is silent:

  Polling is best-effort. If the network
  hiccups, the next 30-second tick will
  try again. Showing a toast every time a
  poll fails would spam the dispatcher
  during a flaky connection.

  On the next successful poll, the
  dashboard catches up. The dispatcher
  doesn't need to know that two polls
  failed if the third one succeeded.

  This is the honest trade-off: silent
  retry for background operations,
  visible errors for user-initiated
  actions. The user clicked "assign" -
  they should see why it failed. The
  system polled on its own - it should
  just try again.

The WebSocket alternative (concept course):

  A WebSocket connection would push
  updates as they happen, no polling.
  Server: ws.send(JSON.stringify(event))
  on every write. Client: ws.onmessage.

  But WebSockets need:
    - A WS-capable server (Flask-SocketIO,
      or a separate Node process)
    - Reconnection logic with backoff
    - Authentication on the connection
    - Heartbeat to detect dead connections
    - A pub/sub layer if multiple servers

  For a dispatcher dashboard, that's
  significant complexity for a marginal
  freshness gain over 30-second polling.

  Stage 04 implements polling. The
  WebSocket pattern lives in a concept
  course. The dispatcher dashboard works
  today; the pattern for sub-second
  freshness is there when the requirements
  demand it.

Notification queue — record intent, don't send

The app knows what happened. Sending is a separate concern.

When a delivery moves to out_for_delivery, delivered, or failed, the customer should get a notification. Stage 04 records that intent in a notifications table with status='pending'. Sending the actual email or SMS is a separate worker, not part of this build.

notify.py backend/app.py · lines 230–250
NOTIFY_ON = {"out_for_delivery", "delivered", "failed"}

def _queue_notification(conn, delivery_id, event_type, ts):
    """Insert a pending notification. Never sends - just records intent."""
    if event_type not in NOTIFY_ON:
        return

    d = conn.execute(
        """SELECT c.email FROM deliveries d
           JOIN customers c ON c.id = d.customer_id
           WHERE d.id = ?""",
        (delivery_id,),
    ).fetchone()
    if not d or not d["email"]:
        return

    conn.execute(
        """INSERT INTO notifications
           (delivery_id, type, recipient, status, created_at)
           VALUES (?, ?, ?, 'pending', ?)""",
        (delivery_id, event_type, d["email"], ts),
    )

# Called from record_event, inside the same transaction:
_queue_notification(conn, did, event_type, ts)
conn.commit()
NOTIFY_ON = {"out_for_delivery", "delivered", "failed"}

def _queue_notification(conn, delivery_id, event_type, ts):
    """Insert a pending notification. Never sends - just records intent."""
    if event_type not in NOTIFY_ON:
        return

    d = conn.execute(
        """SELECT c.email FROM deliveries d
           JOIN customers c ON c.id = d.customer_id
           WHERE d.id = ?""",
        (delivery_id,),
    ).fetchone()
    if not d or not d["email"]:
        return

    conn.execute(
        """INSERT INTO notifications
           (delivery_id, type, recipient, status, created_at)
           VALUES (?, ?, ?, 'pending', ?)""",
        (delivery_id, event_type, d["email"], ts),
    )

# Called from record_event, inside the same transaction:
_queue_notification(conn, did, event_type, ts)
conn.commit()
Why queue, not send:

  Sending an email or SMS is a network
  operation with its own failure modes:
  - The email provider is down
  - The phone number is invalid
  - The customer unsubscribed
  - Rate limits hit

  If the notification send happened inside
  the event recording transaction, a failed
  email would roll back a successful
  delivery. The courier would tap "delivered",
  the DB would refuse, and the UI would
  show "delivery failed" even though the
  parcel was actually delivered. Data loss
  for a downstream concern.

  The queue decouples them. The event
  records. The delivery succeeds. The
  notification is queued. A separate worker
  processes the queue on its own schedule,
  retrying failed sends, respecting rate
  limits, logging issues.

  The user-facing promise ("delivery is
  recorded") is independent of the
  downstream promise ("customer is
  notified"). The queue is the seam.

Why NOTIFY_ON is a set:

  Only three event types warrant a customer
  notification. 'assigned', 'picked_up', and
  'in_transit' are internal - the customer
  doesn't need a message for each.

  The set makes the policy explicit. If
  someone later wants 'picked_up' notifications
  (a pre-delivery reassurance), it's one
  value added. The code that calls
  _queue_notification doesn't change.

Why the recipient is looked up, not passed in:

  The caller (record_event) doesn't know
  the customer's email. It knows the
  delivery_id.

  _queue_notification joins deliveries to
  customers to fetch the email. One query,
  always the correct email even if the
  customer updates it between events.

  The alternative - passing the email from
  the caller - would require every caller
  to look up the customer first, and would
  risk passing a stale email. Better to
  look it up at the moment of queueing.

Why the notification insert is inside the
same transaction as the event:

  If the event insert succeeds but the
  notification insert fails (unlikely, but
  possible with a constraint violation),
  the whole transaction rolls back. The
  delivery status stays unchanged, no
  phantom event is recorded, no
  notification is orphaned.

  The invariant is: every recorded event
  that should trigger a notification has
  exactly one queued notification. The
  transaction makes it hold.

  The alternative - queueing after the
  commit - would allow an event to succeed
  and a notification to be missing. The
  customer wouldn't know their package
  shipped. That's a silent failure mode.

Reports — three aggregates, one pattern

By courier, delivery time, failure rate.

The reports view answers the three questions a dispatcher asks every day. Each is a SQL aggregate over a date range, with a group-by dimension and a computed metric. Same shape as the HR timesheet and the POS Z-report.

reports.py backend/app.py · lines 285–320
@app.route("/api/reports/by-courier", methods=["GET"])
def report_by_courier():
    from_date = request.args.get("from")
    to_date = request.args.get("to")

    with get_db() as conn:
        rows = conn.execute(
            """SELECT co.name AS courier_name,
                      COUNT(CASE WHEN d.status = 'delivered' THEN 1 END) AS delivered,
                      COUNT(CASE WHEN d.status = 'failed'    THEN 1 END) AS failed,
                      COUNT(*) AS total
               FROM deliveries d
               LEFT JOIN couriers co ON co.id = d.courier_id
               WHERE d.updated_at BETWEEN ? AND ?
               GROUP BY co.name
               ORDER BY delivered DESC""",
            (from_date + "T00:00:00", to_date + "T23:59:59"),
        ).fetchall()

    result = []
    for r in rows:
        total = r["total"] or 0
        rate = (r["failed"] / total * 100) if total > 0 else 0
        result.append({
            "courier": r["courier_name"] or "Unassigned",
            "delivered": r["delivered"],
            "failed": r["failed"],
            "total": total,
            "failureRate": round(rate, 1),
        })
    return jsonify(result)
@app.route("/api/reports/by-courier", methods=["GET"])
def report_by_courier():
    from_date = request.args.get("from")
    to_date = request.args.get("to")

    with get_db() as conn:
        rows = conn.execute(
            """SELECT co.name AS courier_name,
                      COUNT(CASE WHEN d.status = 'delivered' THEN 1 END) AS delivered,
                      COUNT(CASE WHEN d.status = 'failed'    THEN 1 END) AS failed,
                      COUNT(*) AS total
               FROM deliveries d
               LEFT JOIN couriers co ON co.id = d.courier_id
               WHERE d.updated_at BETWEEN ? AND ?
               GROUP BY co.name
               ORDER BY delivered DESC""",
            (from_date + "T00:00:00", to_date + "T23:59:59"),
        ).fetchall()

    result = []
    for r in rows:
        total = r["total"] or 0
        rate = (r["failed"] / total * 100) if total > 0 else 0
        result.append({
            "courier": r["courier_name"] or "Unassigned",
            "delivered": r["delivered"],
            "failed": r["failed"],
            "total": total,
            "failureRate": round(rate, 1),
        })
    return jsonify(result)
Why COUNT(CASE WHEN ... THEN 1 END):

  This is the portable conditional count.
  COUNT(*) counts every row. COUNT(CASE
  WHEN cond THEN 1 END) counts only rows
  where the condition is true (the ELSE
  is NULL, and COUNT ignores NULL).

  COUNT(*) FILTER (WHERE ...) is cleaner
  but SQLite only added FILTER in 3.30
  (2019). The CASE form works everywhere.

  Same pattern as the late/absent counts
  in HR's report and the sale/refund
  split in POS's Z-report.

Why the failure rate is computed in Python:

  The SQL could do it:
    ROUND(COUNT(CASE WHEN status='failed' THEN 1 END)
          * 100.0 / COUNT(*), 1)
  as an expression.

  But that's hard to read in the middle of
  a multi-line query. Doing it in Python
  after fetching the raw counts is cleaner:
  the SQL returns three numbers, the Python
  computes one ratio.

  The rule: keep SQL for "fetch the
  aggregate numbers", use Python for "compute
  the derived metric". The split keeps both
  layers readable.

Why the WHERE clause uses updated_at:

  The report wants "deliveries that
  transitioned to delivered or failed
  today". A delivery created yesterday but
  delivered today should count today.

  updated_at is the timestamp of the last
  status change. Filtering on it captures
  "what happened today", not "what was
  created today".

  If you wanted "deliveries created today,
  regardless of when they completed",
  filter on created_at. Different question,
  different column.

  Stage 04 uses updated_at because the
  dispatcher's daily review is about
  today's activity, not today's intake.

Why 'Unassigned' appears in the results:

  The LEFT JOIN keeps deliveries with
  courier_id = NULL (pending, unassigned).
  Grouping by co.name groups all of them
  under "Unassigned".

  This is correct - the dispatcher wants
  to see "3 pending, no courier yet" as a
  row, not as invisible data. The LEFT
  JOIN preserves it.

  Same LEFT JOIN discipline as every
  previous report.

Run it

Same three commands. Two new tables.

Folder structure:
apps/delivery/downloads/backend/
├── app.py                  (updated: proof, bulk, reports, notifications)
├── database.py             (unchanged)
├── schema.sql              (updated: adds proof_of_delivery, notifications)
├── seed.py                 (updated: seeds some proof records)
├── requirements.txt        (unchanged)
├── README.md               (updated)
└── static/
    └── delivery-stage-04.html  (updated: proof modal, retry, bulk, reports)
Commands — note the reseed:
cd apps/delivery/downloads/backend
python seed.py        # WIPES delivery.db and reseeds with new tables
python app.py         # http://localhost:5000

You must reseed. The Stage 03 database has five tables; Stage 04 expects seven. seed.py drops and recreates everything. Any data you added in Stage 03 is lost - that is fine, it was sample data. In a real migration, you would write an ALTER TABLE script; here, reseeding is the honest reset.

Test proof of delivery

Courier view: pick a delivery that's out_for_delivery, click "Mark as delivered" → proof modal opens with method selector, reference field, note. Submit → delivery delivered, proof row created.

Test failed retry

Courier reports a failure. Status becomes failed. Dispatcher clicks the row → "Retry" option → assign to courier → delivery goes back to assigned. Timeline shows failed and assigned.

Test bulk dispatch

Dispatcher selects multiple pending deliveries (checkboxes), picks a courier, clicks "Dispatch selected" → all assigned in one action. If one isn't pending, the whole batch fails.

Test polling

Open dispatcher view. Watch the network tab - every 30 seconds, a request to /api/deliveries/active. Tab away → polling stops. Tab back → polling resumes.

Test notification queue

Mark a delivery out_for_delivery. Check the DB: sqlite3 delivery.db "SELECT * FROM notifications" → one pending row. It never sends - the queue is the point.

Test reports

Reports tab → three tables: by courier, delivery time, failure rate. Date filter defaults to this week. Numbers reconcile with the dashboard KPIs.

Common mistakes

What to check if Stage 04 doesn't work.

1. Not reseeding after the schema change

Stage 03 has five tables; Stage 04 needs seven. Fix: python seed.py (destructive - recreates the DB).

2. Storing proof as columns on deliveries

Creates nullable columns that only apply when delivered. Fix: separate table with UNIQUE delivery_id.

3. Creating a new delivery on retry

Customer has two tracking codes for one parcel. Fix: allow 'failed' to transition back to 'assigned' - one delivery, many attempts.

4. Bulk dispatch as 20 API calls

Half-success leaves the dispatcher confused about what was assigned. Fix: one endpoint, one transaction, all-or-nothing.

5. Sending notifications inside the transaction

A failed email rolls back a successful delivery. Fix: queue the notification, send in a separate worker.

6. Polling without visibility check

Background tabs poll every 30 seconds, wasting server resources. Fix: visibilitychange listener stops and resumes.

7. Failure rate computed in SQL as a nested expression

Hard to read, easy to get wrong. Fix: fetch raw counts, compute the ratio in Python.

8. Using created_at instead of updated_at for daily reports

"Delivered today" needs the delivery timestamp, not the creation timestamp. Fix: filter on updated_at.

Frequently asked

Why is proof of delivery its own table?

Because a delivery has zero or one proof record, but a proof record may have many attributes. Stuffing them into deliveries would create nullable columns that only apply when delivered. More importantly, the proof is evidence - a distinct fact queried differently from operational data. An auditor asks "show me the proof for delivery 42". An operations dashboard asks "how many deliveries are active". Separating them keeps both queries fast.

Why does a failed delivery stay one delivery on retry?

Because the customer has one parcel. If a delivery fails and is retried, the customer shouldn't have to track a new code. The original tracking code stays valid. The state machine allows 'failed' to transition back to 'assigned' or 'out_for_delivery'. Each retry is a new leg, indexed higher than the previous. One delivery, multiple attempts, one tracking code.

What makes bulk dispatch different from 20 API calls?

Atomicity. Twenty sequential calls mean twenty chances to fail halfway. A single bulk endpoint runs all 20 inside one transaction. If any fails, all 20 roll back. The dispatcher gets a clear all-or-nothing result. Same transaction discipline as POS's atomic checkout, applied to a batch operation.

Why polling instead of WebSockets?

Because polling is the simplest thing that works for the dispatcher's operational cadence. A dispatcher needs to know if a courier is stuck - tens of seconds of freshness is enough. WebSockets add a lot of complexity (reconnection, heartbeats, pub/sub) for a marginal gain over 30-second polling. Stage 04 implements polling and names WebSockets as a concept course.

What does the notification queue do?

Records intent. When a delivery transitions to a customer-relevant state, a pending row is inserted. Stage 04 never sends - the notifications sit in the table. A real system has a separate worker that reads pending rows, sends them, updates status. The queue is the contract between the operational app and the notification service.

What do the reports answer?

Three questions a dispatcher asks every day: how many deliveries did each courier complete, how long did deliveries take on average, and what percentage failed. Each is a SQL aggregate over delivery_events or deliveries with a date filter. Same shape as the HR timesheet and POS Z-report.

Is this the final stage?

Yes. The Delivery Tracking build is four stages. Stage 04 completes it. WebSocket live updates, real map tile integration, offline sync, and a production notification sender are separate concept courses - not Stage 05.

You're done — the Delivery Tracking build is complete

Four stages. Seven tables. An event log with a derived legs cache. A server-side state machine with retry. Atomic event recording. A public tracking page. Proof of delivery as evidence. Bulk dispatch. Live polling. A notification queue. Three reports. The app a small courier operation could run on.

The full build
✓ Stage 01 — Interface · three-view shell: customer tracking, courier event log, dispatcher dashboard
✓ Stage 02 — Interactions · state machine, derived status, idempotent events, localStorage
✓ Stage 03 — Backend · five tables, server state machine, atomic events, public tracking
✓ Stage 04 — Advanced · proof, retry, bulk dispatch, polling, notifications, reports
Back to the Delivery Tracking hub
All four stages in one place, with the data model and the download links for the full backend.

Build something new. The four-stage arc is a template for any app that tracks state transitions under partial failure: field service, order fulfilment, ticketing, on-call scheduling. Same event-log discipline, same state machine pattern, same approval/retry workflows. The pattern is the reusable thing.

← Back to Delivery Tracking hub
Delivery Tracking Stage 04 · Advanced · Final