Delivery Tracking Build

Stage 02 · Interactions

Home › Apps › Delivery Tracking › Stage 02
Stage 02 · 3–4 hours

Make the tracking real.
State machine. Event log. Derived status.

The shell becomes a working tracking system. Deliveries move through states: pending, assigned, picked_up, in_transit, out_for_delivery, delivered. Each transition is an event. The current status is derived from the event log, not stored. The state machine rejects invalid transitions. Tapping "delivered" twice does not create two events. The customer timeline derives from the same events. Everything persists in localStorage.

3–4 hours Intermediate JavaScript · DOM · localStorage · state machine
Delivery hub State shape The state machine Derived status Idempotent events Customer timeline localStorage Next: Stage 03

Short answer: One state object with deliveries, events, couriers, and view. One TRANSITIONS map that encodes which event types are valid from which statuses. One deriveDeliveryStatus(events) that walks the event log and produces the current status. One recordEvent(deliveryId, type) with three idempotency guards. One render() that rebuilds all three views from state. One saveState() called on every mutation.

State shape - facts, not conclusions

Deliveries, events, couriers. Nothing derived.

The state object holds only the raw facts: who the couriers are, which deliveries exist, and what events have happened. Every other value — current status, timeline, KPI counts — is a function of these three arrays.

state.js delivery-stage-02.html · lines 480–505
const state = {
deliveries: [], // [{ id, trackingCode, customer, address, destination }]
events: [], // [{ id, deliveryId, type, location, note, occurredAt }]
couriers: [], // [{ id, name, status }]
view: 'customer' // 'customer' | 'courier' | 'dispatcher'
};

// The state machine. For each event type, which current statuses
// make it a valid transition.
const TRANSITIONS = {
'assigned': ['pending'],
'picked_up': ['assigned'],
'in_transit': ['picked_up'],
'out_for_delivery': ['in_transit'],
'delivered': ['out_for_delivery'],
'failed': ['assigned', 'picked_up', 'in_transit', 'out_for_delivery']
};

// What status results from each event type
const EVENT_RESULT = {
'assigned': 'assigned',
'picked_up': 'picked_up',
'in_transit': 'in_transit',
'out_for_delivery': 'out_for_delivery',
'delivered': 'delivered',
'failed': 'failed'
};
' as a note would inject script into the customer page. Applying escapeHtml to both is the safe default. If it's ever unclear whether a value is user-controlled, escape it. Same discipline as POS Stage 02.

localStorage - survive the reload

Save on every mutation. Restore on load.

The state persists under three keys: mak-delivery-deliveries, mak-delivery-events, and mak-delivery-view. On load, if they exist, they're restored. If not, the seed data runs.

persist.js delivery-stage-02.html · lines 790–820
var DELIVERIES_KEY = 'mak-delivery-deliveries';
var EVENTS_KEY = 'mak-delivery-events';
var VIEW_KEY = 'mak-delivery-view';

function saveState() {
try {
localStorage.setItem(DELIVERIES_KEY, JSON.stringify(state.deliveries));
localStorage.setItem(EVENTS_KEY, JSON.stringify(state.events));
localStorage.setItem(VIEW_KEY, state.view);
} catch (_) {
// Quota or private mode - app works in-memory
}
}

function loadState() {
var deliveries = null, events = null, view = 'customer';
try {
var dRaw = localStorage.getItem(DELIVERIES_KEY);
var eRaw = localStorage.getItem(EVENTS_KEY);
var vRaw = localStorage.getItem(VIEW_KEY);
if (dRaw && eRaw) {
var dParsed = JSON.parse(dRaw);
var eParsed = JSON.parse(eRaw);
if (Array.isArray(dParsed) && dParsed.length > 0) {
deliveries = dParsed;
events = Array.isArray(eParsed) ? eParsed : [];
}
}
if (vRaw === 'customer' || vRaw === 'courier' || vRaw === 'dispatcher') {
view = vRaw;
}
} catch (_) { /* fall through to seed */ }

if (deliveries && events) {
state.deliveries = deliveries;
state.events = events;
} else {
state.deliveries = SEED_DELIVERIES.slice();
state.events = seedEvents();
saveState();
}
state.view = view;
}
var DELIVERIES_KEY = 'mak-delivery-deliveries';
var EVENTS_KEY = 'mak-delivery-events';
var VIEW_KEY = 'mak-delivery-view';

function saveState() {
try {
localStorage.setItem(DELIVERIES_KEY, JSON.stringify(state.deliveries));
localStorage.setItem(EVENTS_KEY, JSON.stringify(state.events));
localStorage.setItem(VIEW_KEY, state.view);
} catch (_) {
// Quota or private mode - app works in-memory
}
}

function loadState() {
var deliveries = null, events = null, view = 'customer';
try {
var dRaw = localStorage.getItem(DELIVERIES_KEY);
var eRaw = localStorage.getItem(EVENTS_KEY);
var vRaw = localStorage.getItem(VIEW_KEY);
if (dRaw && eRaw) {
var dParsed = JSON.parse(dRaw);
var eParsed = JSON.parse(eRaw);
if (Array.isArray(dParsed) && dParsed.length > 0) {
deliveries = dParsed;
events = Array.isArray(eParsed) ? eParsed : [];
}
}
if (vRaw === 'customer' || vRaw === 'courier' || vRaw === 'dispatcher') {
view = vRaw;
}
} catch (_) { /* fall through to seed */ }

if (deliveries && events) {
state.deliveries = deliveries;
state.events = events;
} else {
state.deliveries = SEED_DELIVERIES.slice();
state.events = seedEvents();
saveState();
}
state.view = view;
}
Why three keys, not one:

Deliveries are set once and rarely edited.
Events change every time an event is
recorded. The view changes on every tab
click.

Three keys means three writes on every
mutation, but each write is small. If the
events write fails (rare), the deliveries
write already succeeded - the delivery
list isn't corrupted.

One key with { deliveries, events, view }
would also work. The split mirrors the
three tables the data will live in on the
server in Stage 03.

Why the defensive check:

If localStorage has '[]' (empty array)
from a previous failed attempt, the naive
code takes the "data exists" branch,
parses it to an empty array, and never
falls back to the seed. Everything shows
zero.

This is the exact bug that bit us in HR
Stage 02. The check Array.isArray(dParsed) && dParsed.length > 0 treats an empty
array as "no data" and falls through to
the seed.

If dRaw is '[]', dParsed.length === 0, the
condition fails, deliveries stays null,
the else branch runs and seeds. Correct
behavior in every case.

Why view is validated explicitly:

The view must be one of three known values.
If localStorage has 'garbage' (user edited
it, or a previous version used a different
name), the validation falls back to
'customer'.

Validating user-writable data is a discipline.
localStorage is user-editable; you can't
trust it. Same rule as POS Stage 02's cart
filtering and HR Stage 02's event filtering.

The order matters:

loadState runs before any render, and it
must complete before render is called. If
render ran first, it would render empty
state, then loadState would populate it,
then render would need to run again.

loadState at the top of init guarantees
the first render sees real data. Same
pattern as every Stage 02 so far.

✅ The full file

The complete shell. Delivered separately so this page stays readable.

The full shell is delivery-stage-02.html — one HTML file, ~900 lines, three views, state machine, event log, derived status, localStorage persistance. Open it in a browser and the shell is alive.

The complete Stage 02 code, ready to run.

Download:
Download delivery-stage-02.html →

Right-click, save link as. Or open in a new tab and use File → Save Page.

Next: Stage 03 - Backend

Events get a home. The state machine goes server-side.

Stage 02 loses every event on localStorage clear. That's fine for a client demo - but a delivery tracking system without a server isn't a delivery tracking system. Stage 03 adds one:

The client-side state machine from Stage 02 becomes the specification for the server-side state machine. Both must produce the same result. Stage 03's test is: run the same events through both, compare.

Continue the build

Next: Stage 03 - Backend
Five tables, server-side state machine, atomic events, public tracking. 3–4 hours.
Back to the Delivery Tracking hub
All four stages, the data model, and the roadmap.
← Back to Delivery Tracking hub
Delivery Tracking Stage 02 · Interactions