Capstone: The Fee Tracker
The Fee Tracker has appeared in examples throughout this course: late fees in the operators lessons, receipts in the strings lessons, balances in the objects lessons, payments in the async lessons. This capstone builds the whole application at last, using the structure from "Structuring a JavaScript Application" and the patterns from every project before it. A school office uses it to record payments for Navika, Srihitha and Advitha Anamaneni (and any other students), see who owes what including late fees, and keep everything saved between visits. When you finish, you'll have built a real, tested, accessible app with no framework at all.
What You'll Build
- Domain modules: money (cents and formatting), fee rules (late fees, balances) and payment validation, all pure and tested.
- A store: one state object changed only by actions through a reducer, saved to
localStorage. - A payment form: validated with helpful, accessible errors.
- A student list: balances, days late and late fees, sorted by amount due, with a total.
- Undo for the last payment, and an export to CSV.
The Plan
| File | Layer | Responsibility |
|---|---|---|
domain/money.js | Domain | toCents, formatUsd |
domain/fees.js | Domain | lateFee, amountDue, applyPayment |
domain/validation.js | Domain | parsePayment |
state/store.js | State | Reducer, undo, subscribe |
data/storage.js | Data | Load and save with validation |
ui/*.js | UI | Form, list, totals |
main.js | Wiring | Create everything and connect it |
Build from the inside out: domain first (with tests), then state, then data, then the UI.
Step 1: Money
Money is stored in integer cents everywhere, converted only at the edges (reading the form, displaying a value):
function toCents(text) {
const match = /^\$?\s*(\d{1,6})(?:\.(\d{1,2}))?$/.exec(String(text).trim().replaceAll(",", ""));
if (!match) return null;
return Number(match[1]) * 100 + Number((match[2] ?? "0").padEnd(2, "0"));
}
const usd = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const formatUsd = (cents) => usd.format(cents / 100);
console.log(["120", "$45.5", "1,350.00", "0.07", "12.345", "abc", "-5"].map(toCents));
console.log(formatUsd(135000), formatUsd(4550), formatUsd(-250));[12000, 4550, 135000, 7, null, null, null]
$1,350.00 $45.50 -$2.50Parsing digits directly (rather than Math.round(Number(text) * 100)) avoids floating-point surprises entirely, and anything unexpected (three decimals, letters, a minus sign) returns null.
Step 2: Fee Rules
The office's rules: a 10-day grace period after the due date, then $2 per day, capped at $30. Payments reduce the balance; overpayments are rejected:
const RULES = { graceDays: 10, perDayCents: 200, capCents: 3000 };
const daysBetween = (from, to) => Math.round((Date.parse(to) - Date.parse(from)) / 86_400_000);
function lateFee(student, today, rules = RULES) {
if (student.balanceCents <= 0) return 0;
const late = daysBetween(student.dueDate, today) - rules.graceDays;
const total = Math.min(Math.max(late, 0) * rules.perDayCents, rules.capCents);
return Math.max(total - (student.feesChargedCents ?? 0), 0);
}
const amountDue = (student, today) => student.balanceCents + lateFee(student, today);
function applyPayment(student, amountCents, today) {
const due = amountDue(student, today);
if (amountCents > due) throw new RangeError(`Payment is more than the ${due / 100} dollars due`);
const fee = lateFee(student, today);
return {
...student,
balanceCents: student.balanceCents + fee - amountCents,
feesChargedCents: (student.feesChargedCents ?? 0) + fee,
};
}
const srihitha = { name: "Srihitha", balanceCents: 45000, dueDate: "2026-01-01" };
for (const day of ["2026-01-08", "2026-01-14", "2026-02-20"]) console.log(day, lateFee(srihitha, day), amountDue(srihitha, day));
const paid = applyPayment(srihitha, 20000, "2026-01-14");
console.log(paid);
console.log(amountDue(paid, "2026-01-14"), amountDue(paid, "2026-01-20"));2026-01-08 0 45000
2026-01-14 600 45600
2026-02-20 3000 48000
{ name: 'Srihitha', balanceCents: 25600, dueDate: '2026-01-01', feesChargedCents: 600 }
25600 26800On January 14 Srihitha is 13 days past the due date, 3 days past the grace period, so the fee is $6. Recording a payment adds the outstanding late fee to the balance first, then subtracts the payment, and remembers that $6 has been charged in feesChargedCents. Right after paying she owes exactly $256. Six days later the total fee for being 19 days late is $18, of which $6 was already charged, so $12 more is due: $268. The fee still never passes the $30 cap in total.
Dates here are plain YYYY-MM-DD strings, which Date.parse reads as UTC midnight, so the day count is exact in any time zone. (With Temporal, Temporal.PlainDate.from(due).until(today).days expresses the same thing even more clearly.)
Step 3: Validation
function parsePayment({ studentId, amount, method }, students) {
const errors = {};
if (!students.some((s) => s.id === studentId)) errors.studentId = "Choose a student.";
const amountCents = toCents(amount);
if (amountCents === null || amountCents === 0) errors.amount = "Enter an amount like 120 or 45.50.";
if (!["card", "ach", "check"].includes(method)) errors.method = "Choose a payment method.";
return Object.keys(errors).length ? { ok: false, errors } : { ok: true, payment: { studentId, amountCents, method } };
}
function toCents(text) {
const m = /^\$?\s*(\d{1,6})(?:\.(\d{1,2}))?$/.exec(String(text).trim().replaceAll(",", ""));
return m ? Number(m[1]) * 100 + Number((m[2] ?? "0").padEnd(2, "0")) : null;
}
const students = [{ id: "s1" }, { id: "s2" }];
console.log(parsePayment({ studentId: "s1", amount: "120.50", method: "card" }, students));
console.log(parsePayment({ studentId: "s9", amount: "0", method: "cash" }, students));{ ok: true, payment: { studentId: 's1', amountCents: 12050, method: 'card' } }
{ ok: false, errors: { studentId: 'Choose a student.', amount: 'Enter an amount like 120 or 45.50.', method: 'Choose a payment method.' } }Returning { ok, errors } (instead of throwing) suits forms, where you want every problem at once, keyed by field name so each message can appear next to its field.
Step 4: Tests for the Domain
import { test } from "node:test";
import assert from "node:assert/strict";
const RULES = { graceDays: 10, perDayCents: 200, capCents: 3000 };
const daysBetween = (a, b) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
const lateFee = (s, today) => {
if (s.balanceCents <= 0) return 0;
const total = Math.min(Math.max(daysBetween(s.dueDate, today) - RULES.graceDays, 0) * RULES.perDayCents, RULES.capCents);
return Math.max(total - (s.feesChargedCents ?? 0), 0);
};
const student = { balanceCents: 45000, dueDate: "2026-01-01" };
test("no fee during the grace period", () => {
assert.equal(lateFee(student, "2026-01-11"), 0);
});
test("$2 per day after the grace period", () => {
assert.equal(lateFee(student, "2026-01-12"), 200);
assert.equal(lateFee(student, "2026-01-16"), 1000);
});
test("the fee is capped at $30", () => {
assert.equal(lateFee(student, "2026-06-01"), 3000);
});
test("no fee when nothing is owed", () => {
assert.equal(lateFee({ ...student, balanceCents: 0 }, "2026-06-01"), 0);
});
test("fees already charged are never charged again", () => {
assert.equal(lateFee({ ...student, feesChargedCents: 600 }, "2026-01-14"), 0);
assert.equal(lateFee({ ...student, feesChargedCents: 3000 }, "2026-06-01"), 0);
});✔ no fee during the grace period (0.269709ms)
✔ $2 per day after the grace period (0.045667ms)
✔ the fee is capped at $30 (0.033ms)
✔ no fee when nothing is owed (0.033208ms)
✔ fees already charged are never charged again (0.2815ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2.7055In the real project, these tests import from domain/fees.js and run with node --test (see "Testing in Practice"). Write them before the UI: bugs in fee rules cost real families real money.
Step 5: The Store
Every change is an action. The reducer uses the domain functions, so the rules live in exactly one place:
export function reducer(state, action) {
switch (action.type) {
case "payment/recorded": {
const { studentId, amountCents, method } = action.payment;
return {
...state,
students: state.students.map((s) => (s.id === studentId ? applyPayment(s, amountCents, action.today) : s)),
payments: [...state.payments, { ...action.payment, id: state.nextId, date: action.today }],
nextId: state.nextId + 1,
};
}
default:
return state;
}
}Note that today arrives inside the action: the reducer stays pure, and the UI decides what "today" is (the real date in the app, a fixed date in tests). Undo keeps a stack of previous states, exactly as in "Managing State".
Step 6: Saving
const KEY = "feeTracker.v1";
export function loadState(fallback) {
try {
const saved = JSON.parse(localStorage.getItem(KEY));
const valid = saved && Array.isArray(saved.students) && Array.isArray(saved.payments) && Number.isInteger(saved.nextId);
return valid ? saved : fallback;
} catch {
return fallback;
}
}
export const saveState = (state) => localStorage.setItem(KEY, JSON.stringify(state));The key includes a version (v1). If the saved shape changes in a later release, a new key (or a small migration function) avoids crashing on old data.
The Complete App
Everything from Steps 1 to 6, wired together in one page (in the real project these are separate modules). "Today" is fixed at January 14, 2026, so the output is predictable. The checker first submits an invalid form, then records a $200 check from Srihitha, a $45 ACH payment from Advitha, undoes the last payment, and exports CSV:
<h1>Fee Tracker</h1>
<form id="payment-form" novalidate>
<label>Student <select id="student" name="studentId" aria-describedby="studentId-error"><option value="">Choose...</option></select></label>
<p id="studentId-error"></p>
<label>Amount <input id="amount" name="amount" inputmode="decimal" aria-describedby="amount-error"></label>
<p id="amount-error"></p>
<label>Method <select id="method" name="method" aria-describedby="method-error"><option value="">Choose...</option><option value="card">Card</option><option value="ach">ACH</option><option value="check">Check</option></select></label>
<p id="method-error"></p>
<button id="record">Record payment</button>
</form>
<p role="status" id="status"></p>
<table><tbody id="students"></tbody><tfoot><tr><th>Total due</th><td id="total"></td></tr></tfoot></table>
<button type="button" id="undo">Undo last payment</button>
<button type="button" id="export">Export CSV</button>
<script type="module">
// domain/money.js
const toCents = (text) => {
const m = /^\$?\s*(\d{1,6})(?:\.(\d{1,2}))?$/.exec(String(text).trim().replaceAll(",", ""));
return m ? Number(m[1]) * 100 + Number((m[2] ?? "0").padEnd(2, "0")) : null;
};
const usdFormat = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
const formatUsd = (cents) => usdFormat.format(cents / 100);
// domain/fees.js
const RULES = { graceDays: 10, perDayCents: 200, capCents: 3000 };
const daysBetween = (a, b) => Math.round((Date.parse(b) - Date.parse(a)) / 86_400_000);
const lateFee = (s, today) => {
if (s.balanceCents <= 0) return 0;
const total = Math.min(Math.max(daysBetween(s.dueDate, today) - RULES.graceDays, 0) * RULES.perDayCents, RULES.capCents);
return Math.max(total - (s.feesChargedCents ?? 0), 0);
};
const amountDue = (s, today) => s.balanceCents + lateFee(s, today);
const applyPayment = (s, cents, today) => {
if (cents > amountDue(s, today)) throw new RangeError(`That's more than the ${formatUsd(amountDue(s, today))} due.`);
const fee = lateFee(s, today);
return { ...s, balanceCents: s.balanceCents + fee - cents, feesChargedCents: (s.feesChargedCents ?? 0) + fee };
};
// domain/validation.js
function parsePayment({ studentId, amount, method }, students) {
const errors = {};
if (!students.some((s) => s.id === studentId)) errors.studentId = "Choose a student.";
const amountCents = toCents(amount);
if (!amountCents) errors.amount = "Enter an amount like 120 or 45.50.";
if (!["card", "ach", "check"].includes(method)) errors.method = "Choose a payment method.";
return Object.keys(errors).length ? { ok: false, errors } : { ok: true, payment: { studentId, amountCents, method } };
}
// state/store.js
function reducer(state, action) {
if (action.type !== "payment/recorded") return state;
const { studentId, amountCents } = action.payment;
return {
...state,
students: state.students.map((s) => (s.id === studentId ? applyPayment(s, amountCents, action.today) : s)),
payments: [...state.payments, { ...action.payment, id: state.nextId, date: action.today }],
nextId: state.nextId + 1,
};
}
// data/storage.js
const KEY = "feeTracker.v1";
const initial = {
students: [
{ id: "s1", name: "Srihitha Anamaneni", balanceCents: 45000, dueDate: "2026-01-01" },
{ id: "s2", name: "Advitha Anamaneni", balanceCents: 4500, dueDate: "2026-01-10" },
{ id: "s3", name: "Navika Anamaneni", balanceCents: 12000, dueDate: "2025-12-01" },
],
payments: [],
nextId: 1,
};
const loadState = () => {
try {
const s = JSON.parse(localStorage.getItem(KEY));
return s && Array.isArray(s.students) && Array.isArray(s.payments) ? s : initial;
} catch { return initial; }
};
// main.js and ui/
const TODAY = "2026-01-14";
let state = loadState();
let past = [];
const form = document.querySelector("#payment-form");
const status = document.querySelector("#status");
document.querySelector("#student").append(...state.students.map((s) => new Option(s.name, s.id)));
function render() {
const rows = state.students.toSorted((a, b) => amountDue(b, TODAY) - amountDue(a, TODAY));
document.querySelector("#students").replaceChildren(...rows.map((s) => {
const tr = document.createElement("tr");
const fee = lateFee(s, TODAY);
for (const text of [s.name, formatUsd(amountDue(s, TODAY)), fee ? `includes ${formatUsd(fee)} late fee` : ""]) tr.append(Object.assign(document.createElement("td"), { textContent: text }));
return tr;
}));
const total = state.students.reduce((sum, s) => sum + amountDue(s, TODAY), 0);
document.querySelector("#total").textContent = formatUsd(total);
document.querySelector("#undo").disabled = past.length === 0;
console.log(rows.map((s) => `${s.name.split(" ")[0]} ${formatUsd(amountDue(s, TODAY))}`).join(", "), "| total", formatUsd(total));
}
function dispatch(action) {
past = [...past, state];
state = reducer(state, action);
localStorage.setItem(KEY, JSON.stringify(state));
render();
}
form.addEventListener("submit", (e) => {
e.preventDefault();
const result = parsePayment(Object.fromEntries(new FormData(form)), state.students);
for (const field of ["studentId", "amount", "method"]) {
form.querySelector(`#${field}-error`).textContent = result.errors?.[field] ?? "";
form.elements[field].setAttribute("aria-invalid", String(Boolean(result.errors?.[field])));
}
if (!result.ok) {
console.log("not recorded:", Object.values(result.errors).join(" "));
return;
}
try {
dispatch({ type: "payment/recorded", payment: result.payment, today: TODAY });
status.textContent = `Recorded ${formatUsd(result.payment.amountCents)}.`;
form.reset();
} catch (err) {
past = past.slice(0, -1);
status.textContent = err.message;
console.log("not recorded:", err.message);
}
});
document.querySelector("#undo").addEventListener("click", () => {
if (!past.length) return;
state = past.at(-1);
past = past.slice(0, -1);
localStorage.setItem(KEY, JSON.stringify(state));
status.textContent = "Last payment undone.";
render();
});
document.querySelector("#export").addEventListener("click", () => {
const names = new Map(state.students.map((s) => [s.id, s.name]));
const csv = ["id,date,student,method,amount", ...state.payments.map((p) => [p.id, p.date, names.get(p.studentId), p.method, (p.amountCents / 100).toFixed(2)].join(","))].join("\n");
console.log(csv);
});
render();
</script>Srihitha $456.00, Navika $150.00, Advitha $45.00 | total $651.00
not recorded: Choose a student. Enter an amount like 120 or 45.50. Choose a payment method.
Srihitha $256.00, Navika $150.00, Advitha $45.00 | total $451.00
Srihitha $256.00, Navika $150.00, Advitha $0.00 | total $406.00
Srihitha $256.00, Navika $150.00, Advitha $45.00 | total $451.00
id,date,student,method,amount
1,2026-01-14,Srihitha Anamaneni,check,200.00Reading the Output
| Line | What happened |
|---|---|
| 1 | Starting state. Srihitha owes $450 plus a $6 late fee. Navika's balance is 44 days overdue, so her late fee hit the $30 cap. Advitha is still inside her grace period |
| 2 | Submitting the empty form showed all three errors at once, each next to its field |
| 3 | Srihitha's $200 check: the $6 fee was added to her balance and $200 subtracted, leaving $256 |
| 4 | Advitha's $45 ACH payment cleared her balance |
| 5 | Undo restored the state from before Advitha's payment, exactly, because old states are never changed |
| 6 to 7 | The CSV export lists only the payment that remains |
The list is always sorted by amount due, and the total is always the sum of the rows, because both are derived from state on every render.
In Practice
The finished app uses something from nearly every module of the course:
| Feature | Where you learned it |
|---|---|
Money as integer cents, Intl.NumberFormat | Numbers, Number Methods |
toCents regular expression | Regular Expressions |
| Date differences | Dates, Temporal |
Pure fee rules, { ok, errors } results | Functions, Error Handling |
| Reducer, undo, derived totals | Managing State |
localStorage with validation and a versioned key | Web Storage, JSON |
Form with aria-invalid and linked errors | Forms and Validation, Project: Form Validation |
createElement and textContent rendering | Creating Elements, JavaScript Security |
Tests with node:test | First Tests, Testing in Practice |
| Layers and wiring | Structuring a JavaScript Application |
Good next steps: split the page into the modules from "The Plan" with import and export; add TypeScript types for Student and Payment; replace localStorage with a small server API; and add the payments dashboard from the previous project as a second page.
Common Mistakes
Charging the late fee twice. The first version of this app recalculated the late fee from the due date after every payment, so the $6 already added to Srihitha's balance was added again: she appeared to owe $262 instead of $256. The browser check caught it. Tracking feesChargedCents and adding a test for it fixed the rule in one place, and every screen was correct again. Bugs in money rules are why the domain gets tested first.
Using floating-point dollars. 0.1 + 0.2 problems turn into wrong totals. Store cents; format only for display.
Reading new Date() inside the rules. Tests then depend on the day they run. Pass today in.
Trusting saved data. Old or edited localStorage data can have any shape. Validate it and fall back to a safe default.
Rules copied into the UI. If the form recalculates fees itself, the copies drift. The UI calls the domain functions; it never re-implements them.
Practice
Challenge: Add a sibling discount: when two or more students share a last name, each of them gets $10 taken off the late fee owed (never below zero). Write the pure function first:
Show solution
function siblingFeeDiscount(student, students, feeCents) {
const last = student.name.split(" ").at(-1);
const siblings = students.filter((s) => s.name.split(" ").at(-1) === last).length;
return siblings >= 2 ? Math.max(feeCents - 1000, 0) : feeCents;
}
const students = [{ name: "Srihitha Anamaneni" }, { name: "Advitha Anamaneni" }, { name: "Zoe Parker" }];
console.log(siblingFeeDiscount(students[0], students, 600), siblingFeeDiscount(students[0], students, 3000), siblingFeeDiscount(students[2], students, 3000));0 2000 3000Then add a test for it, and use it inside amountDue and applyPayment, so every screen shows the discounted amount without any UI changes.
Key Takeaways
| Layer | Fee Tracker code |
|---|---|
| Domain | toCents, formatUsd, lateFee, amountDue, applyPayment, parsePayment |
| State | reducer, undo stack |
| Data | loadState, saveState (key feeTracker.v1) |
| UI | Form submit, render, undo, export |
| Tests | node:test for the fee rules |
Was this tutorial helpful?