Bring the counter to life.
Tap. Scan. Pay.
The shell from Stage 01 becomes a working POS. A single cart state object, tap-to-add from the product grid, live totals, a payment modal with cash tendered and change due, an 80mm receipt preview, barcode scan detection, focus management, and a cart that survives a page reload. The cart isn't persisted to a server yet — that's Stage 03 — but it survives a browser crash, which is the first thing a real POS needs.
Short answer: One state object with lines: [{productId, qty}] and taxRate. One renderCart() that rebuilds the cart lines, totals, Charge label, catalog badges, and disabled states. totals() derives subtotal, taxAmount, grandTotal from lines — never stored. Every action (add, inc, dec, remove, tax change, sale complete) calls saveCart() then renderCart() then focusBarcode(). Barcode input differentiates scans from typing by keystroke timing.
✅ Cart state — one object, five views
Store the truth. Derive everything else.
The cart state is the single source of truth. Every other UI region is a view of it:
State
lines: [{productId, qty}] · taxRate: 8.5
View 1 — Cart lines
Mapped from lines, joined with the catalog to get name + price.
View 2 — Totals
Derived from lines via totals(). Recomputed on every render.
View 3 — Charge button
Label is "Charge · " + totals().grandTotal. Disabled when lines.length === 0.
View 4 — Catalog badges
Each product card shows the in-cart qty via qtyInCart(productId).
View 5 — Product disabled states
A product is disabled when inCart >= stock. Recomputed on every cart change.
// The only state. Everything else is derived.
const state = {
lines: [], // [{ productId, qty }]
taxRate: 8.5,
categoryFilter: 'All'
};
// ─── Derived: totals ───
function lineTotal(line) {
const p = getProduct(line.productId);
return p ? p.price * line.qty : 0;
}
function totals() {
const subtotal = state.lines.reduce(function (sum, l) {
return sum + lineTotal(l);
}, 0);
// Tax on the subtotal, rounded once. See the tax section.
const taxAmount = Math.round(subtotal * state.taxRate) / 100;
const grandTotal = Math.round((subtotal + taxAmount) * 100) / 100;
return { subtotal, taxAmount, grandTotal };
}
// ─── Derived: counts ───
function itemCount() {
return state.lines.reduce(function (n, l) { return n + l.qty; }, 0);
}
function qtyInCart(productId) {
const line = state.lines.find(function (l) {
return l.productId === productId;
});
return line ? line.qty : 0;
}
// ─── Every mutation ends the same way ───
function addToCart(productId) {
/* ... validate stock, mutate state.lines ... */
saveCart();
renderCart(); // rebuilds lines, totals, catalog, buttons
}
function incQty(productId) {
/* ... */
saveCart();
renderCart();
}
function removeLine(productId) {
state.lines = state.lines.filter(function (l) {
return l.productId !== productId;
});
saveCart();
renderCart();
}
Why "lines: [{productId, qty}]" and not the full product:
The cart line needs to know:
→ which product (id)
→ how many (qty)
Everything else — name, price, stock —
already lives in CATALOG. Duplicating it
into the line creates two sources of truth.
If the price changes while the cart is open,
the line total updates automatically (because
lineTotal() looks up the price at render time).
Is that the right behavior? For Stage 02, yes —
it's a teaching choice. Stage 03 will snapshot
the price server-side at sale time, because
once a customer has paid, the price is fixed.
The lesson: in Stage 02, the cart is a
*view* over the catalog. In Stage 03, the
cart becomes a *transaction* with its own
snapshot. The shift is the whole point of
the backend stage.
Why every mutation ends with saveCart() + renderCart():
This is the discipline that prevents 90% of
cart bugs. Every path that changes state.lines
does the same three things in the same order:
1. mutate state.lines
2. saveCart() (persist to localStorage)
3. renderCart() (rebuild every view)
No path skips the render. No path mutates
the DOM directly. No path updates just one
view. If you find yourself writing
"document.querySelector('.subtotal').textContent = ..."
outside renderCart(), you've broken the pattern.
The same rule as Inventory Stage 02:
store the truth, derive the display,
render after every change.
Why renderCart() re-renders the catalog too:
The catalog shows an "in cart" badge on
products that are in the cart, and it
disables products whose stock is exhausted
by the current cart quantity. Both of those
depend on state.lines, which just changed.
So renderCart() calls renderCatalog() at
the end. The name is slightly misleading —
it rebuilds everything that depends on the
cart — but the behavior is correct. If it
didn't, the in-cart badge would go stale
every time you added an item.
✅ Derived totals
Compute on every render. Never store.
There are three values the cart displays below the lines:
Subtotal
sum(line.price × line.qty) over all lines. Derived from the catalog + lines.
Tax amount
round(subtotal × taxRate / 100, 2). Rounded once, on the subtotal. See below.
Grand total
subtotal + taxAmount. Always exactly these two values, not a third round.
The invariant: grandTotal === subtotal + taxAmount. The receipt shows all three values and they must sum correctly. This is why the tax amount is computed once on the subtotal, not per line.
function totals() {
const subtotal = state.lines.reduce(function (sum, l) {
return sum + lineTotal(l);
}, 0);
// Math.round(x * 100) / 100 is "round to 2 decimal places."
// taxAmount = subtotal * taxRate / 100, but written to round
// on the way there: round(subtotal * taxRate) / 100
// is equivalent and avoids accumulating float error.
const taxAmount = Math.round(subtotal * state.taxRate) / 100;
const grandTotal = Math.round((subtotal + taxAmount) * 100) / 100;
return { subtotal, taxAmount, grandTotal };
}
Why not subtotal * taxRate / 100 directly? Because floating-point multiplication accumulates error. 0.1 + 0.2 is 0.30000000000000004 in JavaScript. Rounding on the way to cents (multiply by 100, round, divide by 100) keeps every intermediate value representable as cents. The receipt shows cents; the math should too.
Why not grandTotal = round(subtotal × (1 + taxRate / 100), 2)? Because that computes a third rounded value, and subtotal + taxAmount can then differ from grandTotal by a cent. The invariant breaks. The three values must sum.
✅ Tax rounding — three options, one choice
Pick one. Document it. Be consistent.
Per-line rounding
Compute tax per line, round each to cents, sum. Matches some jurisdictions' invoice rules. Can overcharge vs subtotal method when many small lines.
Subtotal rounding ✱
Compute tax once on the subtotal, round to cents. What Stage 02 uses. Simple, defensible, invariant-safe.
No rounding until display
Keep full precision internally, round only at display time. subtotal + tax can differ from grandTotal by a cent. The invariant breaks.
Why subtotal rounding: the receipt must satisfy subtotal + tax = total. Subtotal rounding guarantees it by construction. Per-line rounding can break it. No-rounding-until-display definitely breaks it. Subtotal rounding is also what most retail POS systems do — if you switch to a jurisdiction that requires per-line rounding, you change the function and document it. The wrong answer is being inconsistent.
✅ Barcode input — scan detection + focus
A scanner is a fast keyboard. Treat it like one.
Two things must be true for the barcode input to work in a real POS:
1. Focus is always there
After every action — add, remove, qty change, modal close, sale complete — the barcode input regains focus. Otherwise the next scan goes nowhere.
2. Scans look different from typing
A scanner types keystrokes < 50ms apart. A human types slower. The timing distinguishes them and gives visual feedback.
// ─── Focus management ───
function focusBarcode() {
// Defer so the modal close transition finishes first
setTimeout(function () {
barcodeInput.focus();
barcodeInput.select();
}, 30);
}
// After every action that isn't typing in a field:
// addToCart() → focusBarcode()
// removeLine() → focusBarcode()
// closeModal() → focusBarcode()
// paymentSuccess() → focusBarcode()
// ─── Scan vs typing detection ───
let scanTimer = null;
const lastScan = { value: '', startedAt: 0 };
barcodeInput.addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
const value = barcodeInput.value;
barcodeWrap.classList.remove('is-scanning');
clearTimeout(scanTimer);
handleBarcodeSubmit(value);
focusBarcode();
return;
}
// Heuristic: keystrokes < 50ms apart = scan
const now = Date.now();
if (lastScan.value && (now - lastScan.startedAt) < 50) {
barcodeWrap.classList.add('is-scanning');
}
lastScan.value = barcodeInput.value;
lastScan.startedAt = now;
clearTimeout(scanTimer);
scanTimer = setTimeout(function () {
barcodeWrap.classList.remove('is-scanning');
}, 200);
});
function handleBarcodeSubmit(rawValue) {
const value = rawValue.trim();
if (!value) return;
const product = CATALOG.find(function (p) {
return p.sku.toLowerCase() === value.toLowerCase();
});
if (!product) {
showToast('No product matches "' + value + '".', true);
barcodeInput.value = '';
return;
}
addToCart(product.id);
barcodeInput.value = '';
}
Why setTimeout(30) in focusBarcode: When a modal closes, its display property flips from "flex" to "none" on the backdrop. If you try to focus the barcode input immediately, the browser is still processing the display change and the focus can get lost. Deferring 30ms lets the browser finish. The exact delay doesn't matter much — 0 might work in some browsers, 30 is safe everywhere. This is the same "let the browser catch up" pattern you've seen in Stage 01 of the Inventory build. Why .select() after .focus(): The barcode input might have text in it from a partial scan or a manual entry the cashier abandoned. .select() highlights whatever's there, so the next keystroke replaces it. Without .select(), the scanner appends to the stale value and the barcode is wrong. This is a subtle but critical detail. "Focus" isn't enough — "focus with selection" is. Why the scan heuristic isn't used functionally: The Enter key triggers handleBarcodeSubmit regardless of typing speed. A human typing SKU-003 slowly and pressing Enter works fine. The scan detection only drives the visual feedback (border turns amber). Why? Because the heuristic is imperfect. A fast typist hits keys under 50ms apart. A slow scanner (rare) hits keys over 50ms apart. The visual tells the cashier "the scanner fired" but the functional behavior is identical. No keyboard user is ever penalized for typing speed. This is the right trade-off for a POS: the scanner is the common case and it works every time; the human is the fallback and it also works every time. The visual feedback is a bonus for the scanner case. Why focusBarcode() after every action: A real POS has a queue. The cashier scans item 1, item 2, item 3 in rapid succession. If focus moves to a button after item 1's add, item 2's scan goes into the void. So: addToCart() calls focusBarcode() at the end. removeLine() does. clearCart() does. The receipt modal's close button does. The payment form's submit handler does. This is the single most important UX rule of a POS. It's also the one most tutorials skip, because in a demo everything happens one at a time. In a real queue, it's the difference between 20 seconds and 60 seconds per customer. The escape hatch: If the cashier needs to interact with the catalog (browse categories, scroll for a slow-moving item), they click elsewhere and the barcode input loses focus. That's fine — they're not scanning. When they're done, clicking a product card calls focusBarcode() again. Focus follows intent.
✅ Payment flow
Charge → tender → change → complete.
1. Open
Click Charge. The modal opens with the total due, the payment method (default cash), and the cash tendered field empty.
2. Tender
Type a cash amount, or click a quick-cash button. The change due updates live. If tendered < total, "Complete sale" is disabled and the change row turns red.
3. Complete
Click "Complete sale." A sale snapshot is built (id, lines, totals, payment). The cart is cleared. The receipt modal opens with the sale.
4. Close
Close the receipt. The barcode input regains focus. The next customer's sale can begin.
paymentForm.addEventListener('submit', function (e) {
e.preventDefault();
const t = totals();
const tendered = paymentMethod.value === 'cash'
? (parseFloat(cashTendered.value) || 0)
: t.grandTotal;
// Guard: cash must cover the total
if (paymentMethod.value === 'cash' && tendered < t.grandTotal) {
showToast('Cash tendered is less than the total.', true);
return;
}
// Build the immutable sale snapshot
const sale = {
id: 'S-' + Date.now().toString(36).toUpperCase(),
date: new Date(),
cashier: 'Alex Rivera',
lines: state.lines.map(function (l) {
const p = getProduct(l.productId);
return {
name: p.name,
qty: l.qty,
unitPrice: p.price,
lineTotal: p.price * l.qty
};
}),
subtotal: t.subtotal,
taxRate: state.taxRate,
taxAmount: t.taxAmount,
grandTotal: t.grandTotal,
payment: {
method: paymentMethod.value,
tendered: tendered,
change: Math.max(0, tendered - t.grandTotal)
}
};
// Commit: clear cart, close modal, show receipt
state.lines = [];
saveCart();
renderCart();
paymentBackdrop.classList.remove('is-open');
showReceipt(sale);
showToast('Sale completed · ' + money(t.grandTotal));
focusBarcode();
});
The sale object is a snapshot. It captures the cart at the moment of sale — names, prices, quantities, totals. The cart is then cleared, but the receipt shows what the customer actually bought. This is exactly the behavior Stage 03 formalizes on the server: the sale_line stores unit_price at sale time, never looked up from the catalog afterwards.
Why the cash-tendered guard exists: if the tendered amount is less than the total, the change due is negative. That's not a valid sale — the customer hasn't paid enough. The submit button is disabled in that state, but the guard in the handler is the last line of defense against a race (keyboard Enter, autofill, etc.).
✅ localStorage — survive the crash
Close the tab mid-sale. Reopen. Cart is there.
const CART_KEY = 'mak-pos-cart';
const TAX_KEY = 'mak-pos-tax';
function saveCart() {
try {
localStorage.setItem(CART_KEY, JSON.stringify(state.lines));
localStorage.setItem(TAX_KEY, String(state.taxRate));
} catch (_) {
// Quota exceeded or private mode — ignore.
// The cart works in-memory; it just won't survive reload.
}
}
function loadCart() {
try {
const raw = localStorage.getItem(CART_KEY);
if (raw) {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
// Filter to products that still exist in the catalog
state.lines = parsed.filter(function (l) {
return l && CATALOG.some(function (p) {
return p.id === l.productId;
});
});
}
}
const tax = localStorage.getItem(TAX_KEY);
if (tax !== null && !isNaN(parseFloat(tax))) {
state.taxRate = parseFloat(tax);
document.getElementById('tax-rate').value = state.taxRate;
}
} catch (_) {
state.lines = [];
}
}
Why filter on load:
localStorage can hold productIds that no
longer exist in the catalog — because the
catalog changed between sessions. In
Stage 02 the catalog is static, so this
never fires, but the guard is cheap and
correct.
In Stage 03, the catalog comes from the
server. A product the cashier added
yesterday might be deleted today. The
filter protects against that: the cart
loads with only products that still exist.
The cashier might notice a missing line,
but the cart doesn't crash on a stale
productId.
This is the "always validate on load"
rule: localStorage is user-writable, and
you can't trust user-writable data.
Why two keys, not one:
The cart (CART_KEY) and the tax rate
(TAX_KEY) change at different frequencies.
The cart changes on every add/remove; the
tax rate changes rarely. Splitting them
means writing one doesn't touch the other,
which is slightly faster and more readable.
Alternatively, store { cart, tax } under a
single key. That's fine too — the split is
a preference, not a requirement.
Why try/catch on both save and load:
localStorage can throw in two cases:
→ private mode with quota 0
→ quota exceeded (5MB limit)
A cart with 50 items is a few KB — the
quota is never the issue here. But private
mode on iOS Safari still throws on setItem
in some versions.
The try/catch doesn't fix the problem — it
makes the cart work in-memory and silently
fail to persist. That's the right behavior:
a cashier shouldn't see "couldn't save"
toasts for a local persistence issue. The
sale still completes; only the crash-recovery
is unavailable.
Why loadCart() runs before renderCart():
If you render first and load second, the
cart shows empty for a frame, then populates.
If you load first, the first render is
correct. Order matters:
loadCart();
renderCategories();
renderCart(); ← includes totals
focusBarcode();
➡️ Next: Stage 03 — Backend
Sales get a home.
Stage 02 loses every sale on refresh. That's fine for a client demo — but a POS without a database isn't a POS. Stage 03 adds one:
- Three tables —
sales,sale_lines,payments— with two foreign keys - The atomic checkout — insert sale, insert lines, insert payment, write
stock_movementsrows, updateproducts.quantity— all in one transaction, or none of it - Price snapshotting — the line stores
unit_priceat sale time, so tomorrow's price change doesn't rewrite yesterday's receipts - RESTRICT on sold products — you can't delete a product that has been sold; Stage 04 adds archive
- Reading Inventory's products — the POS shares the inventory database; the catalog in Stage 02 becomes
GET /api/products - Client changes — cart stays in localStorage until checkout; on Charge, the cart is sent to
POST /api/sales; on success, clear; on failure, cart survives and the toast explains why
That's Stage 03. The UI barely changes; only where the cart goes on Charge.
✅ The full file
One HTML file, ready to run.
The complete file is at /apps/pos/downloads/pos-stage-02.html. It's the same file the earlier sections described, fully assembled. Open it in a browser and it runs — no build step, no dependencies, no server. The cart persists in localStorage across reloads.
Right-click, save link as. Or open in a new tab and use File → Save Page.
Some browsers render .html files inline, others download them. The second link uses target="_blank" so the browser opens it as a live page rather than a download. If your browser still downloads it, the first link works — just open the file from your Downloads folder.
Test it
Tap a product → it's in the cart. Adjust qty. Change tax. Charge → tender → complete → receipt. Reload the page → cart is still there.
Add 8 of the "Mechanical Keyboard" — the + button disables at 8 and the line shows "Max stock reached." Tap × on any line to remove it.
Test the barcode
Click the barcode input at the top, type SKU-003, press Enter. The USB-C Cable is added. Type SKU-999 → toast error, no line added.
Test persistence
Add a few items, reload the page. The cart survives. Clear the cart, reload, it stays empty. (On Safari file:// URLs, localStorage may not persist — serve over http://localhost to test reliably.)
The demo runs entirely client-side. Open it as a file:// URL from your Downloads folder, or serve the downloads directory with python -m http.server 8000 and visit http://localhost:8000/pos-stage-02.html. The http:// origin is the more reliable way to test localStorage persistence across browsers.