Most debt tools start after you owe. This one starts before you borrow. Enter your myUK bill, aid offer, job hours and cash on hand, and it forecasts your money week by week to the end of the semester, shows the week you'd run out, and finds the cheapest fix: unused subsidized loan room, a few more work hours, or the smallest unsubsidized loan, priced in dollars of interest per hour you'd otherwise work. Built on 2026–27 federal loan rates and fees, the new tiered repayment plan, KEES renewal
<!-- Copyright (c) 2026 Brian Dennis. Released under the MIT License. -->
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- No network: this policy blocks every outside request (scripts, styles, fonts, images, fetch). -->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; base-uri 'none'; form-action 'none'">
<title>Make It to May</title>
<!-- Tab icon: the teal mark, built into the page (a data address, so nothing is downloaded). -->
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 44 44'%3E%3Crect width='44' height='44' rx='11' fill='%230d7480'/%3E%3Cpath d='M9 17 L17 25 L24 20 L33 29' fill='none' stroke='white' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round'/%3E%3Ccircle cx='34' cy='13' r='3.5' fill='white'/%3E%3C/svg%3E">
<meta name="description" content="A week-by-week cash planner for independent University of Kentucky students: will your money last until the semester ends, and should you borrow, work more, or do nothing?">
<style>
/* Look (Nov 12, 2026): "Frost and slate" palette from tasteskill's fintech list (MIT, Leonxlnx; values only, no code
copied). Cool white ground, slate ink, one teal accent; green, red and amber are kept for status only.
Every text pair checked for WCAG AA contrast, light and dark. */
:root {
--bg: #f7f9fa; --surface: #ffffff; --surface-2: #eef2f4; --ink: #1f3038; --muted: #5d6b72; --line: #dbe2e6; --line-strong: #c3ced3;
--accent: #0d7480; --accent-hover: #0a5c66; --accent-soft: #e4f1f2; --on-accent: #ffffff;
--good: #1b6e40; --good-bg: #e3f2e9; --bad: #b42318; --bad-bg: #fdeceb;
--warn: #7a5200; --warn-bg: #fff3d6; --code-bg: #eef2f4; --dot-unsaved: #d97706; --field-bg: #ffffff;
--shadow-1: 0 1px 2px rgba(20, 40, 48, .06), 0 1px 3px rgba(20, 40, 48, .05);
--shadow-2: 0 10px 30px rgba(20, 40, 48, .10);
--r-sm: 6px; --r-md: 10px; --r-lg: 14px;
/* Motion: hover in 150ms, out 120ms, press 90ms; one UI ease, one settling ease for the entrance. */
--m-in: 150ms; --m-out: 120ms; --m-press: 90ms; --ease: cubic-bezier(.2, .8, .2, 1); --ease-enter: cubic-bezier(.22, 1, .36, 1);
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #0f1719; --surface: #172226; --surface-2: #1c2a2f; --ink: #e6edef; --muted: #9aabb1; --line: #27373e; --line-strong: #36494f;
--accent: #5cc0c9; --accent-hover: #84d3da; --accent-soft: #15333a; --on-accent: #0f1719;
--good: #82d4a3; --good-bg: #15301f; --bad: #ff9d93; --bad-bg: #3a1916;
--warn: #f1c36a; --warn-bg: #342910; --code-bg: #1f2c31; --dot-unsaved: #f5a623; --field-bg: #121b1e;
--shadow-1: 0 1px 2px rgba(0, 0, 0, .35); --shadow-2: 0 10px 30px rgba(0, 0, 0, .45);
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #0f1719; --surface: #172226; --surface-2: #1c2a2f; --ink: #e6edef; --muted: #9aabb1; --line: #27373e; --line-strong: #36494f;
--accent: #5cc0c9; --accent-hover: #84d3da; --accent-soft: #15333a; --on-accent: #0f1719;
--good: #82d4a3; --good-bg: #15301f; --bad: #ff9d93; --bad-bg: #3a1916;
--warn: #f1c36a; --warn-bg: #342910; --code-bg: #1f2c31; --dot-unsaved: #f5a623; --field-bg: #121b1e;
--shadow-1: 0 1px 2px rgba(0, 0, 0, .35); --shadow-2: 0 10px 30px rgba(0, 0, 0, .45);
color-scheme: dark;
}
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0; background: var(--bg); color: var(--ink);
font: 16px/1.55 system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility;
}
h1, h2, h3, h4 { text-wrap: balance; }
.wrap { max-width: 1080px; margin: 0 auto; padding: 0 24px; }
a { color: var(--accent); text-underline-offset: 2px; transition: text-decoration-thickness var(--m-out) var(--ease); }
a:hover { text-decoration-thickness: 2px; }
a:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; border-radius: 2px; }
/* Header: wordmark, who it's for, the disclaimer as a quiet strip (still always visible). */
header.site { background: var(--surface); border-bottom: 1px solid var(--line); padding: 28px 0 0; }
.brand { display: flex; align-items: center; gap: 14px; margin: 6px 0 10px; }
.brand-mark { width: 44px; height: 44px; flex: none; }
.brand-mark .bm-bg { fill: var(--accent); }
.brand-mark .bm-line { fill: none; stroke: var(--on-accent); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.brand-mark .bm-dot { fill: var(--on-accent); }
.eyebrow { margin: 0; font-size: 12.5px; font-weight: 600; letter-spacing: .08em; text-transform: uppercase; color: var(--muted); }
h1 { margin: 0; font-size: 38px; line-height: 1.1; letter-spacing: -.02em; font-weight: 800; }
h2 { font-size: 22px; line-height: 1.25; letter-spacing: -.01em; margin: 28px 0 8px; }
.who { margin: 0 0 18px; color: var(--ink); max-width: 820px; font-size: 17px; }
.note { margin: 0; padding: 12px 14px; border-radius: var(--r-md); background: var(--warn-bg); color: var(--ink); font-size: 14px; }
.note strong { color: var(--warn); }
header.site .note { display: flex; gap: 10px; align-items: flex-start; background: none; border-top: 1px solid var(--line);
border-radius: 0; padding: 12px 0 14px; color: var(--muted); }
header.site .note strong { color: var(--ink); }
.note-icon { width: 18px; height: 18px; flex: none; margin-top: 1px; }
.note-icon circle { fill: none; stroke: currentColor; stroke-width: 1.6; }
.note-icon path { fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; }
main { padding: 12px 0 40px; }
main:focus { outline: none; }
.skip-link { position: absolute; left: 12px; top: -80px; z-index: 50; font: inherit; font-weight: 650; padding: 10px 16px; border-radius: 9px;
border: 2px solid var(--accent); background: var(--surface); color: var(--accent); cursor: pointer; box-shadow: var(--shadow-2); }
.skip-link:focus { top: 12px; outline: 3px solid var(--accent); outline-offset: 2px; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-lg); padding: 22px 26px; margin: 18px 0;
box-shadow: var(--shadow-1); }
.card > h3.flush, .card > h2.flush { font-size: 21px; letter-spacing: -.01em; margin-bottom: 6px; }
.muted { color: var(--muted); }
.btn { font: inherit; font-weight: 650; padding: 9px 18px; min-height: 42px; border-radius: 9px; border: 1px solid var(--accent);
background: var(--accent); color: var(--on-accent); cursor: pointer; line-height: 1.3;
transition: background-color var(--m-out) var(--ease), border-color var(--m-out) var(--ease), color var(--m-out) var(--ease),
box-shadow var(--m-out) var(--ease), transform var(--m-press) var(--ease); }
.btn:hover { background: var(--accent-hover); border-color: var(--accent-hover); box-shadow: var(--shadow-1);
transition-duration: var(--m-in); }
.btn:active { transform: translateY(1px) scale(.985); box-shadow: none; }
.btn.secondary { background: var(--surface); color: var(--accent); border-color: color-mix(in srgb, var(--accent) 50%, var(--line)); }
.btn.secondary:hover { background: var(--accent-soft); border-color: var(--accent); color: var(--accent); }
.btn.back { margin-top: 16px; }
.linkish { font: inherit; background: none; border: 0; color: var(--accent); text-decoration: underline; text-underline-offset: 3px;
text-decoration-thickness: 1px; cursor: pointer; padding: 8px 6px; border-radius: 4px;
transition: text-decoration-thickness var(--m-out) var(--ease), color var(--m-out) var(--ease); }
.linkish:hover { text-decoration-thickness: 2px; color: var(--accent-hover); }
.linkish:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.small { font-size: 14px; }
.btn:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
code { background: var(--code-bg); padding: 1px 5px; border-radius: 4px; font-size: .92em; }
footer { border-top: 1px solid var(--line); background: var(--surface); padding: 22px 0 32px; font-size: 14px; color: var(--muted); }
footer p { margin: 6px 0; max-width: 860px; }
footer strong { color: var(--ink); }
/* Test mode */
.banner { padding: 12px 14px; border-radius: var(--r-md); font-weight: 600; margin: 16px 0; }
.banner.pass { background: var(--good-bg); color: var(--good); }
.banner.fail { background: var(--bad-bg); color: var(--bad); }
details.case { background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-md); margin: 8px 0; }
details.case > summary { cursor: pointer; padding: 10px 12px; display: flex; gap: 8px; align-items: baseline; flex-wrap: wrap; }
details.case > summary .count { margin-left: auto; font-size: 14px; }
.tbl { overflow-x: auto; padding: 0 12px 12px; }
table { border-collapse: collapse; width: 100%; min-width: 560px; font-size: 14px; font-variant-numeric: tabular-nums; }
th, td { text-align: left; padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; }
th { color: var(--muted); font-weight: 600; white-space: nowrap; }
thead th { font-size: 13px; border-bottom-color: var(--line-strong); }
td.path { font-family: ui-monospace, Consolas, monospace; font-size: 13px; white-space: nowrap; }
.chip { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; font-weight: 700; }
.chip.pass { background: var(--good-bg); color: var(--good); }
.chip.fail { background: var(--bad-bg); color: var(--bad); }
.legend { font-size: 14px; }
/* Form fields */
.fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 16px 24px; }
.field.wide { grid-column: 1 / -1; }
.field > label, .field > .label { display: block; font-size: 14px; font-weight: 600; margin-bottom: 4px; }
.field input, .field select, .awards input, .awards select, table.rates-table input {
width: 100%; font: inherit; padding: 7px 10px; min-height: 40px; border: 1px solid var(--line-strong); border-radius: var(--r-sm);
background: var(--field-bg); color: var(--ink); font-variant-numeric: tabular-nums;
transition: border-color var(--m-out) var(--ease), box-shadow var(--m-out) var(--ease); }
.field input:hover, .field select:hover, .awards input:hover, .awards select:hover, table.rates-table input:hover { border-color: var(--muted); }
.field input:focus-visible, .field select:focus-visible, .awards input:focus-visible, .awards select:focus-visible,
table.rates-table input:focus-visible, dialog textarea:focus-visible {
outline: 2px solid var(--accent); outline-offset: 0; border-color: var(--accent); box-shadow: 0 0 0 4px var(--accent-soft); }
.field input[type="checkbox"], .awards input[type="checkbox"] { width: 18px; height: 18px; min-height: 0; accent-color: var(--accent); }
.field [aria-invalid="true"], .awards [aria-invalid="true"] { border-color: var(--bad); outline: 1px solid var(--bad); }
.err { color: var(--bad); font-size: 13px; margin: 4px 0 0; }
.datelist { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; }
.datelist .item { display: flex; gap: 2px; align-items: center; }
.datelist input { width: auto; }
.awards { overflow-x: auto; margin-top: 16px; }
.awards table { min-width: 720px; }
.awards th { white-space: normal; vertical-align: bottom; }
.awards input[type="number"] { min-width: 70px; }
.awards td { padding: 4px; vertical-align: middle; }
.awards th { font-size: 13px; }
/* Save bar: always visible, with the unsaved dot */
.filebar { position: sticky; bottom: 0; z-index: 5; background: color-mix(in srgb, var(--surface) 90%, transparent);
-webkit-backdrop-filter: saturate(1.4) blur(10px); backdrop-filter: saturate(1.4) blur(10px);
border-top: 1px solid var(--line); box-shadow: 0 -6px 24px rgba(20, 40, 48, .08); }
.filebar-inner { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; padding-top: 10px; padding-bottom: 10px; }
.status { margin: 0; display: flex; align-items: center; gap: 8px; font-weight: 600; }
.status .dot { width: 12px; height: 12px; border-radius: 50%; background: var(--good); flex: none; }
.status.unsaved .dot { background: var(--dot-unsaved); box-shadow: 0 0 0 3px color-mix(in srgb, var(--dot-unsaved) 25%, transparent); }
.file-actions { margin-left: auto; display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
.status-short, .lbl-short, .more-menu { display: none; }
.more-menu { position: relative; }
.more-menu > summary { list-style: none; display: inline-flex; align-items: center; }
.more-menu > summary::-webkit-details-marker { display: none; }
.more-menu .menu { position: absolute; right: 0; bottom: calc(100% + 8px); min-width: 170px; z-index: 30; display: grid; padding: 6px;
background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-md); box-shadow: var(--shadow-2); }
.more-menu .menu button { font: inherit; text-align: left; padding: 10px 12px; min-height: 44px; border: 0; border-radius: var(--r-sm);
background: none; color: var(--ink); cursor: pointer; transition: background-color var(--m-out) var(--ease); }
.more-menu .menu button:hover { background: var(--accent-soft); color: var(--accent); }
.more-menu .menu button:focus-visible { outline: 3px solid var(--accent); outline-offset: -3px; }
/* Narrow windows: one row. The dot and one word show; screen readers still hear the full status sentence. */
@media (max-width: 900px) {
.filebar .filebar-inner { flex-wrap: nowrap; gap: 10px; padding-top: 8px; padding-bottom: 8px; }
.status { min-width: 0; font-size: 15px; }
#status-text { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.status-short { display: inline; white-space: nowrap; }
.file-actions { flex-wrap: nowrap; gap: 6px; }
.file-actions .btn { padding: 8px 14px; }
#copy-btn, #paste-btn { display: none; }
.more-menu { display: block; }
}
@media (max-width: 480px) {
.lbl-long { display: none; }
.lbl-short { display: inline; }
}
.filemsg { margin: 0 0 10px; padding: 10px 12px; border-radius: 8px; font-size: 14px; display: flex; gap: 12px; align-items: flex-start; }
.filemsg[hidden] { display: none; }
.filemsg.error { background: var(--bad-bg); border: 1px solid var(--bad); }
.filemsg.ok { background: var(--good-bg); }
.filemsg .msg-body { flex: 1; }
.filemsg ul { margin: 6px 0 0; padding-left: 20px; }
dialog { border: 1px solid var(--line); border-radius: var(--r-lg); background: var(--surface); color: var(--ink); width: min(640px, calc(100% - 48px));
padding: 22px 26px; box-shadow: var(--shadow-2); }
dialog::backdrop { background: rgba(10, 22, 26, .5); -webkit-backdrop-filter: blur(2px); backdrop-filter: blur(2px); }
dialog h2 { margin-top: 0; }
dialog textarea { width: 100%; font: 13px/1.4 ui-monospace, Consolas, monospace; padding: 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--field-bg); color: var(--ink); }
.dialog-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 12px; }
/* Sample picker */
.sample-list { display: grid; gap: 8px; margin: 14px 0 4px; max-height: min(62vh, 560px); overflow-y: auto; padding: 3px; }
.sample-pick { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; align-items: center; text-align: left; width: 100%;
font: inherit; color: var(--ink); background: var(--surface); border: 1px solid var(--line); border-radius: var(--r-md);
padding: 12px 14px; cursor: pointer;
transition: border-color var(--m-out) var(--ease), background-color var(--m-out) var(--ease), transform var(--m-press) var(--ease); }
.sample-pick:hover { border-color: var(--accent); background: var(--accent-soft); transition-duration: var(--m-in); }
.sample-pick:active { transform: scale(.99); }
.sample-pick:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.sample-pick[aria-current="true"] { border-color: var(--accent); box-shadow: inset 3px 0 0 var(--accent); }
.sample-pick .sp-name { font-weight: 700; font-size: 16px; }
.sample-pick .chip { justify-self: end; text-align: right; }
.sample-pick .sp-desc { grid-column: 1 / -1; font-size: 14px; color: var(--muted); }
.chip.fix { background: var(--accent-soft); color: var(--accent); }
.dialog-msg { min-height: 1.5em; font-size: 14px; margin: 8px 0 0; }
.dialog-msg.error { color: var(--bad); }
.warn-line { background: var(--warn-bg); padding: 6px 10px; border-radius: 6px; font-size: 14px; }
/* Welcome, guided steps, summary, editor, tips */
.flush { margin-top: 0; }
.linkish.inline { padding: 0; }
.welcome { padding: 36px 40px; display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, 1fr); gap: 32px; align-items: center; }
.welcome h2 { font-size: 32px; line-height: 1.15; letter-spacing: -.02em; margin: 0 0 12px; }
.welcome p { max-width: 620px; font-size: 17px; }
.welcome p.small { font-size: 14px; }
.welcome-art { width: 100%; height: auto; display: block; }
.welcome-art .wa-panel { fill: var(--surface-2); }
.welcome-art .wa-grid { stroke: var(--line); stroke-width: 1; }
.welcome-art .wa-cushion { stroke: var(--muted); stroke-width: 1.5; stroke-dasharray: 5 4; }
.welcome-art .wa-below { fill: var(--bad); opacity: .07; }
.welcome-art .wa-s1 { fill: none; stroke: var(--series-1); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.welcome-art .wa-s2 { fill: none; stroke: var(--series-2); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.welcome-art .wa-dot { fill: var(--series-2); stroke: var(--surface-2); stroke-width: 2; }
.welcome-art .wa-end { fill: var(--series-1); stroke: var(--surface-2); stroke-width: 2; }
.welcome-art .wa-text { font: 600 12px system-ui, -apple-system, "Segoe UI", sans-serif; fill: var(--muted); }
@media (max-width: 760px) { .welcome { grid-template-columns: 1fr; padding: 26px 22px; } .welcome-art { max-width: 420px; } }
.choice-row { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; margin: 22px 0 12px; }
.btn.big { padding: 12px 24px; font-size: 17px; min-height: 48px; }
.btn.small-btn { padding: 4px 12px; font-size: 14px; min-height: 34px; }
.quick-add { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 14px 0 4px; }
.quick-add .quick-label { font-size: 14px; font-weight: 600; margin-right: 2px; }
.title-row { display: flex; align-items: baseline; gap: 16px; flex-wrap: wrap; }
.title-row h2 { margin-bottom: 0; }
.steps { list-style: none; display: flex; gap: 8px; padding: 0; margin: 14px 0 18px; flex-wrap: wrap; }
.steps button { font: inherit; font-size: 15px; font-weight: 600; border: 1px solid var(--line-strong); background: var(--surface); color: var(--ink);
border-radius: 999px; padding: 6px 16px 6px 7px; min-height: 40px; cursor: pointer; display: flex; align-items: center; gap: 8px;
transition: background-color var(--m-out) var(--ease), border-color var(--m-out) var(--ease), transform var(--m-press) var(--ease); }
.steps button:hover { border-color: var(--accent); background: var(--accent-soft); transition-duration: var(--m-in); }
.steps button:active { transform: scale(.98); }
.steps .num { display: inline-grid; place-items: center; width: 26px; height: 26px; border-radius: 50%; background: var(--surface-2); font-weight: 700; font-size: 13px; }
.steps button[aria-current="step"] { border-color: var(--accent); background: var(--accent); color: var(--on-accent); }
.steps button[aria-current="step"] .num { background: var(--on-accent); color: var(--accent); }
.steps button:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.wizard-grid { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 24px; align-items: start; }
.wizard-grid > .card { margin: 0; }
@media (max-width: 920px) { .wizard-grid { grid-template-columns: minmax(0, 1fr); } }
.step-title { margin: 0 0 4px; font-size: 19px; }
.step-intro { margin: 0 0 12px; }
.step-section { border-top: 1px solid var(--line); padding: 14px 0 6px; margin-top: 12px; }
.step-section h4 { margin: 0 0 12px; font-size: 16px; display: flex; align-items: center; gap: 6px; }
.step-section.collapsible > summary { cursor: pointer; padding: 2px 0 10px; }
.step-actions { display: flex; justify-content: space-between; gap: 12px; margin-top: 20px; }
.step-actions .btn:last-child { margin-left: auto; }
.label-row { display: flex; align-items: center; gap: 6px; margin-bottom: 4px; }
.label-row label, .label-row .label { font-size: 14px; font-weight: 600; }
.hint { font-size: 13px; color: var(--muted); margin: 4px 0 0; }
.datelist input.short { width: 90px; }
.terms { display: flex; flex-wrap: wrap; gap: 6px 14px; align-items: center; margin: 0 0 8px; }
.term { display: inline-flex; align-items: center; gap: 4px; }
.tip-wrap { position: relative; display: inline-flex; }
.tip { width: 24px; height: 24px; border-radius: 50%; border: 1px solid color-mix(in srgb, var(--accent) 60%, var(--line)); background: var(--surface);
color: var(--accent); font: 700 13px/1 system-ui, sans-serif; cursor: help; padding: 0; flex: none;
transition: background-color var(--m-out) var(--ease), border-color var(--m-out) var(--ease); }
.tip:hover { background: var(--accent-soft); border-color: var(--accent); transition-duration: var(--m-in); }
.tip:focus-visible { outline: 3px solid var(--accent); outline-offset: 1px; }
/* Fixed, and placed by placeTip() under (or above) its "?" so a scrolling table or the window edge never cuts it off. */
.tip-pop { display: none; position: fixed; left: 8px; top: 0; width: 280px; max-width: calc(100vw - 16px); z-index: 20;
background: var(--ink); color: var(--bg); padding: 11px 13px; border-radius: var(--r-md); font-size: 13px; font-weight: 400;
line-height: 1.5; text-align: left; box-shadow: var(--shadow-2); }
.tip-wrap:hover .tip-pop, .tip-wrap:focus-within .tip-pop, .tip-wrap.open .tip-pop { display: block; }
.summary { position: sticky; top: 16px; }
.summary h3 { margin: 0 0 10px; font-size: 16px; }
.summary h4 { margin: 14px 0 6px; font-size: 14px; }
.summary dl { margin: 0; display: grid; grid-template-columns: 1fr auto; gap: 6px 12px; font-size: 14px; }
.summary dt { color: var(--muted); display: flex; align-items: center; gap: 4px; }
.summary dd { margin: 0; text-align: right; font-weight: 600; font-variant-numeric: tabular-nums; }
.summary .total { border-top: 1px solid var(--line); padding-top: 6px; color: var(--ink); }
/* The edit loop: the editor sits under the answer; while it's open, a panel beside the form keeps the answer in view
(a strip pinned to the top of the editor in narrow windows). */
.edit-grid { display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 28px; align-items: start; }
.live-panel { max-height: calc(100vh - 120px); overflow-y: auto; padding: 16px 16px 18px; border-radius: var(--r-md);
background: var(--surface-2); border: 1px solid var(--line); }
.live-head { margin: 0 0 8px; font-size: 12.5px; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; color: var(--muted); }
.live-answer { margin: 0 0 16px; }
.live-answer .stats { grid-template-columns: 1fr; gap: 8px; margin: 0; }
.live-answer .stat { padding: 10px 12px 11px; }
.live-answer .stat-label { font-size: 11.5px; margin-bottom: 2px; }
.live-answer .stat-figure { font-size: 22px; }
.live-answer .stat-figure.words { font-size: 17px; }
.live-answer .stat-sub { font-size: 13px; margin-top: 2px; }
.live-panel .summary-slot { border-top: 1px solid var(--line); padding-top: 14px; }
.live-strip { display: none; }
@keyframes glow { from { box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 55%, transparent); } to { box-shadow: 0 0 0 0 transparent; } }
.live-answer.flash .stat, .live-strip.flash { animation: glow 900ms var(--ease) both; }
.edit-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; margin: 22px 0 0; padding-top: 16px; border-top: 1px solid var(--line); }
@media (max-width: 920px) {
.edit-grid { grid-template-columns: minmax(0, 1fr); }
.live-panel { position: static; max-height: none; overflow: visible; }
.live-panel .live-answer, .live-panel .live-head { display: none; }
.live-panel .summary-slot { border-top: 0; padding-top: 0; }
.live-strip { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 14px; position: sticky; top: 0; z-index: 4;
margin: 0 0 12px; padding: 9px 12px; border-radius: var(--r-sm); background: color-mix(in srgb, var(--surface) 94%, transparent);
-webkit-backdrop-filter: blur(8px); backdrop-filter: blur(8px); border: 1px solid var(--line); box-shadow: var(--shadow-1); font-size: 14px; }
.live-strip .strip-head { color: var(--muted); font-weight: 600; }
.live-strip .strip-item { display: inline-flex; align-items: center; gap: 5px; }
.live-strip .strip-item.bad { color: var(--bad); }
.live-strip .strip-item.good { color: var(--good); }
.live-strip .strip-item.fix { color: var(--accent); }
.live-strip .strip-item strong { color: var(--ink); font-variant-numeric: tabular-nums; }
}
table.mini { min-width: 0; width: 100%; font-size: 14px; }
table.mini td { padding: 3px 0; border-bottom: 1px dashed var(--line); }
table.mini td.num { text-align: right; font-variant-numeric: tabular-nums; }
.missing { background: var(--warn-bg); border-radius: 8px; padding: 8px 12px; margin-top: 12px; font-size: 14px; }
.missing ul { margin: 4px 0 0; padding-left: 20px; }
.ready { color: var(--good); font-weight: 600; font-size: 14px; margin: 12px 0 0; }
.warnings { margin: 10px 0 0; padding-left: 20px; font-size: 14px; color: var(--warn); }
.notes { margin: 8px 0 0; padding-left: 20px; }
.drawer > summary { cursor: pointer; font-weight: 700; font-size: 18px; border-radius: 6px;
transition: color var(--m-out) var(--ease); }
.drawer > summary:hover { color: var(--accent); }
.drawer > summary .drawer-hint { font-weight: 400; font-size: 14px; color: var(--muted); margin-left: 8px; }
.drawer > summary:focus-visible, details > summary:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
.drawer[open] > summary { margin-bottom: 4px; }
.sample-note { margin: 18px 0 0; background: var(--accent-soft); border: 1px solid color-mix(in srgb, var(--accent) 22%, transparent); }
.note.sample-note strong { color: var(--accent); }
/* Results. Chart colors: a teal line for the plan (the accent's hue) and the reference orange for "if nothing
changes". Checked with the data-viz palette validator on the new chart surfaces (Nov 12, 2026): light #008c99/#eb6834
on #ffffff, CVD ΔE 13.6, normal 28.6; dark #1fa8b4/#d95926 on #172226, CVD ΔE 17.6, normal 28.3; all ≥ 3:1. */
:root { --series-1: #008c99; --series-2: #eb6834; --chart-grid: #e6ebee; --chart-axis: #c3ced3; --chart-shade: rgba(31,48,56,.05); --chart-below: rgba(180,35,24,.05); }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) { --series-1: #1fa8b4; --series-2: #d95926; --chart-grid: #233238; --chart-axis: #3a4d54; --chart-shade: rgba(255,255,255,.04); --chart-below: rgba(255,157,147,.06); }
}
:root[data-theme="dark"] { --series-1: #1fa8b4; --series-2: #d95926; --chart-grid: #233238; --chart-axis: #3a4d54; --chart-shade: rgba(255,255,255,.04); --chart-below: rgba(255,157,147,.06); }
.answer { position: relative; overflow: hidden; padding: 26px 30px 24px; }
.answer::before { content: ""; position: absolute; inset: 0 0 auto 0; height: 4px; background: var(--accent); }
.answer.is-short::before { background: var(--bad); }
.answer.is-covered::before { background: var(--good); }
.answer .eyebrow { margin-bottom: 14px; }
/* The answer at a glance: the problem and the fix as two big numbers (the headline sentence below says it in full). */
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 14px; margin: 0 0 18px; }
.stat { border-radius: var(--r-md); padding: 14px 18px 16px; background: var(--surface-2); border: 1px solid var(--line); }
.stat.good { background: var(--good-bg); border-color: color-mix(in srgb, var(--good) 25%, transparent); }
.stat.bad { background: var(--bad-bg); border-color: color-mix(in srgb, var(--bad) 22%, transparent); }
.stat.fix { background: var(--accent-soft); border-color: color-mix(in srgb, var(--accent) 28%, transparent); }
.stat-label { display: flex; align-items: center; gap: 6px; margin: 0 0 6px; font-size: 12.5px; font-weight: 700; letter-spacing: .06em; text-transform: uppercase; }
.stat.good .stat-label { color: var(--good); }
.stat.bad .stat-label { color: var(--bad); }
.stat.fix .stat-label { color: var(--accent); }
.stat-icon { width: 16px; height: 16px; flex: none; }
.stat-icon * { fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.stat-figure { margin: 0; font-size: 34px; line-height: 1.1; font-weight: 800; letter-spacing: -.02em; font-variant-numeric: tabular-nums; color: var(--ink); }
.stat-figure.words { font-size: 26px; line-height: 1.2; }
.stat-sub { margin: 6px 0 0; font-size: 14px; color: var(--muted); }
.headline { font-size: 20px; line-height: 1.45; font-weight: 650; margin: 0 0 10px; max-width: 900px; letter-spacing: -.005em; }
.tradeoff { font-size: 17px; margin: 0 0 10px; max-width: 900px; }
.follow { margin: 0 0 10px; padding-left: 20px; font-size: 15px; }
.follow li { margin: 4px 0; }
/* The answer enters once, the first time results appear (tasteskill: one entrance; nothing moves on scroll). */
@keyframes rise { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
.enter .stat, .enter .headline, .enter .tradeoff, .welcome.enter > * { animation: rise 520ms var(--ease-enter) both; }
.enter .stat:nth-child(2) { animation-delay: 70ms; }
.enter .headline { animation-delay: 140ms; }
.enter .tradeoff { animation-delay: 200ms; }
.welcome.enter > :nth-child(2) { animation-delay: 120ms; }
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { animation: none !important; transition-duration: 1ms !important; }
}
.chart-legend { display: flex; flex-wrap: wrap; gap: 6px 18px; font-size: 14px; color: var(--muted); margin: 10px 0 8px; }
.chart-legend .lg { display: inline-flex; align-items: center; gap: 6px; }
.key { display: inline-block; width: 18px; height: 0; border-top: 2px solid; flex: none; }
.key.s1 { border-color: var(--series-1); }
.key.s2 { border-color: var(--series-2); }
.key.dashed { border-top: 2px dashed var(--muted); }
.key.box { height: 12px; border: 0; background: var(--chart-shade); outline: 1px solid var(--chart-axis); }
.key.below { height: 12px; border: 0; background: var(--chart-below); outline: 1px solid color-mix(in srgb, var(--bad) 35%, transparent); }
.chart-box { position: relative; }
.cash-chart { width: 100%; height: auto; display: block; overflow: visible; }
.cash-chart:focus { outline: none; }
.cash-chart:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; border-radius: 6px; }
.cash-chart .grid { stroke: var(--chart-grid); stroke-width: 1; }
.cash-chart .zero { stroke: var(--chart-axis); stroke-width: 1.5; }
.cash-chart .tick { stroke: var(--chart-axis); }
.cash-chart .axis-text, .cash-chart .note-text, .cash-chart .event-text, .cash-chart .end-text, .cash-chart .mark-text {
font: 12px system-ui, -apple-system, "Segoe UI", sans-serif; fill: var(--muted); font-variant-numeric: tabular-nums; }
.cash-chart .end-text, .cash-chart .mark-text { fill: var(--ink); font-weight: 600; }
.cash-chart .cushion { stroke: var(--muted); stroke-width: 1.5; stroke-dasharray: 5 4; }
.cash-chart .shade { fill: var(--chart-shade); }
.cash-chart .below { fill: var(--chart-below); }
.cash-chart .shade.light { opacity: .6; }
.cash-chart .event { stroke: var(--chart-axis); stroke-width: 1; }
.cash-chart .line { fill: none; stroke-width: 2.5; stroke-linejoin: round; stroke-linecap: round; }
.cash-chart .line.s1 { stroke: var(--series-1); }
.cash-chart .line.s2 { stroke: var(--series-2); }
.cash-chart .dot { stroke: var(--surface); stroke-width: 2; }
.cash-chart .dot.s1 { fill: var(--series-1); }
.cash-chart .dot.s2 { fill: var(--series-2); }
.cash-chart .cross { stroke: var(--muted); stroke-width: 1; }
.cash-chart .hit { fill: transparent; cursor: crosshair; }
.chart-tip { position: absolute; z-index: 15; width: 260px; background: var(--surface); color: var(--ink); border: 1px solid var(--line);
border-radius: var(--r-md); box-shadow: var(--shadow-2); padding: 11px 13px; font-size: 13px; pointer-events: none; }
.chart-tip .tip-head { font-weight: 600; margin-bottom: 6px; }
.chart-tip .tip-row { display: flex; align-items: center; gap: 8px; margin: 2px 0; }
.chart-tip .tip-row strong { font-size: 15px; font-variant-numeric: tabular-nums; }
.chart-tip .tip-note { color: var(--muted); margin-top: 3px; }
.chart-table { margin-top: 10px; }
.chart-table > summary, .rates > summary { cursor: pointer; color: var(--accent); font-weight: 600; padding: 6px 0; width: fit-content; }
.chart-table > summary:hover, .rates > summary:hover { color: var(--accent-hover); text-decoration: underline; text-underline-offset: 3px; }
.options { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; margin-top: 14px; }
.options.two { grid-template-columns: repeat(2, minmax(0, 1fr)); }
@media (max-width: 860px) { .options, .options.two { grid-template-columns: minmax(0, 1fr); } }
.option .why-note { margin: 12px 0 0; padding-top: 10px; border-top: 1px dashed var(--line-strong); font-size: 13.5px; color: var(--muted); }
/* Explore: cards are picked to show on the chart; the picked one has the teal border and "On the chart". */
.options .option { cursor: pointer; transition: border-color var(--m-out) var(--ease), box-shadow var(--m-out) var(--ease), transform var(--m-out) var(--ease); }
.options .option:hover { border-color: var(--accent); box-shadow: var(--shadow-1); transform: translateY(-2px); transition-duration: var(--m-in); }
.options .option:active { transform: translateY(0); transition-duration: var(--m-press); }
.options .option:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
.on-chart { display: none; align-items: center; gap: 6px; margin: 10px 0 0; font-size: 12.5px; font-weight: 700; color: var(--accent); }
.option[aria-checked="true"] .on-chart, .mix.is-on .on-chart { display: inline-flex; }
.mix .on-chart { margin: 0; }
.on-chart-icon { width: 16px; height: 16px; flex: none; }
.on-chart-icon * { fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.pick-hint { margin: 0 0 4px; }
.pick-readout { margin: 12px 0 0; font-size: 15px; }
.pick-readout:empty { display: none; }
.chart-card .pick-readout { margin: 4px 0 0; }
.pick-jump { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; margin: 12px 0 0; font-size: 14px; color: var(--muted); }
.pick-jump .on-chart-icon { color: var(--accent); }
.pick-jump:empty { display: none; }
.mix { margin-top: 16px; padding: 16px 18px; border: 1px solid var(--line); border-radius: var(--r-md); background: var(--surface-2);
transition: border-color var(--m-out) var(--ease); }
.mix.is-on { border: 2px solid var(--accent); background: var(--surface); padding: 15px 17px; box-shadow: var(--shadow-1); }
.mix-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; flex-wrap: wrap; }
.mix-head h4 { margin: 0; font-size: 16px; }
.mix-intro { margin: 4px 0 6px; }
.mix-row { display: grid; grid-template-columns: 170px minmax(0, 1fr) 230px; align-items: center; gap: 6px 16px; margin: 10px 0; }
.mix-row label { font-weight: 600; font-size: 14px; }
.mix-row input[type="range"] { width: 100%; height: 28px; margin: 0; accent-color: var(--accent); cursor: pointer; }
.mix-row input[type="range"]:disabled { cursor: not-allowed; opacity: .5; }
.mix-row input[type="range"]:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; border-radius: 6px; }
.mix-value { font-weight: 700; font-variant-numeric: tabular-nums; }
.mix .chips { margin: 4px 0 0; }
.mix-cost { margin: 8px 0 0; color: var(--muted); }
@media (max-width: 700px) {
.mix-row { grid-template-columns: minmax(0, 1fr) auto; }
.mix-row input[type="range"] { grid-column: 1 / -1; grid-row: 2; }
}
.chart-card.flash { animation: glow 900ms var(--ease) both; }
/* After graduation: the tint follows the picked card (Work more = "Borrow nothing extra"; otherwise "This plan"). */
table.compare[data-pick="nothing_extra"] .this { background: none; }
table.compare[data-pick="nothing_extra"] thead th.this { box-shadow: none; }
table.compare[data-pick="nothing_extra"] .col-nothing_extra { background: var(--accent-soft); }
table.compare[data-pick="nothing_extra"] thead th.col-nothing_extra { box-shadow: inset 0 3px 0 var(--accent); border-radius: 8px 8px 0 0; }
.covered-line { margin: 10px 0 6px; padding: 12px 16px; border-radius: var(--r-md); background: var(--good-bg); color: var(--ink); font-weight: 600; }
.option { border: 1px solid var(--line); border-radius: var(--r-md); padding: 16px 18px; background: var(--surface-2); }
.option[aria-checked="true"] { position: relative; border: 2px solid var(--accent); background: var(--surface); box-shadow: var(--shadow-1); padding: 15px 17px; }
.option[aria-checked="true"]::before { content: ""; position: absolute; inset: -2px -2px auto -2px; height: 5px; background: var(--accent); border-radius: var(--r-md) var(--r-md) 0 0; }
.option h4 { margin: 0 0 8px; font-size: 12.5px; color: var(--muted); text-transform: uppercase; letter-spacing: .07em; display: flex; justify-content: space-between; align-items: center; gap: 8px; }
.option .badge { text-transform: none; letter-spacing: 0; background: var(--accent); color: var(--on-accent); border-radius: 999px; padding: 2px 9px; font-size: 12px; }
.option .big { font-size: 26px; line-height: 1.15; font-weight: 800; letter-spacing: -.015em; margin: 0 0 6px; font-variant-numeric: tabular-nums; }
.option .sub { margin: 0 0 8px; color: var(--muted); font-size: 14px; }
.option .small { margin: 4px 0; }
.option dl.costs { margin: 8px 0 0; font-size: 14px; }
.option dl.costs dt { color: var(--muted); }
.option dl.costs dd { margin: 0 0 6px; font-weight: 600; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 8px 0 0; }
.chip.warn { background: var(--warn-bg); color: var(--warn); }
.value-line { font-weight: 600; margin: 16px 0 6px; }
/* Aid you're protecting */
.aid-total { font-size: 17px; margin: 0 0 12px; }
.flush-tbl { padding: 0; }
table.aid-table, table.ladder { min-width: 0; }
table.aid-table td.num, table.aid-table th:nth-child(2) { text-align: right; white-space: nowrap; }
table.aid-table td.strong { font-weight: 700; }
.kees, .under12 { border-top: 1px solid var(--line); margin-top: 16px; padding-top: 12px; }
.kees h4, .under12 h4 { margin: 0 0 8px; font-size: 16px; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.kees-status { font-weight: 600; margin: 0 0 6px; }
table.ladder tr.you td { background: var(--good-bg); font-weight: 600; }
table.ladder td:last-child { white-space: nowrap; }
/* After graduation */
table.compare { min-width: 640px; }
table.compare thead th { vertical-align: bottom; }
table.compare th[scope="row"] { color: var(--muted); font-weight: 400; white-space: normal; display: table-cell; }
table.compare td { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; }
table.compare thead th:not(:first-child) { text-align: right; }
table.compare .plan-name { display: block; color: var(--ink); font-weight: 700; font-size: 15px; }
table.compare .plan-sub { display: block; font-weight: 400; font-size: 13px; white-space: normal; }
table.compare .this { background: var(--accent-soft); }
table.compare thead th.this { box-shadow: inset 0 3px 0 var(--accent); border-radius: 8px 8px 0 0; }
table.compare tr.strong td, table.compare tr.strong th[scope="row"] { border-top: 1px solid var(--line-strong); }
table.compare tr.strong td { font-weight: 700; }
table.compare tr.strong th[scope="row"] { color: var(--ink); }
table.compare .plan-flag { display: inline-block; margin-top: 4px; padding: 1px 8px; border-radius: 999px; font-size: 12px; font-weight: 700;
color: var(--bad); background: var(--bad-bg); }
table.compare td.is-short { color: var(--muted); }
table.compare tr.short-row td.has-short { color: var(--bad); }
@media (max-width: 600px) {
.wrap { padding: 0 16px; }
h1 { font-size: 30px; }
.brand-mark { width: 38px; height: 38px; }
.who { font-size: 16px; }
.card { padding: 18px 16px; }
.answer { padding: 22px 16px 18px; }
.stat-figure { font-size: 30px; }
.headline { font-size: 18px; }
.welcome h2 { font-size: 26px; }
}
.verdict { font-weight: 600; margin: 16px 0 8px; max-width: 900px; padding: 12px 16px; border-radius: var(--r-md);
background: var(--surface-2); border-left: 3px solid var(--accent); }
.rates { margin-top: 12px; }
table.rates-table { min-width: 0; }
table.rates-table input { width: 110px; min-height: 36px; padding: 4px 8px; }
/* How this works, accessibility, print */
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.headline:focus { outline: none; }
.headline:focus-visible { outline: 3px solid var(--accent); outline-offset: 4px; border-radius: 4px; }
.answer-actions { margin: 10px 0 0; }
.how h3 { font-size: 17px; margin: 22px 0 8px; }
/* Closed-by-default sections ("fold"): the title and a note on what's inside always show. */
.fold { border-top: 1px solid var(--line); margin-top: 14px; }
.fold > summary { cursor: pointer; padding: 12px 0 10px; border-radius: 6px; }
.fold > summary::marker { color: var(--accent); }
.fold > summary > .fold-title { display: inline; margin: 0; font-size: 16px; font-weight: 700; letter-spacing: 0;
transition: color var(--m-out) var(--ease); }
.fold > summary:hover > .fold-title { color: var(--accent); }
.fold > summary > .fold-note { margin-left: 10px; font-size: 14px; font-weight: 400; color: var(--muted); }
.fold[open] > summary { margin-bottom: 2px; }
.fold-body { padding-bottom: 6px; }
.fold-body > :first-child { margin-top: 0; }
.under12 > .fold { border-top: 0; margin-top: -6px; }
.kees .fold { margin-top: 10px; }
.how-steps { padding-left: 22px; max-width: 900px; }
.how-steps li { margin: 8px 0; }
table.sources { min-width: 640px; }
table.sources td { font-size: 14px; }
table.sources .url { font: 12px ui-monospace, Consolas, monospace; word-break: break-all; }
.nowrap { white-space: nowrap; }
@media (forced-colors: active) {
.cash-chart .line.s2, .key.s2 { stroke-dasharray: 8 5; border-top-style: dashed; }
.cash-chart .cushion, .key.dashed { stroke-dasharray: 2 4; border-top-style: dotted; }
.chip, .option[aria-checked="true"], .stat, .mix.is-on { border: 1px solid CanvasText; }
.answer::before, .option[aria-checked="true"]::before { background: CanvasText; }
.brand-mark .bm-bg { fill: CanvasText; }
.brand-mark .bm-line { stroke: Canvas; }
.brand-mark .bm-dot { fill: Canvas; }
}
@media print {
.filebar, dialog, .drawer, .answer-actions, .chart-table, .rates, header.site .note, #tests, .tip, .btn, .linkish { display: none !important; }
body { background: #fff; color: #000; }
.card { break-inside: avoid; border-color: #999; box-shadow: none; }
.welcome-art { display: none; }
.cash-chart .line.s2 { stroke-dasharray: 8 5; }
.key.s2 { border-top-style: dashed; }
footer { border: 0; }
}
</style>
</head>
<body>
<!-- Shows on the first Tab press. A button, not a "#main" link, so it never changes the page address (safe in a frame). -->
<button type="button" class="skip-link" id="skip-link">Skip to the planner</button>
<header class="site">
<div class="wrap">
<p class="eyebrow">Kentucky PFM Challenge · Debt</p>
<div class="brand">
<svg class="brand-mark" viewBox="0 0 44 44" aria-hidden="true" focusable="false">
<rect class="bm-bg" width="44" height="44" rx="11"/>
<path class="bm-line" d="M9 17 L17 25 L24 20 L33 29"/>
<circle class="bm-dot" cx="34" cy="13" r="3.5"/>
</svg>
<h1>Make It to May</h1>
</div>
<p class="who">For independent, first-generation University of Kentucky undergrads who pay their own way: aid arrives as two lump sums a year, you work an hourly campus job, and there's no family backstop. It answers one question: will your money last until the semester ends, and should you borrow, work more, or do nothing?</p>
<p class="note" role="note"><svg class="note-icon" viewBox="0 0 18 18" aria-hidden="true" focusable="false"><circle cx="9" cy="9" r="7.5"/><path d="M9 8v5M9 5.2v.1"/></svg><span><strong>Educational use only.</strong> This is not financial, tax or legal advice. Every number is an estimate that assumes you keep the aid you have now. Confirm with UK Financial Aid and Student Account Services before you act.</span></p>
</div>
</header>
<main class="wrap" id="main" tabindex="-1">
<section id="app"></section>
<section id="tests" hidden></section>
<section id="how" class="card how" aria-labelledby="how-title"></section>
</main>
<div class="filebar" id="filebar">
<div class="wrap">
<div id="file-msg" class="filemsg" role="alert" hidden></div>
</div>
<div class="wrap filebar-inner">
<p class="status" id="save-status" aria-live="polite"><span class="dot" aria-hidden="true"></span><span id="status-text">No changes yet</span><span class="status-short" id="status-short" aria-hidden="true">No changes</span></p>
<div class="file-actions">
<button type="button" class="btn" id="save-btn"><span class="lbl-long">Save to file</span><span class="lbl-short">Save</span></button>
<button type="button" class="btn secondary" id="open-btn"><span class="lbl-long">Open file</span><span class="lbl-short">Open</span></button>
<button type="button" class="linkish" id="copy-btn">Copy data</button>
<button type="button" class="linkish" id="paste-btn">Paste data</button>
<!-- Narrow windows: Copy and Paste move into this menu so the bar fits on one row. -->
<details class="more-menu" id="more-menu">
<summary class="btn secondary">More</summary>
<div class="menu">
<button type="button" data-proxy="copy-btn">Copy data</button>
<button type="button" data-proxy="paste-btn">Paste data</button>
</div>
</details>
<input type="file" id="open-input" accept=".json,application/json" hidden>
</div>
</div>
</div>
<dialog id="copy-dialog" aria-labelledby="copy-title">
<h2 id="copy-title">Copy your data</h2>
<p class="small">If Save didn't give you a file, copy this text and paste it into a note or a text file you keep. To bring your numbers back, use <strong>Paste data</strong>.</p>
<textarea id="copy-text" rows="12" readonly spellcheck="false" aria-label="Your data as text"></textarea>
<p class="dialog-msg" id="copy-msg" role="status"></p>
<div class="dialog-actions">
<button type="button" class="btn" id="copy-do">Copy to clipboard</button>
<button type="button" class="btn secondary" id="copy-close">Close</button>
</div>
</dialog>
<dialog id="paste-dialog" aria-labelledby="paste-title">
<h2 id="paste-title">Paste your data</h2>
<p class="small">Paste the text you copied earlier, or the contents of a saved file.</p>
<p class="warn-line" id="paste-warn" hidden>Restoring will replace your unsaved changes.</p>
<textarea id="paste-text" rows="12" spellcheck="false" aria-label="Paste your data here"></textarea>
<div class="dialog-msg error" id="paste-msg" role="alert"></div>
<div class="dialog-actions">
<button type="button" class="btn" id="paste-do">Restore</button>
<button type="button" class="btn secondary" id="paste-close">Cancel</button>
</div>
</dialog>
<dialog id="sample-dialog" aria-labelledby="sample-title">
<h2 id="sample-title">Pick a sample student</h2>
<p class="small">All six are fictional, and each one lands on a different answer. Afterward, change any number to see what happens.</p>
<div class="sample-list" id="sample-list"></div>
<div class="dialog-actions">
<button type="button" class="btn secondary" id="sample-close">Cancel</button>
</div>
</dialog>
<dialog id="confirm-dialog" aria-labelledby="confirm-title">
<h2 id="confirm-title">Replace your unsaved changes?</h2>
<p id="confirm-body">Opening this file replaces the numbers on the page. Changes you haven't saved will be lost.</p>
<div class="dialog-actions">
<button type="button" class="btn" id="confirm-yes">Open the file</button>
<button type="button" class="btn secondary" id="confirm-no">Keep editing</button>
</div>
</dialog>
<footer>
<div class="wrap">
<p><strong>Educational use only.</strong> Not financial, tax or legal advice. No specific investments are ever suggested.</p>
<p>Private by design: nothing you type leaves this page. It makes no network calls, needs no login and never asks for bank details.</p>
<p>Independent student project, not affiliated with or endorsed by the University of Kentucky, KHEAA or the U.S. Department of Education.</p>
<p>Copyright © 2026 Brian Dennis. Released under the MIT License. Credits: no third-party code or libraries.</p>
<p><button type="button" class="linkish inline" id="run-tests">Run the test cases</button> to check every number this page computes against the reference model (or add <code>?test=1</code> to the address).</p>
</div>
</footer>
<script>
"use strict";
/* =====================================================================================
CONFIG: every constant the math uses, with its source and the date it was checked.
===================================================================================== */
const CONFIG = {
checked: "2026-11-11",
loan: {
// Undergraduate Direct Loan fixed rate, loans first disbursed Jul 1, 2026 – Jun 30, 2027.
// Source: https://fsapartners.ed.gov/knowledge-center/library/electronic-announcements/2026-06-04/interest-rates-federal-direct-loans-first-disbursed-between-july-1-2026-and-june-30-2027
// (FSA GENERAL-26-33, published Jun 4, 2026). Checked Nov 11, 2026.
// Later years' rates are set each July 1; the four-year view uses this as an editable default and says so.
rate: 0.0652,
// Origination fee (subsidized and unsubsidized), loans first disbursed through Sep 30, 2027.
// Source: https://fsapartners.ed.gov/knowledge-center/library/electronic-announcements/2026-05-13/fy27-sequester-required-changes-title-iv-student-aid-programs
// (FSA GENERAL-26-28, published May 13, 2026). Checked Nov 11, 2026.
fee: 0.01057,
// Grace period: 6 months after you leave school. Subsidized: no interest in school or grace.
// Unsubsidized: daily simple interest from disbursement = principal × rate ÷ 365 × days.
// Source: https://studentaid.gov/articles/subsidized-vs-unsubsidized-loans/ Checked Nov 11, 2026.
graceMonths: 6,
// Capitalization when repayment starts: none on Direct Loans since Jul 1, 2023. VERIFY (secondary source).
// Source: https://www.tateesq.com/learn/student-loan-interest-capitalization Checked Nov 11, 2026.
capitalizeAtRepayment: false,
},
limits: {
// Annual Direct Loan limits by grade level: [total, subsidized max]. Level 3 = 3rd year and beyond.
// Source: https://fsapartners.ed.gov/sites/default/files/2025-2026/2025-2026_Federal_Student_Aid_Handbook/_knowledge-center_fsa-handbook_2025-2026_vol8_ch4-annual-and-aggregate-loan-limits.pdf
// Unchanged for 2026–27: https://www.jmu.edu/financialaid/newsletters/federal_updates/obbba/obbba-ug-direct-loans.shtml
// Checked Nov 11, 2026. (Limits are prorated below full-time; the page says so but has no formula.)
annual: {
dependent: { 1: [5500, 3500], 2: [6500, 4500], 3: [7500, 5500] },
independent: { 1: [9500, 3500], 2: [10500, 4500], 3: [12500, 5500] },
},
// Aggregate undergraduate limits. Same handbook. Checked Nov 11, 2026.
aggregate: { dependent: 31000, independent: 57500 },
aggregateSub: 23000,
},
// Tiered Standard repayment term for loans first disbursed on or after Jul 1, 2026, by total balance:
// under $25,000: 10 years; $25,000–49,999: 15; $50,000–99,999: 20; $100,000+: 25.
// Source: https://www.mass.gov/info-details/the-new-tiered-standard-plan Checked Nov 11, 2026.
standardTiers: [[25000, 120], [50000, 180], [100000, 240]],
standardTopMonths: 300,
kees: {
// Renewal is checked once a year, at the end of spring, on cumulative GPA.
// 3.0+: full. 2.5–2.99: full if on track to graduate; 50% if not on track but full-time in one of
// the last two terms; otherwise none. Below 2.5: none next year.
// Source: https://studentsuccess.uky.edu/financial-aid-and-scholarships/academic-scholarships/kees
// Checked Nov 11, 2026. VERIFY: the page states the full-award line as both 3.0 and 2.5.
fullGpa: 3.0, minGpa: 2.5, partialShare: 0.5,
// Enrollment: full award at full time; "If you enrolled for 6 to 11 credit hours, your semester award will
// reduce proportionally" (the planner uses hours ÷ 12); 1–5 hours: no award that term. Same source, re-read Nov 11, 2026.
fullTimeHours: 12, minHours: 6,
// "available for undergraduate students for a maximum of 8 academic terms" and "must be used within 5 years
// of your high school graduation date." Same source, re-read Nov 11, 2026. (A "400%" lifetime figure from
// Brian's notes is not on that page, so the planner doesn't show it.)
maxTerms: 8, yearsFromHighSchool: 5,
// "On Track to Graduate": earned credit hours needed by the end of spring, by year in school. Year 1 is not
// checked; Year 2 (up to 4 terms) 48; Year 3 (up to 6 terms) 72; Year 4 (up to 8 terms) 120.
// Same source (table), read Nov 11, 2026. Brian chose this table for the planner.
onTrackHours: { 2: 48, 3: 72, 4: 120 },
},
term: {
// UK spring 2027. Source: https://registrar.uky.edu/sites/default/files/2025-10/university-calendar-academic-year-26-27-final.pdf
// Checked Nov 11, 2026. Aid is assumed to disburse on the first day of classes (editable).
name: "Spring 2027",
classesStart: "2027-01-11",
lastDayToAdd: "2027-01-15",
springBreak: ["2027-03-15", "2027-03-20"],
end: "2027-05-07",
// First day of fall classes, used as the fall loan date in the four-year view.
// Source: https://registrar.uky.edu/calendars/academic-calendar (Fall 2026 and Fall 2027 "Semester Begins").
// Checked Nov 11, 2026. Later years are ESTIMATES (same month and day as fall 2027); the page says so.
fallStarts: { 2026: "2026-08-24", 2027: "2027-08-23" },
fallStartEstimate: "08-23",
},
plan: {
// UK Installment Payment Plan: 4 payments (fall/spring); 1st due at enrollment ("immediate"), the rest by
// the 22nd of each following month; $50 non-refundable enrollment fee per semester, paid with the 1st
// payment; account balance must be $500 or more; aid or charge changes adjust the following installments.
// Source: https://studentaccount.uky.edu/student-account/installment-payment-plan (Fall 2026 text). Checked Nov 11, 2026.
// These are defaults: every value is editable on the page for other schools, and "pay in full" is an option.
payments: 4, dueDay: 22, enrollmentFee: 50, minBalance: 500,
// Spring timing: the plan opens "the first week of January"; without a plan the total is due "the 22nd of
// the month for which the charges were billed" (spring statements go out in January).
// Source: https://studentaccount.uky.edu/frequently-asked-questions Checked Nov 11, 2026.
// Spring 2027 defaults below are ESTIMATES from those rules; the page labels them and asks students to check myUK.
springFirstPayment: "2027-01-04",
springPayInFullDue: "2027-01-22",
},
privateLoan: {
// A LAST RESORT (Brian, Nov 12, 2026): shown only with a rate a lender quoted the student, never as the
// recommended fix, and only (a) after all federal room and the safe max, or (b) in the four-year view as
// the cost of skipping this plan's federal loan. There is no default rate: it depends on the lender,
// the student's credit and a cosigner.
// "Most private student loans require [a co-signer] unless the borrower has positive credit history";
// "For most student borrowers, federal Direct loans are the better option."
// Source: https://www.consumerfinance.gov/paying-for-college/choose-a-student-loan/ Checked Nov 12, 2026.
// UK: before private loans, "maximize all federal, state, and institutional financial aid funds"; UK's own
// loans include the CATapult Loan (full-time juniors and seniors with unmet need, 4.53%) and the Young Loan
// (unmet need and a 2.5+ GPA, 5%). Source: https://studentsuccess.uky.edu/financial-aid-and-scholarships/aid-options/loans
// Checked Nov 12, 2026. (Named on the page only; their terms aren't in the math.)
ukLoans: [{ name: "CATapult Loan", who: "full-time juniors and seniors with unmet need", rate: 0.0453 },
{ name: "Young Loan", who: "students with unmet need and a 2.5+ GPA", rate: 0.05 }],
// ASSUMPTIONS (Brian, Nov 12, 2026), each editable on the page: fixed rate; interest builds daily from each
// aid date; unpaid interest is added to the balance when payments start; payments start 6 months after
// graduation; repaid over the student's own private-loan years, else as long as this plan's federal loans.
graceMonths: 6,
},
// Every outside source, listed on the page under "How this works" (same links as the comments above).
sources: [
{ key: "rate", what: "Federal Direct Loan interest rate, 2026–27 (FSA GENERAL-26-33)",
url: "https://fsapartners.ed.gov/knowledge-center/library/electronic-announcements/2026-06-04/interest-rates-federal-direct-loans-first-disbursed-between-july-1-2026-and-june-30-2027" },
{ key: "fee", what: "Origination fee (FSA GENERAL-26-28)",
url: "https://fsapartners.ed.gov/knowledge-center/library/electronic-announcements/2026-05-13/fy27-sequester-required-changes-title-iv-student-aid-programs" },
{ key: "limits", what: "Annual and lifetime loan limits (FSA Handbook 2025–26, Vol. 8 Ch. 4)",
url: "https://fsapartners.ed.gov/sites/default/files/2025-2026/2025-2026_Federal_Student_Aid_Handbook/_knowledge-center_fsa-handbook_2025-2026_vol8_ch4-annual-and-aggregate-loan-limits.pdf" },
{ key: "limits2627", what: "Undergraduate limits unchanged for 2026–27 (JMU Financial Aid)",
url: "https://www.jmu.edu/financialaid/newsletters/federal_updates/obbba/obbba-ug-direct-loans.shtml" },
{ key: "interest", what: "Subsidized vs. unsubsidized interest and the grace period (StudentAid.gov)",
url: "https://studentaid.gov/articles/subsidized-vs-unsubsidized-loans/" },
{ key: "tiers", what: "Tiered Standard repayment plan (Mass.gov)", url: "https://www.mass.gov/info-details/the-new-tiered-standard-plan" },
{ key: "cap", what: "Interest capitalization when repayment starts (Tate Law; secondary, to be confirmed)",
url: "https://www.tateesq.com/learn/student-loan-interest-capitalization" },
{ key: "kees", what: "KEES renewal, enrollment and term limits (UK Student Success)",
url: "https://studentsuccess.uky.edu/financial-aid-and-scholarships/academic-scholarships/kees" },
{ key: "spring", what: "UK spring 2027 calendar (UK Registrar)",
url: "https://registrar.uky.edu/sites/default/files/2025-10/university-calendar-academic-year-26-27-final.pdf" },
{ key: "fall", what: "UK fall 2026 and fall 2027 start dates (UK Registrar academic calendar)",
url: "https://registrar.uky.edu/calendars/academic-calendar" },
{ key: "plan", what: "UK Installment Payment Plan (Student Account Services)",
url: "https://studentaccount.uky.edu/student-account/installment-payment-plan" },
{ key: "planFaq", what: "UK spring plan timing and bill due date (Student Account Services FAQ)",
url: "https://studentaccount.uky.edu/frequently-asked-questions" },
{ key: "privateCfpb", what: "Federal vs. private student loans, cosigners (Consumer Financial Protection Bureau)",
url: "https://www.consumerfinance.gov/paying-for-college/choose-a-student-loan/", checked: "2026-11-12" },
{ key: "ukLoans", what: "UK loans: federal aid first, CATapult and Young loans, private loan comparison chart (UK Financial Aid)",
url: "https://studentsuccess.uky.edu/financial-aid-and-scholarships/aid-options/loans", checked: "2026-11-12" },
],
product: {
// Product choices (Brian, Nov 11, 2026), not outside facts.
fastPayoffMonths: 24, // "pay it off over 2 years once payments start"
testStandardMonths: 120, // test mode keeps the 10-year comparison
loanStep: 10, // smallest loan search, in $ of cash received
hoursStep: 0.5, // smallest extra-hours search
hoursWarn: 40, // total hours/week above this: warning
hoursFlag: 60, // above this: flagged as nearly impossible
creditsPerSemester: 15, // assumed credits per past fall/spring term unless the student enters them
springGraduationDay: "05-07" // spring graduation default (estimate, editable)
},
};
/* =====================================================================================
ENGINE: a line-by-line port of reference_model.py. Keep the two in step.
Python and JavaScript round some halves differently, so pyRound/pySum copy Python exactly.
===================================================================================== */
// ENGINE-START
const Engine = (() => {
const RATE = CONFIG.loan.rate, FEE = CONFIG.loan.fee;
const LIMITS = CONFIG.limits.annual, AGG = CONFIG.limits.aggregate, AGG_SUB = CONFIG.limits.aggregateSub;
const TEST_START = "2027-01-04"; // reference-model default; the page always passes a start date
const DEFAULT_END = CONFIG.term.end, DEFAULT_DISB = CONFIG.term.classesStart;
const DAY_MS = 86400000;
// ---- Python-identical arithmetic ----
// round(x, nd): correctly rounded on the exact binary value, exact ties go to even (Python's rule).
function pyRound(x, nd = 2) {
const t = x * 2 ** (nd + 1); // exact (power of two)
if (Number.isInteger(t) && Math.abs(t) % 2 === 1) { // exact tie, e.g. 0.125 at 2 places
const p = 10 ** nd, n = Math.floor(x * p);
return (n % 2 === 0 ? n : n + 1) / p;
}
return Number(x.toFixed(nd)); // exact-value rounding; only ties differ, handled above
}
// sum(): CPython 3.12+ adds floats with Neumaier compensated summation.
function pySum(xs) {
let s = 0, c = 0;
for (const x of xs) {
const t = s + x;
if (Math.abs(s) >= Math.abs(x)) c += (s - t) + x; else c += (x - t) + s;
s = t;
}
return (c !== 0 && Number.isFinite(c)) ? s + c : s;
}
// ---- Dates (whole UTC days, so time zones can't shift anything) ----
const toDay = s => Date.UTC(+s.slice(0, 4), +s.slice(5, 7) - 1, +s.slice(8, 10)) / DAY_MS;
const toIso = n => new Date(n * DAY_MS).toISOString().slice(0, 10);
const weekday = n => (((n + 3) % 7) + 7) % 7; // Monday = 0, like Python
const monday = s => { const n = toDay(s); return toIso(n - weekday(n)); };
const monthEnd = (y, m) => new Date(Date.UTC(y, m, 0)).getUTCDate(); // m is 1-12
const isoOf = (y, m, dd) => toIso(Date.UTC(y, m - 1, dd) / DAY_MS);
function addMonths(s, k) {
const y0 = +s.slice(0, 4), m = +s.slice(5, 7), dd = +s.slice(8, 10);
const m0 = m - 1 + k;
const y = y0 + Math.floor(m0 / 12), mm = (((m0 % 12) + 12) % 12) + 1;
return isoOf(y, mm, Math.min(dd, monthEnd(y, mm)));
}
// Payment-plan dates: the first at enrollment, the rest on dueDay of each following month (clamped).
function planDates(first, payments, dueDay) {
const y0 = +first.slice(0, 4), m = +first.slice(5, 7), out = [first];
for (let i = 1; i < payments; i++) {
const m0 = m - 1 + i, y = y0 + Math.floor(m0 / 12), mm = (m0 % 12) + 1;
out.push(isoOf(y, mm, Math.min(dueDay, monthEnd(y, mm))));
}
return out;
}
const graceEndFrom = graduation => addMonths(graduation, CONFIG.loan.graceMonths);
// ---- Semester model ----
const netOfFee = (gross, fee = FEE) => pyRound(gross * (1 - fee), 2);
const gap = (charges, gifts, loansGross) =>
pyRound(charges - gifts - pySum(loansGross.map(l => netOfFee(l))), 2);
function splitInstallments(total, dates) {
const n = dates.length;
const base = Math.floor(total * 100 / n) / 100;
const amts = new Array(n).fill(base);
amts[0] = pyRound(total - base * (n - 1), 2); // leftover cent on the first
return dates.map((d, i) => [d, amts[i]]);
}
const datesOf = c => [c.start ?? TEST_START, c.end ?? DEFAULT_END, c.disb ?? DEFAULT_DISB];
function billSchedule(c, loanNet = 0) {
const disb = datesOf(c)[2];
const dates = [...c.due].sort();
const g0 = c.gap;
if (g0 <= 0) {
const refund = pyRound(loanNet - g0, 2);
return [[], refund > 0 ? [[disb, refund]] : []];
}
const fixed = splitInstallments(g0, dates).filter(([bd]) => bd < disb);
const restDates = dates.filter(bd => bd >= disb);
const restTotal = pyRound(g0 - pySum(fixed.map(b => b[1])) - loanNet, 2);
const rest = restTotal > 0 && restDates.length ? splitInstallments(restTotal, restDates) : [];
const bills = fixed.concat(rest);
const fee = dates.length > 1 ? (c.plan_fee || 0) : 0;
if (fee && bills.length) bills.push([dates[0], fee]);
const refund = restTotal < 0 ? pyRound(-restTotal, 2) : 0;
return [bills, refund > 0 ? [[disb, refund]] : []];
}
// What is due on each date (installment plus any plan fee), for the read-only schedule.
function billsByDate(c, loanNet = 0) {
const totals = new Map();
for (const [bd, a] of billSchedule(c, loanNet)[0]) {
if (!totals.has(bd)) totals.set(bd, []);
totals.get(bd).push(a);
}
return [...totals.keys()].sort().map(bd => [bd, pyRound(pySum(totals.get(bd)), 2)]);
}
function forecast(c, extraHours = 0, loanNet = 0) {
const [start, end] = datesOf(c);
const [bills, inflows] = billSchedule(c, loanNet);
const billDays = bills.map(([bd, a]) => [toDay(bd), a]);
const inDays = inflows.map(([bd, a]) => [toDay(bd), a]);
const noPay = new Set((c.no_pay_weeks || []).map(monday));
const endDay = toDay(end);
const rows = [];
let cash = c.cash0, w = 0, day = toDay(monday(start));
while (day <= endDay) {
const weekEnd = day + 6, iso = toIso(day);
const pay = noPay.has(iso) ? 0 : pyRound((c.hours + extraHours) * c.wage * c.k, 2);
const living = pyRound(c.living * 12 / 52, 2);
const due = pySum(billDays.filter(([n]) => day <= n && n <= weekEnd).map(b => b[1]));
const inflow = pySum(inDays.filter(([n]) => day <= n && n <= weekEnd).map(b => b[1]));
cash = pyRound(cash + pay - living - due + inflow, 2);
w += 1;
rows.push([w, iso, cash]);
day += 7;
}
return rows;
}
// Cushion is checked from the disbursement week onward.
function shortfall(rows, cushion, fromDate = DEFAULT_DISB) {
const dm = monday(fromDate);
const counted = rows.filter(r => r[1] >= dm);
let low = counted[0];
for (const r of counted) if (r[2] < low[2]) low = r;
const runOut = counted.find(r => r[2] < cushion) || null;
return [Math.max(0, pyRound(cushion - low[2], 2)), low, runOut];
}
const preAidDip = (rows, disb) => rows.find(r => r[1] < monday(disb) && r[2] < 0) || null;
function levelPayment(gross, accrued, months, rate = RATE) {
const endBalance = payment => {
let principal = gross, unpaid = accrued;
for (let i = 0; i < months; i++) {
unpaid += principal * rate / 12;
let p = payment;
const x = Math.min(p, unpaid);
unpaid -= x;
p -= x;
principal -= p;
}
return principal + unpaid;
};
let lo = 0, hi = gross;
for (let i = 0; i < 200; i++) {
const mid = (lo + hi) / 2;
if (endBalance(mid) > 0) lo = mid; else hi = mid;
}
return pyRound(hi, 2);
}
function loanCost(net, graceEnd, months, subsidized = false, disb = DEFAULT_DISB) {
const gross = Math.ceil(net / (1 - FEE));
const days = toDay(graceEnd) - toDay(disb);
const accrued = subsidized ? 0 : pyRound(gross * RATE * days / 365, 2);
const pmt = levelPayment(gross, accrued, months);
const total = pyRound(pmt * months, 2);
return { gross, accrued, days, pmt, total, cost: pyRound(total - net, 2) };
}
// ---- Private loans: a last resort, priced only at a rate a lender quoted the student (port of private_cost,
// private_fill and private_payoff). Fixed rate; daily interest from the aid date to grace end; with
// capitalize, that interest is added to the balance when payments start; level monthly payment.
function privateCost(net, disb, graceEnd, rate, fee, months, capitalize = true) {
const gross = Math.ceil(net / (1 - fee));
const days = toDay(graceEnd) - toDay(disb);
const accrued = pyRound(gross * rate * days / 365, 2);
const pmt = capitalize ? levelPayment(pyRound(gross + accrued, 2), 0, months, rate) : levelPayment(gross, accrued, months, rate);
const total = pyRound(pmt * months, 2);
return { gross, accrued, days, pmt, total, fee: pyRound(gross - netOfFee(gross, fee), 2), cost: pyRound(total - net, 2) };
}
// Smallest private loan (cash, $10 steps) that closes what's left after working extraHours more and borrowing
// federalNet. A loan of the remaining bill plus the shortfall always closes it, so the search stops there.
function privateFill(c, extraHours, federalNet) {
const disb = datesOf(c)[2], step = CONFIG.product.loanStep;
const short = x => shortfall(forecast(c, extraHours, federalNet + x), c.cushion, disb)[0];
const left = short(0);
if (left === 0) return 0;
const bound = step * Math.ceil((Math.max(0, c.gap) + left) / step) + step;
return grid(bound, step).slice(1).find(x => short(x) === 0) ?? null;
}
function privatePayoff(cash, springs, pv) {
const rows = springs.map(s => privateCost(cash, s, pv.grace_end, pv.rate, pv.fee, pv.months, pv.capitalize));
const borrowed = pySum(rows.map(r => r.gross));
const total = pyRound(pySum(rows.map(r => r.total)), 2);
return { cash_each_spring: cash, loans: rows.length, borrowed, fees: pyRound(pySum(rows.map(r => r.fee)), 2),
accrued: pyRound(pySum(rows.map(r => r.accrued)), 2), months: pv.months, payment: pyRound(pySum(rows.map(r => r.pmt)), 2),
total_repaid: total, interest: pyRound(total - borrowed, 2), payoff_date: addMonths(pv.grace_end, pv.months) };
}
function grid(cap, step) {
const vals = [];
let x = 0;
while (x <= cap) { vals.push(x); x += step; }
if (cap > 0 && vals[vals.length - 1] < cap) vals.push(cap);
return vals;
}
function solve(c) {
const disb = datesOf(c)[2];
const rows = forecast(c);
const [S, low, runOut] = shortfall(rows, c.cushion, disb);
const weeksLeft = rows.filter(r => r[1] >= monday(disb)).length;
const dip = preAidDip(rows, disb);
const out = {
gap: c.gap, tightest_week: low[1], min_cash: low[2], run_out_week: runOut ? runOut[1] : null, S,
weeks_counted: weeksLeft, pre_aid_negative_week: dip ? dip[1] : null,
};
if (S === 0) return { ...out, state: "covered", spare: pyRound(low[2] - c.cushion, 2) };
const short = (h, loanNet) => shortfall(forecast(c, h, loanNet), c.cushion, disb)[0];
const minLoan = (h, capNet, base = 0) => {
for (const x of grid(capNet, CONFIG.product.loanStep)) if (short(h, base + x) === 0) return x;
return null;
};
const unsubCosts = y => {
const payRate = c.wage * c.k;
const hoursToBorrow = payRate > 0 ? y / payRate : null;
for (const [label, months] of [["2yr", CONFIG.product.fastPayoffMonths], ["10yr", CONFIG.product.testStandardMonths]]) {
const lc = loanCost(y, c.grace_end, months, false, disb);
out["unsub_" + label] = lc;
out["V_" + label] = hoursToBorrow ? pyRound(lc.cost / hoursToBorrow, 2) : null;
}
out.tradeoff_hours = hoursToBorrow ? pyRound(hoursToBorrow / weeksLeft, 1) : null;
};
// 1) subsidized room
const subCap = Math.floor(c.sub_room * (1 - FEE) * 100) / 100;
let sub = 0;
if (subCap > 0) {
const x = minLoan(0, subCap);
if (x !== null) {
return { ...out, state: "fixed_sub", sub_net: x,
sub_2yr: loanCost(x, c.grace_end, CONFIG.product.fastPayoffMonths, true, disb),
sub_10yr: loanCost(x, c.grace_end, CONFIG.product.testStandardMonths, true, disb) };
}
sub = subCap;
out.sub_net = sub;
}
// 2) extra hours alone, within safe max
const room = c.safe_max - c.hours;
for (const h of grid(room, CONFIG.product.hoursStep)) {
if (short(h, sub) === 0) return { ...out, state: "fixed_hours", extra_hours: h };
}
// 3) smallest unsubsidized loan
const unsubCap = Math.floor(c.unsub_room * (1 - FEE) * 100) / 100;
const y = minLoan(0, unsubCap, sub);
if (y !== null) {
out.state = "fixed_unsub";
out.unsub_net = y;
unsubCosts(y);
if (room > 0) out.unsub_if_work_to_max = minLoan(room, unsubCap, sub);
return out;
}
// 4) mix (Brian, Nov 11): work up to the safe max, borrow the smallest unsubsidized loan that then
// closes the gap, and trim any extra hours that loan doesn't need. Alternative shown on the page:
// borrow all remaining room and work the fewest extra hours.
if (unsubCap > 0 && room > 0) {
const yMix = minLoan(room, unsubCap, sub);
if (yMix !== null) {
const hours = grid(room, CONFIG.product.hoursStep);
out.state = "fixed_mix";
out.unsub_net = yMix;
out.extra_hours = hours.find(h => short(h, sub + yMix) === 0);
unsubCosts(yMix);
out.alt_extra_hours = hours.find(h => short(h, sub + unsubCap) === 0);
out.alt_unsub_net = unsubCap;
return out;
}
}
// 5) still short after working to the safe max and borrowing all remaining room
return { ...out, state: "short_beyond_limits", short_after_all: short(Math.max(0, room), sub + unsubCap) };
}
// ---- Option cards and aid at risk (port of options() and aid_at_risk()) ----
function options(c, ceiling, planMonths) {
const disb = datesOf(c)[2];
const rec = solve(c);
const payRate = c.wage * c.k;
const short = (h, loanNet) => shortfall(forecast(c, h, loanNet), c.cushion, disb)[0];
const minLoan = (h, capNet, base = 0) => {
for (const x of grid(capNet, CONFIG.product.loanStep)) if (short(h, base + x) === 0) return x;
return null;
};
const priced = (subNet, unsubNet) => {
const out = { sub_net: subNet, unsub_net: unsubNet };
for (const [label, months] of [["fast", CONFIG.product.fastPayoffMonths], ["plan", planMonths]]) {
const parts = (subNet > 0 ? [loanCost(subNet, c.grace_end, months, true, disb)] : [])
.concat(unsubNet > 0 ? [loanCost(unsubNet, c.grace_end, months, false, disb)] : []);
out[label] = { months, gross: pySum(parts.map(p => p.gross)), pmt: pyRound(pySum(parts.map(p => p.pmt)), 2),
cost: pyRound(pySum(parts.map(p => p.cost)), 2) };
}
const cash = pyRound(subNet + unsubNet, 2);
out.V_plan = cash > 0 && payRate > 0 ? pyRound(out.plan.cost / (cash / payRate), 2) : null;
return out;
};
const subCap = Math.floor(c.sub_room * (1 - FEE) * 100) / 100;
const unsubCap = Math.floor(c.unsub_room * (1 - FEE) * 100) / 100;
const out = { state: rec.state };
if (rec.S === 0) return Object.assign(out, { hours_alone: 0, borrow: null, borrow_short: 0, recommended: null,
safe_hours_alone: 0, nothing_extra_short: 0, private_net: 0 });
out.hours_alone = grid(ceiling - c.hours, CONFIG.product.hoursStep).find(h => short(h, 0) === 0) ?? null;
// "Borrow nothing extra" only counts if extra hours within the SAFE MAX close the gap (Brian, Nov 12, 2026).
const room = Math.max(0, c.safe_max - c.hours);
out.safe_hours_alone = grid(room, CONFIG.product.hoursStep).find(h => short(h, 0) === 0) ?? null;
out.nothing_extra_short = out.safe_hours_alone !== null ? 0 : short(room, 0);
out.private_net = rec.state === "short_beyond_limits" ? privateFill(c, room, subCap + unsubCap) : 0;
const x = subCap > 0 ? minLoan(0, subCap) : null;
if (x !== null) out.borrow = priced(x, 0);
else {
const y = minLoan(0, unsubCap, subCap);
out.borrow = y !== null ? priced(subCap, y) : null;
}
out.borrow_short = out.borrow ? 0 : short(0, subCap + unsubCap);
out.recommended = ["fixed_sub", "fixed_hours", "fixed_unsub", "fixed_mix"].includes(rec.state)
? { ...priced(rec.sub_net ?? 0, rec.unsub_net ?? 0), extra_hours: rec.extra_hours ?? 0 } : null;
return out;
}
const hasRule = v => v !== null && v !== undefined;
const aidAtRisk = awards => pyRound(2 * pySum(awards.filter(a => a.accepted &&
(a.type === "kees" || hasRule(a.min_gpa) || hasRule(a.min_credits))).map(a => a.amount)), 2);
// Display only: the same weekly loop as forecast(), keeping each week's parts for the chart and table.
// A test-mode check confirms its cash column equals forecast() exactly.
function forecastDetail(c, extraHours = 0, loanNet = 0) {
const [start, end] = datesOf(c);
const [bills, inflows] = billSchedule(c, loanNet);
const billDays = bills.map(([bd, a]) => [toDay(bd), a, bd]);
const inDays = inflows.map(([bd, a]) => [toDay(bd), a, bd]);
const noPay = new Set((c.no_pay_weeks || []).map(monday));
const endDay = toDay(end);
const rows = [];
let cash = c.cash0, w = 0, day = toDay(monday(start));
while (day <= endDay) {
const weekEnd = day + 6, iso = toIso(day);
const pay = noPay.has(iso) ? 0 : pyRound((c.hours + extraHours) * c.wage * c.k, 2);
const living = pyRound(c.living * 12 / 52, 2);
const weekBills = billDays.filter(([n]) => day <= n && n <= weekEnd);
const weekIn = inDays.filter(([n]) => day <= n && n <= weekEnd);
const due = pySum(weekBills.map(b => b[1]));
const inflow = pySum(weekIn.map(b => b[1]));
cash = pyRound(cash + pay - living - due + inflow, 2);
w += 1;
rows.push({ week: w, monday: iso, pay, living, due, inflow, cash, billDates: weekBills.map(b => b[2]) });
day += 7;
}
return rows;
}
// ---- Loan room, repayment term, KEES ----
function loanRoom(dependency, level, subYear, unsubYear, priorTotal = 0, priorSub = 0) {
const [total, subMax] = LIMITS[dependency][Math.min(level, 3)];
const totalRoom = Math.max(0, Math.min(total - subYear - unsubYear,
AGG[dependency] - priorTotal - subYear - unsubYear));
const subRoom = Math.max(0, Math.min(subMax - subYear, AGG_SUB - priorSub - subYear, totalRoom));
return { sub_room: subRoom, unsub_room: totalRoom - subRoom };
}
function standardMonths(balance) {
for (const [limit, months] of CONFIG.standardTiers) if (balance < limit) return months;
return CONFIG.standardTopMonths;
}
function keesNextYear(gpa, onTrack, fullTimeRecent) {
const K = CONFIG.kees;
if (gpa >= K.fullGpa) return 1.0;
if (gpa >= K.minGpa) {
if (onTrack) return 1.0;
return fullTimeRecent ? K.partialShare : 0.0;
}
return 0.0;
}
// KEES "on track" (UK's table: year 1 not checked; years 2, 3, 4+ need 48, 72, 120 earned credit hours by the
// end of spring) and this term's aid lost at a lighter credit load. Ports of reference_model.py.
function keesOnTrack(yearInSchool, earned) {
const need = CONFIG.kees.onTrackHours[Math.min(yearInSchool, 4)];
return need === undefined ? true : earned >= need;
}
function under12Cost(awards, creditHours) {
const lost = pySum(awards.filter(a => a.accepted && hasRule(a.min_credits) && creditHours < a.min_credits).map(a => a.amount));
const kees = pySum(awards.filter(a => a.accepted && a.type === "kees").map(a => a.amount));
return pyRound(lost + kees * (1 - keesTermShare(creditHours)), 2);
}
function keesTermShare(creditHours) {
const K = CONFIG.kees;
if (creditHours >= K.fullTimeHours) return 1.0;
if (creditHours >= K.minHours) return creditHours / K.fullTimeHours;
return 0.0;
}
// ---- Four-year view (spec in reference_model.py) ----
function payoff(loans, graceEnd, months) {
const rows = [];
for (const l of loans) {
if (l.gross <= 0) continue;
const days = toDay(graceEnd) - toDay(l.disb);
const accrued = l.sub ? 0 : pyRound(l.gross * l.rate * days / 365, 2);
const pmt = levelPayment(l.gross, accrued, months, l.rate);
rows.push({ gross: l.gross, sub: l.sub, accrued, pmt, total: pyRound(pmt * months, 2),
fee: pyRound(l.gross - netOfFee(l.gross, l.fee), 2) });
}
const borrowed = pySum(rows.map(r => r.gross));
const totalRepaid = pyRound(pySum(rows.map(r => r.total)), 2);
return {
sub_borrowed: pySum(rows.filter(r => r.sub).map(r => r.gross)),
unsub_borrowed: pySum(rows.filter(r => !r.sub).map(r => r.gross)),
borrowed,
fees: pyRound(pySum(rows.map(r => r.fee)), 2),
accrued: pyRound(pySum(rows.map(r => r.accrued)), 2),
months,
payment: pyRound(pySum(rows.map(r => r.pmt)), 2),
total_repaid: totalRepaid,
interest: pyRound(totalRepaid - borrowed, 2),
payoff_date: addMonths(graceEnd, months),
};
}
function fourYear(fy) {
const dep = fy.dependency, out = {}, fedLoans = {};
for (const plan of ["full_offer", "this_plan", "nothing_extra"]) {
const loans = (fy.prior || []).map(l => ({ ...l }));
let cumTotal = pySum(loans.map(l => l.gross));
let cumSub = pySum(loans.filter(l => l.sub).map(l => l.gross));
fy.years.forEach((y, i) => {
const [totalLim, subLim] = LIMITS[dep][Math.min(y.level, 3)];
let wantSub, wantUnsub;
if (plan === "full_offer") {
wantSub = subLim; wantUnsub = totalLim - subLim;
} else {
wantSub = y.accepted_sub; wantUnsub = y.accepted_unsub;
if (plan === "this_plan") { wantSub += fy.extra_sub; wantUnsub += fy.extra_unsub; }
}
const sub = Math.max(0, Math.min(wantSub, subLim, AGG_SUB - cumSub));
const unsub = Math.max(0, Math.min(wantUnsub, totalLim - sub, AGG[dep] - cumTotal - sub));
for (const [isSub, amt, accepted] of [[true, sub, y.accepted_sub], [false, unsub, y.accepted_unsub]]) {
const fall = (plan === "full_offer" && i > 0) ? Math.floor(amt / 2) : Math.min(amt, Math.floor(accepted / 2));
const spring = y.spring === null ? 0 : amt - fall; // graduating in fall: no spring loan that year
for (const [when, part] of [[y.fall, fall], [y.spring, spring]]) {
if (part > 0) loans.push({ gross: part, sub: isSub, rate: y.rate, fee: y.fee, disb: when });
}
if (isSub) cumSub += fall + spring;
cumTotal += fall + spring;
}
});
const total = pySum(loans.map(l => l.gross));
const months = fy.own_years ? fy.own_years * 12 : standardMonths(total);
fedLoans[plan] = loans;
out[plan] = payoff(loans, fy.grace_end, months);
}
// Private loans (only with a quoted rate): see four_year() in reference_model.py.
if (fy.private) {
const springs = fy.years.map(y => y.spring).filter(s => s !== null);
const mThis = out.this_plan.months;
const pv = { ...fy.private, months: fy.private.months || mThis };
const extraCash = (pv.cash.nothing_extra ?? 0) - (pv.cash.this_plan ?? 0);
if (extraCash > 0 && springs.length) {
const cost = o => o.interest + o.fees;
const neAtM = payoff(fedLoans.nothing_extra, fy.grace_end, mThis);
const priv = privatePayoff(extraCash, springs, { ...pv, months: mThis });
out.compare = { months: mThis, cash_each_spring: extraCash, federal: pyRound(cost(out.this_plan) - cost(neAtM), 2),
private: pyRound(priv.interest + priv.fees, 2) };
}
for (const plan of ["this_plan", "nothing_extra"]) {
const cash = pv.cash[plan] ?? 0;
if (!(cash > 0 && springs.length)) continue;
const p = privatePayoff(cash, springs, pv), o = out[plan];
o.private = p;
o.payoff_date = o.borrowed === 0 ? p.payoff_date : (o.payoff_date > p.payoff_date ? o.payoff_date : p.payoff_date);
o.borrowed = o.borrowed + p.borrowed;
o.fees = pyRound(o.fees + p.fees, 2);
o.accrued = pyRound(o.accrued + p.accrued, 2);
o.payment = pyRound(o.payment + p.payment, 2);
o.total_repaid = pyRound(o.total_repaid + p.total_repaid, 2);
o.interest = pyRound(o.total_repaid - o.borrowed, 2);
}
}
return out;
}
return { pyRound, pySum, toDay, toIso, monday, addMonths, planDates, graceEndFrom, netOfFee, gap, splitInstallments,
billSchedule, billsByDate, forecast, forecastDetail, shortfall, preAidDip, levelPayment, loanCost, grid, solve,
options, aidAtRisk, keesOnTrack, under12Cost, loanRoom,
standardMonths, keesNextYear, keesTermShare, payoff, fourYear, privateCost, privateFill, privatePayoff };
})();
// ENGINE-END
</script>
<script>
"use strict";
/* =====================================================================================
YOUR DATA: what the planner keeps, and how a saved file is checked, saved and opened.
Nothing is stored in the browser (Globefin pages can't store data); Save writes a file
the student keeps, and Copy/Paste is the fallback if a host blocks downloads.
===================================================================================== */
const Schema = (() => {
const APP_ID = "make-it-to-may", VERSION = 1, MAX_CHARS = 1000000, MAX_AWARDS = 30;
const f = (path, label, kind, o = {}) => ({ path, label, kind, nullable: true, ...o });
const money = (path, label, o = {}) => f(path, label, "money", o);
const AWARD_TYPES = [["grant", "Grant"], ["scholarship", "Scholarship"], ["kees", "KEES"],
["subsidized", "Subsidized loan"], ["unsubsidized", "Unsubsidized loan"], ["workstudy", "Work-Study"]];
// Every saved field: label, type, allowed range, where to find it (hint) and a jargon tip.
// The form and the file check both use this list, so they can't disagree.
const GROUPS = [
{ id: "about", fields: [
f("profile.yearInSchool", "Year in school", "enum", { options: [[1, "1st year"], [2, "2nd year"], [3, "3rd year"], [4, "4th year or more"]],
hint: "Your class standing on myUK. It sets how much you can borrow." }),
f("profile.dependency", "FAFSA dependency status", "enum", { options: [["independent", "Independent"], ["dependent", "Dependent"]],
tip: "dependency", hint: "On your FAFSA Submission Summary." }),
f("profile.gpa", "Cumulative GPA", "num", { min: 0, max: 4, step: 0.01, tip: "gpa", hint: "On myUK." }),
f("profile.creditHours", "Credit hours this term", "num", { min: 0, max: 30, step: 0.5, tip: "creditHours", hint: "Full-time is 12 or more." }),
f("profile.graduationTerm", "Expected graduation term", "enum", { options: [["spring", "Spring"], ["fall", "Fall"]], rerender: true }),
f("profile.graduationYear", "Expected graduation year", "int", { min: 2026, max: 2040, year: true,
hint: "Your best guess. It sets how long interest builds before payments start." }),
f("profile.graduationDate", "Graduation date", "date", { hint: "Spring fills in May 7 (an estimate). For fall, enter your date." }),
f("profile.semesterCredits", "Credits you earned in each past semester", "numbers", { nullable: false, missingOk: true, dflt: [],
min: 0, max: 30, step: 0.5, maxItems: 16, addLabel: "Add a semester",
hint: `Optional; include transfer credit UK accepted. If you leave this empty, the planner assumes ${CONFIG.product.creditsPerSemester} a semester.` }),
f("profile.fullTimeRecent", "Full-time (12+ hours) in one of your last two terms", "bool",
{ hint: "KEES uses this if your GPA ends up between 2.5 and 2.99." }),
] },
{ id: "term", fields: [
f("school.termName", "Term", "text", { nullable: false, max: 40 }),
f("school.forecastStart", "Start the forecast on", "date", { nullable: false,
hint: "Usually this week. Your cash on hand should be what you have on this date." }),
f("school.aidDate", "Aid arrives (disbursement)", "date", { nullable: false, tip: "disbursement",
hint: "UK: assumed to be the first day of classes. Financial Aid can confirm." }),
f("school.termEnd", "Last day of the term", "date", { nullable: false }),
f("school.noPayWeeks", "Weeks with no paycheck", "dates", { nullable: false, maxItems: 40, addLabel: "Add a week", every: "week",
hint: "Weeks your job pays nothing, like winter break. Any day in the week works." }),
] },
{ id: "bill", fields: [
money("bill.tuition", "Tuition and fees", { hint: "From your myUK Account Summary. Leave a line blank if it isn't on your bill." }),
money("bill.housing", "Housing"),
money("bill.meals", "Meal plan"),
money("bill.books", "Books (only if billed)"),
money("bill.other", "Other billed charges"),
f("payment.mode", "How you pay the bill", "enum", { nullable: false, rerender: true, tip: "paymentPlan",
options: [["plan", "Monthly payment plan"], ["full", "Pay in full by the due date"]] }),
f("payment.fullDue", "Due date", "date", { nullable: false,
hint: "UK: the 22nd of the month the bill comes out, so Jan 22 for spring (an estimate)." }),
f("payment.firstPayment", "First payment (the day you enroll in the plan)", "date", { nullable: false,
hint: "UK's spring plan opens the first week of January. Enrolling after your aid arrives lets a new loan lower every payment, including the first." }),
f("payment.payments", "Number of payments", "int", { nullable: false, min: 2, max: 12 }),
f("payment.dueDay", "Later payments are due on day", "int", { nullable: false, min: 1, max: 31 }),
money("payment.fee", "Plan enrollment fee", { nullable: false, max: 10000,
hint: `UK: $${CONFIG.plan.enrollmentFee} a semester, paid with the first payment.` }),
money("payment.minBalance", "Smallest balance the plan allows", { nullable: false, hint: `UK: $${CONFIG.plan.minBalance}.` }),
f("payment.dates", "Payment dates", "dates", { nullable: false, maxItems: 12, addLabel: "Add a date", every: "month",
hint: "Rebuilt when you change the settings above. Edit any date if your school's differ." }),
] },
{ id: "aid", fields: [
money("loans.subRoomOverride", "Subsidized loan you can still accept this year", { tip: "subsidized",
hint: "Optional. Leave blank to use the federal limits. Subsidized loans depend on need, so myUK's offer may be lower." }),
money("loans.unsubRoomOverride", "Unsubsidized loan you can still accept this year", { tip: "unsubsidized",
hint: "Optional. Leave blank to use the federal limits." }),
money("loans.priorTotal", "Federal loans from earlier school years", { hint: "Optional. Used for the lifetime borrowing limit." }),
money("loans.priorSub", "…of which subsidized"),
] },
{ id: "money", fields: [
money("money.cash", "Cash on hand", { min: -100000,
hint: "Checking plus savings you can use, on the forecast start date." }),
f("money.hours", "Job hours per week", "num", { min: 0, max: 100, step: 0.5 }),
money("money.wage", "Hourly wage", { max: 200 }),
money("money.takeHome", "Take-home pay per week", { max: 20000, tip: "takeHome",
hint: "Optional, from a pay stub. Leave blank and the planner uses pay before taxes." }),
f("money.safeMax", "Most hours a week you can work without hurting your grades", "num", { min: 0, max: 100, step: 0.5,
hint: "Your own judgment." }),
money("money.living", "Living costs outside the bill, per month", {
hint: "Rent you pay yourself, food beyond your meal plan, phone, gas and so on." }),
money("money.cushion", "Emergency cushion to keep", { tip: "cushion" }),
f("money.hoursCeiling", "Highest weekly hours to consider", "num", { nullable: false, min: 1, max: 168, step: 0.5,
hint: `For the "work more" option. Above ${CONFIG.product.hoursWarn} hours a week gets a warning; above ${CONFIG.product.hoursFlag} is flagged as nearly impossible.` }),
] },
{ id: "payoff", fields: [
f("payoff.mode", "Payoff plan", "enum", { nullable: false, rerender: true, tip: "standardPlan",
options: [["standard", "Standard plan (length set by how much you owe)"], ["years", "Pay it off in my own number of years"]] }),
f("payoff.years", "Years to pay it off", "int", { min: 1, max: 30 }),
] },
{ id: "private", fields: [ // added Nov 12, 2026 (files saved earlier open with these blank)
f("private.rate", "Private loan rate a lender quoted you (APR, %)", "num", { missingOk: true, dflt: null, min: 0, max: 36, step: 0.01,
tip: "privateLoan", hint: "Only if you've been quoted one. Blank keeps private loans out of your plan." }),
f("private.fee", "Private loan fee (%)", "num", { missingOk: true, dflt: null, min: 0, max: 10, step: 0.01, hint: "Blank = no fee." }),
f("private.years", "Years to repay the private loan", "int", { missingOk: true, dflt: null, min: 1, max: 25,
hint: "Blank = as long as your federal loans, so the two compare fairly." }),
f("private.graceMonths", "Months after graduation before private payments start", "int", { missingOk: true, dflt: null, min: 0, max: 24,
hint: `Blank = ${CONFIG.privateLoan.graceMonths} (an assumption; check your lender's terms).` }),
f("private.capitalize", "Unpaid interest is added to the balance when payments start", "bool", { nullable: false, missingOk: true, dflt: true,
hint: "Usual for private loans; check your lender's terms." }),
] },
{ id: "future", fields: [ // edited in the "After graduation" section; blank = the 2026–27 value
f("future.rates", "Loan interest rate for later school years (%)", "numbers", { nullable: false, missingOk: true, dflt: [],
allowNull: true, min: 0, max: 20, step: 0.01, maxItems: 12 }),
f("future.fees", "Origination fee for later school years (%)", "numbers", { nullable: false, missingOk: true, dflt: [],
allowNull: true, min: 0, max: 10, step: 0.001, maxItems: 12 }),
] },
];
const FIELDS = GROUPS.flatMap(g => g.fields);
const byPath = Object.fromEntries(FIELDS.map(fd => [fd.path, fd]));
const AWARD_FIELDS = [
f("name", "Name", "text", { nullable: false, max: 60 }),
f("type", "Type", "enum", { nullable: false, options: AWARD_TYPES, rerender: true }),
money("amount", "Amount this term"),
f("accepted", "Accepted", "bool", { nullable: false }),
f("minGpa", "Min GPA to keep", "num", { min: 0, max: 4, step: 0.01 }),
f("minCredits", "Min credit hours to keep", "num", { min: 0, max: 30, step: 0.5 }),
f("hasJob", "Have a Work-Study job", "bool", { nullable: false }),
];
const newAward = () => ({ name: "", type: "grant", amount: null, accepted: true, minGpa: null, minCredits: null, hasJob: false });
// Range limits in messages: years as written (2026, not 2,026); money with a dollar sign.
const fmtNum = (n, fd = {}) => fd.year ? String(n)
: fd.kind === "money" ? (n < 0 ? "−$" : "$") + Math.abs(n).toLocaleString("en-US") : n.toLocaleString("en-US");
const isDate = v => typeof v === "string" && /^\d{4}-\d{2}-\d{2}$/.test(v) &&
+v.slice(0, 4) >= 2000 && +v.slice(0, 4) <= 2100 && Engine.toIso(Engine.toDay(v)) === v;
function todayIso() {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
const getPath = (obj, path) =>
path.split(".").reduce((o, k) => (o !== null && typeof o === "object" ? o[k] : undefined), obj);
function setPath(obj, path, value) {
const keys = path.split(".");
let o = obj;
keys.slice(0, -1).forEach((k, i) => {
if (o[k] === null || typeof o[k] !== "object") o[k] = /^\d+$/.test(keys[i + 1]) ? [] : {};
o = o[k];
});
o[keys[keys.length - 1]] = value;
}
// One field's value: null if fine, otherwise a plain-language problem.
function check(fd, v) {
if (v === undefined) return `${fd.label} is missing.`;
if (v === null) return fd.nullable ? null : `${fd.label} is missing.`;
switch (fd.kind) {
case "money": case "num": case "int": {
const min = fd.min ?? 0, max = fd.max ?? 1000000;
if (typeof v !== "number" || !Number.isFinite(v)) return `${fd.label} must be a number.`;
if (fd.kind === "int" && !Number.isInteger(v)) return `${fd.label} must be a whole number.`;
if (v < min || v > max) return `${fd.label} must be from ${fmtNum(min, fd)} to ${fmtNum(max, fd)}.`;
return null;
}
case "date": return isDate(v) ? null : `${fd.label} must be a real date (YYYY-MM-DD).`;
case "bool": return typeof v === "boolean" ? null : `${fd.label} must be yes or no.`;
case "enum": return fd.options.some(([val]) => val === v) ? null
: `${fd.label} must be one of: ${fd.options.map(o => o[1]).join(", ")}.`;
case "text": {
const max = fd.max ?? 60;
return typeof v === "string" && v.length <= max ? null : `${fd.label} must be text of at most ${max} characters.`;
}
case "dates":
if (!Array.isArray(v)) return `${fd.label} must be a list of dates.`;
if (v.length > fd.maxItems) return `${fd.label} can have at most ${fd.maxItems} dates.`;
return v.every(isDate) ? null : `${fd.label} must contain only real dates (YYYY-MM-DD).`;
case "numbers": {
const min = fd.min ?? 0, max = fd.max ?? 1000000;
if (!Array.isArray(v)) return `${fd.label} must be a list of numbers.`;
if (v.length > fd.maxItems) return `${fd.label} can have at most ${fd.maxItems} entries.`;
return v.every(x => (fd.allowNull && x === null) || (typeof x === "number" && Number.isFinite(x) && x >= min && x <= max)) ? null
: `${fd.label} must contain only numbers from ${fmtNum(min, fd)} to ${fmtNum(max, fd)}.`;
}
}
return `${fd.label} has an unknown type.`;
}
// Build a clean copy that holds only known fields, or list every problem.
function validateData(raw) {
const errors = [], data = {};
for (const fd of FIELDS) {
let v = getPath(raw, fd.path);
if (v === undefined && fd.missingOk) v = structuredClone(fd.dflt); // added after files were already saved
const err = check(fd, v);
if (err) errors.push(err); else setPath(data, fd.path, Array.isArray(v) ? [...v] : v);
}
const awards = getPath(raw, "awards");
if (!Array.isArray(awards)) errors.push("The list of awards is missing.");
else if (awards.length > MAX_AWARDS) errors.push(`You can list at most ${MAX_AWARDS} awards.`);
else {
data.awards = awards.map((a, i) => {
const clean = {};
if (a === null || typeof a !== "object" || Array.isArray(a)) { errors.push(`Award ${i + 1} can't be read.`); return clean; }
for (const fd of AWARD_FIELDS) {
const err = check(fd, a[fd.path]);
if (err) errors.push(`Award ${i + 1}: ${err}`); else clean[fd.path] = a[fd.path];
}
return clean;
});
}
if (!errors.length) {
const s = data.school;
if (s.aidDate > s.termEnd) errors.push("The term must end after aid arrives (check the aid date and the last day of the term).");
if (s.forecastStart > s.termEnd) errors.push("The forecast must start before the term ends.");
}
return { errors, data };
}
function defaults() {
const P = CONFIG.plan;
let start = Engine.monday(todayIso());
if (start > CONFIG.term.end) start = Engine.monday(CONFIG.term.classesStart);
return {
profile: { yearInSchool: null, dependency: null, graduationTerm: null, graduationYear: null, graduationDate: null,
gpa: null, creditHours: null, semesterCredits: [], fullTimeRecent: null },
school: { termName: CONFIG.term.name, forecastStart: start, aidDate: CONFIG.term.classesStart,
termEnd: CONFIG.term.end, noPayWeeks: [] },
bill: { tuition: null, housing: null, meals: null, books: null, other: null },
payment: { mode: "plan", fullDue: P.springPayInFullDue, firstPayment: P.springFirstPayment, payments: P.payments,
dueDay: P.dueDay, fee: P.enrollmentFee, minBalance: P.minBalance,
dates: Engine.planDates(P.springFirstPayment, P.payments, P.dueDay) },
loans: { priorTotal: null, priorSub: null, subRoomOverride: null, unsubRoomOverride: null },
awards: [],
money: { cash: null, hours: null, wage: null, takeHome: null, safeMax: null,
hoursCeiling: CONFIG.product.hoursFlag, living: null, cushion: null },
payoff: { mode: "standard", years: null },
private: { rate: null, fee: null, years: null, graceMonths: null, capitalize: true },
future: { rates: [], fees: [] },
};
}
// A filled-in, fictional record used only by the Save/Open checks in test mode.
function example() {
const d = defaults();
Object.assign(d.profile, { yearInSchool: 2, dependency: "independent", graduationTerm: "spring", graduationYear: 2029,
graduationDate: "2029-05-07", gpa: 3.12, creditHours: 15, semesterCredits: [15, 15], fullTimeRecent: true });
d.school.forecastStart = "2026-11-09";
d.school.noPayWeeks = ["2026-12-21", "2026-12-28"];
Object.assign(d.bill, { tuition: 6800, housing: 4200.5, meals: 2633, books: 0, other: 157.25 });
Object.assign(d.loans, { priorTotal: 5500, priorSub: 3500, subRoomOverride: null, unsubRoomOverride: 2000 });
d.awards = [
{ name: "Example grant", type: "grant", amount: 3000, accepted: true, minGpa: null, minCredits: null, hasJob: false },
{ name: "Example scholarship", type: "scholarship", amount: 2500, accepted: true, minGpa: 3, minCredits: 12, hasJob: false },
{ name: "KEES", type: "kees", amount: 500, accepted: true, minGpa: null, minCredits: null, hasJob: false },
{ name: "Subsidized loan", type: "subsidized", amount: 2250, accepted: true, minGpa: null, minCredits: null, hasJob: false },
{ name: "Work-Study", type: "workstudy", amount: 1500, accepted: false, minGpa: null, minCredits: null, hasJob: false },
];
Object.assign(d.money, { cash: -42.17, hours: 10, wage: 12.5, takeHome: 114.38, safeMax: 15, hoursCeiling: 60, living: 240, cushion: 300 });
Object.assign(d.payoff, { mode: "years", years: 5 });
Object.assign(d.private, { rate: 10.25, fee: 1.5, years: 8, graceMonths: 9, capitalize: false }); // fictional quote
return d;
}
const serialize = data =>
JSON.stringify({ app: APP_ID, schemaVersion: VERSION, savedAt: new Date().toISOString(), data }, null, 2);
// Read a saved file's text. Returns { ok: true, data } or { ok: false, errors: [plain messages] }.
function parse(text) {
const fail = (...errors) => ({ ok: false, errors });
if (typeof text !== "string") return fail("The file can't be read.");
if (text.length > MAX_CHARS) return fail("This file is too large to be a Make It to May save file (over 1 MB).");
if (!text.trim()) return fail("The file is empty.");
let obj;
try { obj = JSON.parse(text); } catch { return fail("This file isn't valid JSON, so it can't be a Make It to May save file."); }
if (obj === null || typeof obj !== "object" || Array.isArray(obj) || obj.app !== APP_ID) {
return fail("This doesn't look like a Make It to May save file.");
}
if (!Number.isInteger(obj.schemaVersion) || obj.schemaVersion < 1) {
return fail("This save file has no version number, so it can't be read safely.");
}
if (obj.schemaVersion > VERSION) {
return fail(`This file was saved by a newer version of Make It to May (version ${obj.schemaVersion}). This page reads version ${VERSION}.`);
}
if (obj.data === null || typeof obj.data !== "object" || Array.isArray(obj.data)) return fail("This save file has no data in it.");
const { errors, data } = validateData(obj.data);
return errors.length ? fail(...errors) : { ok: true, data };
}
return { APP_ID, VERSION, MAX_CHARS, GROUPS, FIELDS, byPath, AWARD_FIELDS, AWARD_TYPES, newAward, isDate, todayIso,
getPath, setPath, check, validateData, defaults, example, serialize, parse };
})();
/* The current data plus the "unsaved" flag. Edits mark it unsaved; Save, Copy, Open and Paste clear it. */
function createStore(initial) {
const listeners = new Set();
const store = {
data: initial, dirty: false, status: "new", when: null, name: "",
on(fn) { listeners.add(fn); },
set(path, value) { Schema.setPath(store.data, path, value); store.touch(); },
touch() { store.dirty = true; emit(); },
markSaved(how) { store.dirty = false; store.status = how; store.when = new Date(); emit(); },
load(data, how, name = "") {
store.data = data; store.dirty = false; store.status = how; store.name = name; store.when = new Date(); emit();
},
};
const emit = () => listeners.forEach(fn => fn(store));
return store;
}
const FileIO = (() => {
const fileName = () => `make-it-to-may-${Schema.todayIso()}.json`;
// Save: hand the browser a file to download. Nothing is kept in the browser itself.
function download(store) {
const name = fileName();
const url = URL.createObjectURL(new Blob([Schema.serialize(store.data)], { type: "application/json" }));
const a = document.createElement("a");
a.href = url;
a.download = name;
a.hidden = true;
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10000);
store.markSaved("saved");
return name;
}
// Open or paste: check everything first. Current data changes only if the file is valid
// (and, when there are unsaved changes, only if the student confirms).
async function tryOpen(store, text, confirmReplace, how, name = "") {
const r = Schema.parse(text);
if (!r.ok) return r;
if (store.dirty && !(await confirmReplace())) return { ok: false, cancelled: true, errors: [] };
store.load(r.data, how, name);
return r;
}
// Warn before the page closes with unsaved changes.
const leaveGuard = store => event => {
if (!store.dirty) return undefined;
event.preventDefault();
event.returnValue = "";
return "";
};
return { fileName, download, tryOpen, leaveGuard };
})();
/* =====================================================================================
PLAIN-LANGUAGE TIPS: shown with a "?" next to any jargon.
===================================================================================== */
const GLOSSARY = (() => {
const tiers = CONFIG.standardTiers.map(([limit, months]) => `${months / 12} years under $${limit.toLocaleString("en-US")}`);
return {
dependency: { term: "dependency status", text: "Your status on the FAFSA. Independent students can borrow more in unsubsidized loans each year than dependent students." },
gpa: { term: "cumulative GPA", text: "Your grade point average across every term so far, on a 4.0 scale. KEES and many scholarships check it." },
creditHours: { term: "credit hours", text: "The credit hours you're enrolled in this term. 12 or more is full-time, which many awards require." },
disbursement: { term: "disbursement", text: "The day your aid is paid to your student account. If your aid is more than your bill, the extra comes to you as a refund." },
paymentPlan: { term: "payment plan", text: `Splitting your bill into monthly payments. UK's plan has ${CONFIG.plan.payments} payments a semester and a $${CONFIG.plan.enrollmentFee} fee. Not every school has one.` },
subsidized: { term: "subsidized loan", text: `A need-based federal student loan. The government pays the interest while you're in school at least half-time and for the ${CONFIG.loan.graceMonths}-month grace period after.` },
unsubsidized: { term: "unsubsidized loan", text: "A federal student loan that doesn't depend on need. Interest starts adding up the day it's paid out, even while you're in school." },
loanRoom: { term: "loan room", text: "How much more you can still borrow in federal loans this school year, under the yearly and lifetime limits." },
takeHome: { term: "take-home pay", text: "What actually lands in your bank account after taxes and other deductions. It's on your pay stub." },
cushion: { term: "emergency cushion", text: "Money you never want to dip below, for surprises like a car repair or a late paycheck. A week that ends at $0 doesn't count as covered." },
kees: { term: "KEES", text: "The Kentucky Educational Excellence Scholarship, earned in high school. KHEAA checks your GPA once a year, at the end of spring, to set next year's award." },
workstudy: { term: "Work-Study", text: "Federal Work-Study is paid as wages from a campus job. It is never taken off your bill; you earn it by working." },
grace: { term: "grace period", text: `The ${CONFIG.loan.graceMonths} months after you leave school before loan payments start.` },
originationFee: { term: "origination fee", text: `A fee taken out of each federal loan before you get it: ${(CONFIG.loan.fee * 100).toFixed(3)}% for loans first paid out by Sep 30, 2027.` },
standardPlan: { term: "standard plan", text: `Equal monthly payments. For loans made after July 1, 2026, the length depends on what you owe: ${tiers.join(", ")}, and ${CONFIG.standardTopMonths / 12} years above that.` },
gift: { term: "gift aid", text: "Grants, scholarships and KEES. You don't pay them back." },
privateLoan: { term: "private loan", text: "A loan from a bank or other lender, not the government. The rate depends on your credit, most need a cosigner, and there are no federal options for lowering or pausing payments. Use federal, state and UK aid first." },
};
})();
const Fmt = {
money(x, cents = false) {
if (typeof x !== "number" || !Number.isFinite(x)) return "—";
const r = cents ? Math.round(x * 100) / 100 : Math.round(x);
if (r === 0) return cents ? "$0.00" : "$0";
const s = Math.abs(r).toLocaleString("en-US", { minimumFractionDigits: cents ? 2 : 0, maximumFractionDigits: cents ? 2 : 0 });
return (r < 0 ? "−$" : "$") + s;
},
date(iso) {
return iso ? new Date(iso + "T00:00:00Z").toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" }) : "—";
},
monthYear(iso) {
return iso ? new Date(iso + "T00:00:00Z").toLocaleDateString("en-US", { month: "short", year: "numeric", timeZone: "UTC" }) : "—";
},
dateShort(iso) {
return iso ? new Date(iso + "T00:00:00Z").toLocaleDateString("en-US", { month: "short", day: "numeric", timeZone: "UTC" }) : "—";
},
};
/* =====================================================================================
INPUTS → ENGINE: turn what the student typed into the reference model's inputs, plus the
in-between numbers the page shows (bill, aid, gap, schedule, pay, loan room).
===================================================================================== */
const Inputs = (() => {
const { pyRound, pySum } = Engine;
const n0 = v => (typeof v === "number" ? v : 0);
const has = v => v !== null && v !== undefined;
const GIFT = new Set(["grant", "scholarship", "kees"]);
const LOAN = new Set(["subsidized", "unsubsidized"]);
const BILL = ["tuition", "housing", "meals", "books", "other"];
function derive(d) {
const missing = [], missingAt = [], warnings = [], notes = [];
// Each missing item also records the box that fixes it, so the page can link straight to it.
const need = (text, path) => { missing.push(text); missingAt.push(path); };
const p = d.profile, s = d.school, pay = d.payment, m = d.money, L = d.loans;
// 1. Gap = charges − grants, scholarships and KEES − loans after the origination fee. Work-Study never counts.
const charges = pyRound(pySum(BILL.map(k => n0(d.bill[k]))), 2);
if (BILL.every(k => !has(d.bill[k]))) need("Your bill (at least tuition and fees)", "bill.tuition");
const accepted = d.awards.filter(a => a.accepted);
const gifts = pyRound(pySum(accepted.filter(a => GIFT.has(a.type)).map(a => n0(a.amount))), 2);
const loansGross = accepted.filter(a => LOAN.has(a.type)).map(a => n0(a.amount));
const loansNet = pyRound(pySum(loansGross.map(g => Engine.netOfFee(g))), 2);
const gap = Engine.gap(charges, gifts, loansGross);
d.awards.forEach((a, i) => {
if (!has(a.amount)) warnings.push(`${a.name || "Award " + (i + 1)} has no amount yet, so it counts as $0.`);
});
if (d.awards.some(a => !a.accepted && LOAN.has(a.type))) {
notes.push("Loans you haven't accepted aren't counted toward your bill. If one is what myUK offers you, enter it under \"loan you can still accept this year\".");
}
// 2. Federal loan room left this year: what the student entered from myUK, else the federal limits
// (year total = 2 × this term's accepted loans, as in the reference model).
const subTerm = pySum(accepted.filter(a => a.type === "subsidized").map(a => n0(a.amount)));
const unsubTerm = pySum(accepted.filter(a => a.type === "unsubsidized").map(a => n0(a.amount)));
let limits = null;
if (has(p.yearInSchool) && has(p.dependency)) {
limits = Engine.loanRoom(p.dependency, Math.min(p.yearInSchool, 3), 2 * subTerm, 2 * unsubTerm, n0(L.priorTotal), n0(L.priorSub));
}
const subRoom = has(L.subRoomOverride) ? L.subRoomOverride : limits ? limits.sub_room : null;
const unsubRoom = has(L.unsubRoomOverride) ? L.unsubRoomOverride : limits ? limits.unsub_room : null;
if (subRoom === null || unsubRoom === null) need("Year in school and FAFSA dependency status (they set your loan limits)", has(p.yearInSchool) ? "profile.dependency" : "profile.yearInSchool");
if (limits && subRoom !== null && unsubRoom !== null && subRoom + unsubRoom > limits.sub_room + limits.unsub_room) {
warnings.push(`The loan amounts you entered add up to more than the federal limits leave for your year (${Fmt.money(limits.sub_room + limits.unsub_room)}).`);
}
// 3. Pay: take-home ratio k = take-home ÷ (hours × wage); 1 ("before taxes") without a pay stub.
if (!has(m.cash)) need("Cash on hand", "money.cash");
if (!has(m.hours)) need("Job hours per week", "money.hours");
const hours = n0(m.hours);
if (hours > 0 && !has(m.wage)) need("Hourly wage", "money.wage");
const wage = n0(m.wage);
let k = 1, afterTax = false;
if (has(m.takeHome) && hours * wage > 0) { k = m.takeHome / (hours * wage); afterTax = true; }
if (k > 1) warnings.push("Your take-home pay is more than your pay before taxes. Check the pay stub numbers.");
if (!has(m.living)) need("Living costs per month", "money.living");
if (!has(m.cushion)) need("Emergency cushion", "money.cushion");
if (!has(m.safeMax)) need("Most hours you can work", "money.safeMax");
else {
if (m.safeMax < hours) warnings.push("Your safe maximum is lower than the hours you already work, so the planner won't suggest more hours.");
if (m.safeMax > CONFIG.product.hoursFlag) warnings.push(`More than ${CONFIG.product.hoursFlag} hours a week on top of classes is nearly impossible.`);
else if (m.safeMax > CONFIG.product.hoursWarn) warnings.push(`More than ${CONFIG.product.hoursWarn} hours a week is a full-time job on top of classes.`);
}
// 4. Graduation sets when unsubsidized interest stops building up and payments start.
if (!has(p.graduationDate)) need("Graduation date", "profile.graduationDate");
if (d.payoff.mode === "years" && !has(d.payoff.years)) need("Years to pay off your loans", "payoff.years");
const graceEnd = has(p.graduationDate) ? Engine.graceEndFrom(p.graduationDate) : null;
if (has(p.creditHours) && p.creditHours < CONFIG.kees.fullTimeHours) {
warnings.push("Under 12 credit hours, KEES is prorated, scholarships with a 12-hour rule are at risk, and Pell and federal loan limits may be lower. Talk to UK Financial Aid before changing your schedule.");
}
// 5. When the bill is due.
const plan = pay.mode === "plan";
const due = plan ? [...pay.dates].sort() : [pay.fullDue];
if (plan && !due.length) need("Payment plan dates", "payment.dates");
if (plan && gap > 0 && gap < pay.minBalance) {
warnings.push(`Payment plans need a balance of at least ${Fmt.money(pay.minBalance)}. Yours is ${Fmt.money(gap)}, so you may have to pay in full.`);
}
if (due.some(x => x < s.forecastStart)) notes.push(`Payments due before ${Fmt.date(s.forecastStart)} are treated as already paid.`);
if (due.some(x => x > s.termEnd)) warnings.push(`A payment is due after the term ends (${Fmt.date(s.termEnd)}), so the forecast leaves it out.`);
// Late in the term (the forecast starts on this week's Monday by default), the aid date can fall before the forecast:
// then a new loan has no week to arrive in, and the planner would wrongly say even all federal loans can't help.
if (has(s.forecastStart) && has(s.aidDate) && Engine.monday(s.forecastStart) > Engine.monday(s.aidDate)) {
warnings.push(`Your forecast starts after your aid date (${Fmt.date(s.aidDate)}), so a new loan can't show up in it. Set the aid date to when a new loan would actually reach you, or move the forecast start back. Both are under "Your bill", School dates.`);
}
const engineCase = {
gap, cash0: n0(m.cash), hours, wage, k, living: n0(m.living), cushion: n0(m.cushion), safe_max: n0(m.safeMax), due,
sub_room: n0(subRoom), unsub_room: n0(unsubRoom), grace_end: graceEnd,
start: s.forecastStart, end: s.termEnd, disb: s.aidDate, no_pay_weeks: [...s.noPayWeeks],
};
if (plan) engineCase.plan_fee = pay.fee;
return {
ready: missing.length === 0, missing, missingAt, warnings, notes, case: engineCase,
charges, gifts, loansNet, gap, schedule: Engine.billsByDate(engineCase), plan, fee: plan ? pay.fee : 0,
k, afterTax, weeklyPay: pyRound(hours * wage * k, 2), weeklyLiving: pyRound(n0(m.living) * 12 / 52, 2),
room: { sub: subRoom, unsub: unsubRoom, fromMyUK: has(L.subRoomOverride) || has(L.unsubRoomOverride) }, limits, graceEnd,
};
}
// Four-year inputs (spec in reference_model.py): one entry per academic year from this one through
// graduation. Accepted loans carry forward at 2 × this term; this term's recommended new loan (gross)
// repeats each spring under "this plan". Rate and fee default to the 2026–27 values every year.
const academicYear = iso => +iso.slice(0, 4) + (+iso.slice(5, 7) >= 7 ? 1 : 0); // named by the year it ends
const fallStart = y => CONFIG.term.fallStarts[y] ?? `${y}-${CONFIG.term.fallStartEstimate}`;
function fourYearInput(d, extraSubGross, extraUnsubGross) {
const p = d.profile, L = d.loans;
if (!has(p.yearInSchool) || !has(p.dependency) || !has(p.graduationDate)) return null;
const accepted = d.awards.filter(a => a.accepted);
const subYear = 2 * pySum(accepted.filter(a => a.type === "subsidized").map(a => n0(a.amount)));
const unsubYear = 2 * pySum(accepted.filter(a => a.type === "unsubsidized").map(a => n0(a.amount)));
const first = academicYear(d.school.termEnd);
const n = Math.max(1, academicYear(p.graduationDate) - first + 1);
const fallGrad = +p.graduationDate.slice(5, 7) >= 7;
// Later years' rate and fee: what the student entered (percent), else the 2026–27 values. Year 0 is set.
const pick = (list, i, dflt) => (i > 0 && has(list[i]) ? list[i] / 100 : dflt);
const years = [];
for (let i = 0; i < n; i++) {
years.push({ level: Math.min(p.yearInSchool + i, 3), fall: fallStart(first - 1 + i),
spring: fallGrad && i === n - 1 ? null : Engine.addMonths(d.school.aidDate, 12 * i),
rate: pick(d.future.rates, i, CONFIG.loan.rate), fee: pick(d.future.fees, i, CONFIG.loan.fee),
accepted_sub: subYear, accepted_unsub: unsubYear });
}
const priorSub = n0(L.priorSub), priorUnsub = Math.max(0, n0(L.priorTotal) - priorSub), priorDate = fallStart(first - 2);
const prior = [];
if (priorSub > 0) prior.push({ gross: priorSub, sub: true, rate: CONFIG.loan.rate, fee: CONFIG.loan.fee, disb: priorDate });
if (priorUnsub > 0) prior.push({ gross: priorUnsub, sub: false, rate: CONFIG.loan.rate, fee: CONFIG.loan.fee, disb: priorDate });
return { dependency: p.dependency, grace_end: Engine.graceEndFrom(p.graduationDate),
own_years: d.payoff.mode === "years" && has(d.payoff.years) ? d.payoff.years : null,
prior, extra_sub: extraSubGross, extra_unsub: extraUnsubGross, years };
}
// "Aid you're protecting" (Stage 5): each award's rule and status at the current GPA and credit load,
// where the student sits on the KEES ladder, and what dropping below 12 credit hours would cost this term.
function completedTerms(year, termEnd) {
if (!has(year)) return null;
const isSpring = +termEnd.slice(5, 7) < 7;
return 2 * (year - 1) + (isSpring ? 1 : 0); // fall/spring terms finished before this one
}
function aidStatus(d) {
const p = d.profile, accepted = d.awards.filter(a => a.accepted);
const gpaText = g => g.toFixed(2);
const rows = accepted.filter(a => a.type !== "kees" && (has(a.minGpa) || has(a.minCredits))).map(a => {
const rules = [], problems = [], unknown = [];
if (has(a.minGpa)) {
rules.push(`a ${gpaText(a.minGpa)} GPA`);
if (!has(p.gpa)) unknown.push("your GPA");
else if (p.gpa < a.minGpa) problems.push(`your GPA is ${gpaText(p.gpa)}`);
}
if (has(a.minCredits)) {
rules.push(`${a.minCredits}+ credit hours a term`);
if (!has(p.creditHours)) unknown.push("your credit hours");
else if (p.creditHours < a.minCredits) problems.push(`you're taking ${p.creditHours} credit hours`);
}
const status = problems.length ? "risk" : unknown.length ? "unknown" : "safe";
const said = problems.join(" and ");
const detail = problems.length ? said.charAt(0).toUpperCase() + said.slice(1) + "." : unknown.length ? `Add ${unknown.join(" and ")} to check.` : "You meet it now.";
return { name: a.name || "Unnamed award", perYear: pyRound(2 * n0(a.amount), 2), rule: `Keep ${rules.join(" and ")}`, status, detail };
});
let kees = null;
const keesAwards = accepted.filter(a => a.type === "kees");
if (keesAwards.length) {
const perTerm = pySum(keesAwards.map(a => n0(a.amount)));
const assumed = !p.semesterCredits.length;
const done = completedTerms(p.yearInSchool, d.school.termEnd);
const past = assumed ? (done === null ? null : CONFIG.product.creditsPerSemester * done) : pySum(p.semesterCredits);
// UK's on-track table: earned credit hours by the end of spring (past + this term), by year in school.
const term = n0(p.creditHours);
const earned = past === null ? null : past + term;
const need = has(p.yearInSchool) ? (CONFIG.kees.onTrackHours[Math.min(p.yearInSchool, 4)] ?? null) : null;
const onTrack = has(p.yearInSchool) && earned !== null ? Engine.keesOnTrack(p.yearInSchool, earned) : null;
const K = CONFIG.kees;
// Which ladder row applies: 0 = 3.0+, 1 = 2.5–2.99 on track, 2 = not on track + full-time recently, 3 = otherwise, 4 = below 2.5.
let row = null, share = null;
if (has(p.gpa)) {
if (p.gpa >= K.fullGpa) row = 0;
else if (p.gpa >= K.minGpa) row = onTrack === true ? 1 : onTrack === false ? (p.fullTimeRecent === true ? 2 : p.fullTimeRecent === false ? 3 : "2or3") : "1to3";
else row = 4;
if (typeof row === "number") share = [1, 1, K.partialShare, 0, 0][row];
// keesNextYear() (tested against the reference model) must agree with the ladder row.
if (typeof row === "number" && share !== Engine.keesNextYear(p.gpa, onTrack === true, p.fullTimeRecent === true)) share = null;
}
kees = { perTerm, perYear: pyRound(2 * perTerm, 2), past, assumed, done, term, earned, need, year: p.yearInSchool, onTrack, row, share };
}
const pyAwards = accepted.map(a => ({ type: a.type, amount: n0(a.amount), accepted: true, min_gpa: a.minGpa, min_credits: a.minCredits }));
const under = [11, 9, 6].map(hours => {
const total = Engine.under12Cost(pyAwards, hours);
const rules = pyRound(pySum(pyAwards.filter(a => has(a.min_credits) && hours < a.min_credits).map(a => a.amount)), 2);
return { hours, total, rules, kees: pyRound(total - rules, 2) };
});
return { rows, kees, under, total: Engine.aidAtRisk(pyAwards) };
}
return { derive, fourYearInput, aidStatus };
})();
/* The fictional sample student ("Try a sample student"): test case "Jordan (UK plan)" in reference_model.py.
Charges and awards are made-up splits that add up to the test case's totals ($15,990 and $10,365). */
const Sample = {
jordan() {
const d = Schema.defaults();
Object.assign(d.profile, { yearInSchool: 1, dependency: "independent", gpa: 3.2, creditHours: 15, graduationTerm: "spring",
graduationYear: 2030, graduationDate: "2030-05-07", semesterCredits: [15], fullTimeRecent: true });
Object.assign(d.school, { termName: "Spring 2027", forecastStart: "2027-01-04", aidDate: "2027-01-11", termEnd: "2027-05-07", noPayWeeks: [] });
Object.assign(d.bill, { tuition: 6800, housing: 5923, meals: 2633, books: 0, other: 634 });
Object.assign(d.payment, { mode: "plan", fullDue: "2027-01-22", firstPayment: "2027-01-11", payments: 4, dueDay: 22, fee: 50,
minBalance: 500, dates: Engine.planDates("2027-01-11", 4, 22) });
Object.assign(d.loans, { priorTotal: 0, priorSub: 0, subRoomOverride: null, unsubRoomOverride: null });
const award = (name, type, amount, rules = {}) =>
({ name, type, amount, accepted: true, minGpa: null, minCredits: null, hasJob: false, ...rules });
d.awards = [
award("Federal Pell Grant", "grant", 3500),
award("State grant", "grant", 1900),
award("University scholarship", "scholarship", 4215, { minGpa: 3, minCredits: 12 }),
award("KEES", "kees", 750),
award("Direct Subsidized Loan", "subsidized", 1750),
];
Object.assign(d.money, { cash: 150, hours: 8, wage: 12, takeHome: 89.28, safeMax: 12, hoursCeiling: CONFIG.product.hoursFlag,
living: 160, cushion: 500 });
d.payoff = { mode: "standard", years: null };
return d;
},
/* The other five test cases in reference_model.py, one per kind of answer (Brian, Nov 12, 2026). From the model:
bill after aid (charges, gift aid, loans), cash, hours, wage, take-home rate, living costs, cushion, safe max,
due dates, loan room (year and dependency from ROOM_CHECKS), payments start (graduation + 6 months), Casey's
November start and no-pay weeks. Made up (fictional, like Jordan's): how each bill and each gift total splits,
award names, GPA, credit hours, earned credits. Those change only "Aid you're protecting" and the four-year view. */
build(s) {
const d = Schema.defaults();
Object.assign(d.profile, { creditHours: 15, graduationTerm: "spring", fullTimeRecent: true, ...s.profile,
graduationDate: `${s.profile.graduationYear}-05-07` });
Object.assign(d.school, { termName: "Spring 2027", forecastStart: "2027-01-04", aidDate: "2027-01-11", termEnd: "2027-05-07", noPayWeeks: [] },
s.school || {});
Object.assign(d.bill, { tuition: 6800, books: 0, ...s.bill });
Object.assign(d.payment, s.payment);
if (s.payment.mode === "plan") d.payment.dates = Engine.planDates(s.payment.firstPayment, s.payment.payments, s.payment.dueDay);
Object.assign(d.loans, { priorTotal: 0, priorSub: 0, subRoomOverride: null, unsubRoomOverride: null });
const award = (name, type, amount, rules = {}) =>
({ name, type, amount, accepted: true, minGpa: null, minCredits: null, hasJob: false, ...rules });
d.awards = s.awards.map(a => award(...a));
Object.assign(d.money, { hoursCeiling: CONFIG.product.hoursFlag, ...s.money });
d.payoff = { mode: "standard", years: null };
return d;
},
// A pay-in-full bill due Jan 15 (the test cases' date, not UK's calendar).
payInFull: { mode: "full", fullDue: "2027-01-15" },
};
// The picker's list: one line on the situation and a tag for what the planner finds. No pronouns.
Sample.LIST = [
{ key: "maya", name: "Maya", testCase: "Maya", tone: "good", tag: "Covered",
desc: "1st year, dependent. $2,600 saved and a 10-hour-a-week job.",
data: () => Sample.build({
profile: { yearInSchool: 1, dependency: "dependent", gpa: 3.6, graduationYear: 2030, semesterCredits: [15] },
bill: { housing: 5200, meals: 2400, other: 600 }, // $15,000
payment: Sample.payInFull,
awards: [["Federal Pell Grant", "grant", 2500], ["State grant", "grant", 2000], // gift aid $11,200
["University scholarship", "scholarship", 6000, { minGpa: 3, minCredits: 12 }], ["KEES", "kees", 700],
["Direct Subsidized Loan", "subsidized", 1750]],
money: { cash: 2600, hours: 10, wage: 11, takeHome: 101.2, safeMax: 12, living: 200, cushion: 300 } }) },
{ key: "dee", name: "Dee", testCase: "Dee", tone: "fix", tag: "Fix: subsidized loan",
desc: "2nd year, dependent. Works 6 hours a week and still has subsidized loan room.",
data: () => Sample.build({
profile: { yearInSchool: 2, dependency: "dependent", gpa: 2.9, graduationYear: 2029, semesterCredits: [15, 15, 15] },
bill: { housing: 4900, meals: 2200, other: 600 }, // $14,500
payment: Sample.payInFull,
awards: [["Federal Pell Grant", "grant", 3000], ["State grant", "grant", 1500], // gift aid $11,000
["University scholarship", "scholarship", 5900, { minGpa: 3, minCredits: 12 }], ["KEES", "kees", 600],
["Direct Subsidized Loan", "subsidized", 1250]],
money: { cash: 1300, hours: 6, wage: 11.5, takeHome: 62.1, safeMax: 10, living: 250, cushion: 400 } }) },
{ key: "sam", name: "Sam", testCase: "Sam", tone: "fix", tag: "Fix: 4 more hours a week",
desc: "3rd year, dependent. On a 4-payment plan, with no pay stub (pay before taxes).",
data: () => Sample.build({
profile: { yearInSchool: 3, dependency: "dependent", gpa: 3.4, graduationYear: 2028, semesterCredits: [15, 15, 15, 15, 15] },
bill: { housing: 4600, meals: 1900, other: 500 }, // $13,800
payment: { mode: "plan", firstPayment: "2027-01-15", payments: 4, dueDay: 15, fee: 0 },
awards: [["Federal Pell Grant", "grant", 2000], ["State grant", "grant", 1300], // gift aid $9,800
["University scholarship", "scholarship", 6000, { minGpa: 2.5, minCredits: 12 }], ["KEES", "kees", 500],
["Direct Subsidized Loan", "subsidized", 2750]],
money: { cash: 400, hours: 10, wage: 13, takeHome: null, safeMax: 16, living: 300, cushion: 300 } }) },
{ key: "jordan", name: "Jordan", testCase: "Jordan (UK plan)", tone: "fix", tag: "Fix: unsubsidized loan",
desc: "1st year, independent, on UK's payment plan.",
data: () => Sample.jordan() },
{ key: "casey", name: "Casey", testCase: "Casey", tone: "fix", tag: "Fix: more hours and a loan",
desc: "2nd year, dependent. No paychecks over winter break, and the first payment is due before aid arrives.",
data: () => Sample.build({
profile: { yearInSchool: 2, dependency: "dependent", gpa: 3.1, graduationYear: 2029, semesterCredits: [15, 15, 15] },
school: { forecastStart: "2026-11-09", noPayWeeks: ["2026-12-14", "2026-12-21", "2026-12-28", "2027-01-04"] },
bill: { housing: 5400, meals: 2600, other: 800 }, // $15,600
payment: { mode: "plan", firstPayment: "2027-01-04", payments: 4, dueDay: 22, fee: 50 },
awards: [["Federal Pell Grant", "grant", 2500], ["State grant", "grant", 1600], // gift aid $10,900
["University scholarship", "scholarship", 6200, { minGpa: 3, minCredits: 12 }], ["KEES", "kees", 600],
["Direct Subsidized Loan", "subsidized", 2250]],
money: { cash: 600, hours: 8, wage: 12, takeHome: 88.32, safeMax: 14, living: 200, cushion: 300 } }) },
{ key: "riley", name: "Riley", testCase: "Riley", tone: "bad", tag: "Short after all federal loans",
desc: "1st year, independent. Already accepted the federal loan maximum.",
data: () => Sample.build({
profile: { yearInSchool: 1, dependency: "independent", gpa: 3.3, graduationYear: 2030, semesterCredits: [15] },
bill: { housing: 5923, meals: 2633, other: 844 }, // $16,200
payment: Sample.payInFull,
awards: [["Federal Pell Grant", "grant", 3600], ["State grant", "grant", 2200], // gift aid $8,000
["University scholarship", "scholarship", 1500], ["KEES", "kees", 700],
["Direct Subsidized Loan", "subsidized", 1750], ["Direct Unsubsidized Loan", "unsubsidized", 3000]],
money: { cash: 400, hours: 12, wage: 12, takeHome: 133.92, safeMax: 12, living: 200, cushion: 300 } }) },
];
Sample.byKey = key => Sample.LIST.find(s => s.key === key) || null;
/* =====================================================================================
RESULTS: the headline answer, the tradeoff line and the three option cards.
Every number comes from the engine (solve, options, forecast); this part only words it.
===================================================================================== */
const Results = (() => {
const FEE = CONFIG.loan.fee;
const gross = net => (net > 0 ? Math.ceil(net / (1 - FEE)) : 0); // amount to accept, as in loan_cost()
const cap = room => Math.floor(room * (1 - FEE) * 100) / 100; // most cash a loan room can deliver
function compute(d) {
const inputs = Inputs.derive(d);
if (!inputs.ready) return { ready: false, inputs };
const c = inputs.case, rec = Engine.solve(c);
const beyond = rec.state === "short_beyond_limits";
// The student's own payoff plan: their own years, or the standard term for the total they'd owe under this plan.
// Short beyond limits, "this plan" borrows all remaining room (Nov 12, 2026; before, only the subsidized part).
const extraSub = rec.state === "fixed_sub" ? gross(rec.sub_net) : (rec.sub_net ? c.sub_room : 0);
let fy = Inputs.fourYearInput(d, extraSub, beyond ? c.unsub_room : gross(rec.unsub_net ?? 0));
let four = Engine.fourYear(fy);
const planMonths = four.this_plan.months;
const opts = Engine.options(c, d.money.hoursCeiling, planMonths);
// Private loan, a last resort (Brian, Nov 12, 2026): only with a rate a lender quoted, and only for what
// federal loans and the safe max can't cover (P), or as the same money as this plan's new loans when
// extra hours within the safe max can't close the gap (the "private loan instead" column).
const pt = privateTerms(d);
let priv = null;
if (pt) {
const P = beyond ? (opts.private_net ?? 0) : 0;
const F = beyond ? Engine.pyRound(cap(c.sub_room) + cap(c.unsub_room), 2) : Engine.pyRound((rec.sub_net ?? 0) + (rec.unsub_net ?? 0), 2);
const neCash = opts.safe_hours_alone === null ? Engine.pyRound(F + P, 2) : 0;
if (P > 0 || neCash > 0) {
fy = { ...fy, private: { rate: pt.rate, fee: pt.fee, months: pt.years ? pt.years * 12 : null, capitalize: pt.capitalize,
grace_end: pt.graceEnd, cash: { this_plan: P, nothing_extra: neCash } } };
four = Engine.fourYear(fy);
}
const months = pt.years ? pt.years * 12 : planMonths;
priv = { ...pt, months, P, F, neCash,
cost: P > 0 ? Engine.privateCost(P, c.disb, pt.graceEnd, pt.rate, pt.fee, months, pt.capitalize) : null };
}
// How short each plan leaves you each spring, after working up to the safe max at most. The full offer is the
// federal maximum, which can be more than the myUK amounts the student typed in.
const safeRoom = Math.max(0, c.safe_max - c.hours);
const fullShort = !beyond ? 0 : !(inputs.room.fromMyUK && inputs.limits) ? rec.short_after_all
: Engine.shortfall(Engine.forecast(c, safeRoom, cap(inputs.limits.sub_room) + cap(inputs.limits.unsub_room)), c.cushion, c.disb)[0];
const shorts = {
full_offer: fullShort,
this_plan: beyond && !(priv && priv.P > 0) ? rec.short_after_all : 0,
nothing_extra: priv && priv.neCash > 0 ? 0 : (opts.nothing_extra_short ?? 0),
};
const aid = Engine.aidAtRisk(d.awards.map(a => ({ type: a.type, amount: a.amount ?? 0, accepted: a.accepted,
min_gpa: a.minGpa, min_credits: a.minCredits })));
const base = Engine.forecastDetail(c);
// The chart's second line (the recommendation, a picked card or the sliders' mix) is drawn by the page's
// Explore code (scenario / applyPick), so only "if nothing changes" is built here.
return { ready: true, inputs, d, c, rec, opts, aid, planMonths, ownYears: fy.own_years, fy, four, base, priv, shorts };
}
// The private-loan terms the student entered, or null without a quoted rate (percent inputs → decimals).
function privateTerms(d) {
const p = d.private;
if (!p || p.rate === null || p.rate === undefined || !d.profile.graduationDate) return null;
const graceMonths = p.graceMonths ?? CONFIG.privateLoan.graceMonths;
return { rate: p.rate / 100, fee: (p.fee ?? 0) / 100, years: p.years ?? null, graceMonths, capitalize: p.capitalize !== false,
graceEnd: Engine.addMonths(d.profile.graduationDate, graceMonths) };
}
const hrs = x => (Math.round(x * 2) / 2).toLocaleString("en-US");
const week = iso => `the week of ${Fmt.dateShort(iso)}`;
const fastYears = () => CONFIG.product.fastPayoffMonths / 12;
function planName(R) {
const years = R.planMonths / 12;
return R.ownYears ? `your own ${years}-year plan` : `the ${years}-year standard plan`;
}
const loanPhrase = (g, net, kind) => `${Fmt.money(g)} ${kind} (${Fmt.money(net)} after the fee)`;
const pct = x => `${+(x * 100).toFixed(3)}%`; // a decimal rate as the percent the student typed
// The one-sentence answer, plus at most two follow-up lines.
function headline(R) {
const { rec, c, opts, d } = R, r = opts.recommended;
const shortBy = `You'll drop below your ${Fmt.money(c.cushion)} cushion ${week(rec.run_out_week)}, about ${Fmt.money(rec.S)} short.`;
const cost = r ? `It costs about ${Fmt.money(r.fast.cost)} in interest and fees if you pay it off over ${fastYears()} years once payments start.` : "";
const subUsed = rec.state !== "fixed_sub" && rec.sub_net > 0;
const subLead = subUsed ? `accept your remaining ${Fmt.money(c.sub_room)} in subsidized loans and ` : "";
const lines = [];
let main;
switch (rec.state) {
case "covered":
main = `You're covered through ${Fmt.date(c.end)} with ${Fmt.money(rec.spare)} to spare. Your tightest week is ${week(rec.tightest_week)}, at ${Fmt.money(rec.min_cash)}.`;
lines.push(`"To spare" is your lowest week minus your ${Fmt.money(c.cushion)} cushion.`);
break;
case "fixed_sub":
main = `${shortBy} Cheapest fix: accept ${loanPhrase(gross(rec.sub_net), rec.sub_net, "more in subsidized loans")}. Nothing accrues while you're in school; ${cost.charAt(0).toLowerCase() + cost.slice(1)}`;
break;
case "fixed_hours": {
const total = c.hours + rec.extra_hours;
main = `${shortBy} Cheapest fix: ${subLead}work ${hrs(rec.extra_hours)} more hours a week (${hrs(total)} total).${subUsed ? "" : " No borrowing."}`;
const ws = d.awards.some(a => a.accepted && a.type === "workstudy" && !a.hasJob);
if (ws) lines.push("You accepted Work-Study but don't have a Work-Study job yet. A Work-Study job could supply these hours.");
break;
}
case "fixed_unsub": {
main = `${shortBy} Cheapest fix: ${subLead}borrow ${loanPhrase(gross(rec.unsub_net), rec.unsub_net, "unsubsidized")}. ${cost}`;
const smaller = rec.unsub_if_work_to_max;
if (smaller !== undefined && smaller !== null && smaller < rec.unsub_net) {
lines.push(`If you also work up to your safe max (${hrs(c.safe_max)} hours a week), the loan drops to ${Fmt.money(gross(smaller))} (${Fmt.money(smaller)} after the fee).`);
}
break;
}
case "fixed_mix": {
const total = c.hours + rec.extra_hours;
main = `${shortBy} Cheapest fix: work ${hrs(rec.extra_hours)} more hours a week (${hrs(total)} total) and ${subLead}borrow ${loanPhrase(gross(rec.unsub_net), rec.unsub_net, "unsubsidized")}. ${cost}`;
lines.push(`Or borrow all ${Fmt.money(gross(rec.alt_unsub_net))} of your remaining unsubsidized room and work ${hrs(rec.alt_extra_hours)} more hours a week instead.`);
break;
}
default: {
const today = c.start, due = [...c.due].sort().find(x => x >= today) || c.due[0];
main = `You're ${Fmt.money(rec.short_after_all)} short even after working up to your safe max and borrowing your remaining federal loan room. Contact UK Financial Aid about emergency aid before ${Fmt.date(due)}.`;
lines.push(`Ask them about UK's own loans too: the ${CONFIG.privateLoan.ukLoans.map(u => u.name).join(" and the ")}.`);
const pv = R.priv;
if (pv && pv.cost) {
const got = pv.fee > 0 ? ` (${Fmt.money(pv.P)} after its fee)` : "";
lines.push(`Last resort: a private loan of ${Fmt.money(pv.cost.gross)}${got} at the ${pct(pv.rate)} you were quoted would cover the rest. It would cost about ${Fmt.money(pv.cost.cost)} in interest and fees over ${pv.months / 12} years. Most private loans need a cosigner unless you have a good credit history.`);
} else if (!pv) {
lines.push("A private loan is the last resort. If a lender quotes you a rate, enter it under Your aid (Private loan) to see what covering the rest would cost.");
}
}
}
if (rec.pre_aid_negative_week) {
lines.push(`Heads up: your cash goes below $0 ${week(rec.pre_aid_negative_week)}, before your aid arrives. Those weeks aren't counted toward your cushion because no loan or extra hours reach them in time.`);
}
return { main, lines };
}
// The answer at a glance: the same numbers as the headline, as two tiles (problem, then fix). Display only.
function summary(R) {
const { rec, c } = R;
const short = { tone: "bad", icon: "alert", label: "Short", figure: Fmt.money(rec.S),
sub: `below your ${Fmt.money(c.cushion)} cushion, starting ${week(rec.run_out_week)}` };
const subUsed = rec.state !== "fixed_sub" && rec.sub_net > 0;
const plusSub = subUsed ? `, plus your remaining ${Fmt.money(c.sub_room)} subsidized` : "";
const fix = (figure, sub, words = false) => ({ tone: "fix", icon: "arrow", label: "Cheapest fix", figure, sub, words });
switch (rec.state) {
case "covered":
return { tone: "good", tiles: [
{ tone: "good", icon: "check", label: "Covered", figure: Fmt.money(rec.spare), sub: `to spare through ${Fmt.dateShort(c.end)}, above your cushion` },
{ tone: "plain", icon: "calendar", label: "Tightest week", figure: Fmt.money(rec.min_cash), sub: week(rec.tightest_week) }] };
case "fixed_sub":
return { tone: "bad", tiles: [short, fix(Fmt.money(gross(rec.sub_net)), "more in subsidized loans")] };
case "fixed_hours":
return { tone: "bad", tiles: [short, fix(`+${hrs(rec.extra_hours)} hours`, `a week (${hrs(c.hours + rec.extra_hours)} total)${subUsed ? plusSub : ", no borrowing"}`, true)] };
case "fixed_unsub":
return { tone: "bad", tiles: [short, fix(Fmt.money(gross(rec.unsub_net)), `unsubsidized loan${plusSub}`)] };
case "fixed_mix":
return { tone: "bad", tiles: [short, fix(Fmt.money(gross(rec.unsub_net)), `unsubsidized, and ${hrs(rec.extra_hours)} more hours a week${plusSub}`)] };
default: {
const due = [...c.due].sort().find(x => x >= c.start) || c.due[0];
return { tone: "bad", tiles: [
{ tone: "bad", icon: "alert", label: "Short after all federal loans", figure: Fmt.money(rec.short_after_all), sub: "even working up to your safe max" },
{ tone: "fix", icon: "arrow", label: "Next step", figure: "Contact UK Financial Aid", words: true, sub: `about emergency aid, before ${Fmt.dateShort(due)}` }] };
}
}
}
function tradeoff(R) {
const aidPart = R.aid > 0 ? `${Fmt.money(R.aid)} a year of your aid depends on keeping your GPA` : "";
const { rec, opts } = R, r = opts.recommended;
const tail = aidPart ? `, while ${aidPart}.` : ".";
if ((rec.state === "fixed_unsub" || rec.state === "fixed_mix") && r && r.V_plan !== null && rec.tradeoff_hours) {
return `Working about ${hrs(rec.tradeoff_hours)} more hours a week instead is worth about ${Fmt.money(r.V_plan, true)} an hour in interest and fees saved${tail}`;
}
if (rec.state === "fixed_hours" && opts.borrow && opts.borrow.V_plan !== null) {
return `Borrowing instead would cost about ${Fmt.money(opts.borrow.plan.cost)} in interest and fees, about ${Fmt.money(opts.borrow.V_plan, true)} for each hour you'd skip${tail}`;
}
return aidPart ? aidPart.charAt(0).toUpperCase() + aidPart.slice(1) + "." : "";
}
return { compute, headline, summary, tradeoff, planName, gross, hrs, week, pct };
})();
/* =====================================================================================
WEEKLY CASH CHART: inline SVG, no libraries. Colors are the validated reference palette
(slot 1 blue = with the fix, slot 2 orange = if nothing changes; both pass every check in
light and dark). Hover or arrow keys show a readout; the table below has every number.
===================================================================================== */
const Chart = (() => {
const NS = "http://www.w3.org/2000/svg";
function s(tag, attrs = {}, ...kids) {
const n = document.createElementNS(NS, tag);
for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
for (const k of kids) if (k != null) n.append(k);
return n;
}
function h(tag, attrs = {}, ...kids) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") n.className = v; else if (k === "text") n.textContent = v; else n.setAttribute(k, v);
}
for (const k of kids) if (k != null) n.append(k);
return n;
}
function niceTicks(lo, hi, count = 5) {
const span = hi - lo || 1, raw = span / count, mag = 10 ** Math.floor(Math.log10(raw)), err = raw / mag;
const step = (err >= 7.5 ? 10 : err >= 3.5 ? 5 : err >= 1.5 ? 2 : 1) * mag;
const start = Math.floor(lo / step) * step, end = Math.ceil(hi / step) * step, ticks = [];
for (let v = start; v <= end + step / 2; v += step) ticks.push(Math.round(v));
return { ticks, lo: start, hi: end };
}
function draw(root, R) {
const base = R.base, fix = R.fix, c = R.c, rec = R.rec;
const series = fix
? [{ label: "If nothing changes", rows: base, cls: "s2" }, { label: R.fixLabel, rows: fix, cls: "s1" }]
: [{ label: "Your cash", rows: base, cls: "s1" }];
const n = base.length;
// Drawn at the box's real width (up to 960) so text stays 12px instead of shrinking; narrow boxes get a shorter
// chart, tighter margins and the cushion label inside the plot.
const W = fitWidth(root), narrow = W < 600, H = narrow ? 300 : 400;
const m = narrow ? { l: 60, r: 52, t: 56, b: 40 } : { l: 76, r: 96, t: 64, b: 44 }, pw = W - m.l - m.r, ph = H - m.t - m.b;
const step = n > 1 ? pw / (n - 1) : pw;
const xi = i => m.l + (n > 1 ? i * step : pw / 2);
const day0 = Engine.toDay(base[0].monday);
const xDate = iso => m.l + ((Engine.toDay(iso) - day0) / 7) * step;
// yExtra: every option card's line, so picking a card never rescales the chart (a slider can still stretch it).
const values = series.flatMap(se => se.rows.map(r => r.cash)).concat([0, c.cushion], R.yExtra || []);
const { ticks, lo, hi } = niceTicks(Math.min(...values), Math.max(...values), narrow ? 4 : 5);
const y = v => m.t + ph - ((v - lo) / (hi - lo || 1)) * ph;
const compact = ticks.some(t => Math.abs(t) >= 10000);
const tickText = v => compact && v !== 0 ? `${v < 0 ? "−" : ""}$${Math.abs(v) / 1000}K` : Fmt.money(v);
const svg = s("svg", { viewBox: `0 0 ${W} ${H}`, class: "cash-chart", role: "group", tabindex: "0",
"aria-label": "Weekly cash chart. Use the left and right arrow keys to read each week." });
const lastIso = base[n - 1].monday;
svg.append(s("title", {}, "Your cash, week by week"),
s("desc", {}, `Cash at the end of each week from ${Fmt.date(base[0].monday)} to the week of ${Fmt.date(lastIso)}. The table below the chart lists every value.`));
// Weeks before aid arrives: shown, not counted.
const disbMon = Engine.monday(c.disb);
const disbIdx = base.findIndex(r => r.monday >= disbMon);
if (disbIdx > 0) {
const xEnd = xi(disbIdx) - step / 2;
svg.append(s("rect", { class: "shade", x: m.l, y: m.t, width: Math.max(0, xEnd - m.l), height: ph }));
if (xEnd - m.l > 150) svg.append(s("text", { class: "note-text", x: m.l + 8, y: m.t + 16 }, "Before aid arrives (not counted)"));
}
// Spring break band.
const [sb0, sb1] = CONFIG.term.springBreak;
const sbIdx = base.findIndex(r => r.monday <= sb1 && Engine.toIso(Engine.toDay(r.monday) + 6) >= sb0);
if (sbIdx >= 0) svg.append(s("rect", { class: "shade light", x: xi(sbIdx) - step / 2, y: m.t, width: step, height: ph }));
// Everything under the cushion line gets a faint red wash: the zone this planner tries to keep you out of.
const yCush = Math.min(m.t + ph, Math.max(m.t, y(c.cushion)));
svg.append(s("rect", { class: "below", x: m.l, y: yCush, width: pw, height: m.t + ph - yCush }));
// Grid, zero line, y labels.
for (const t of ticks) {
svg.append(s("line", { class: t === 0 ? "zero" : "grid", x1: m.l, x2: m.l + pw, y1: y(t), y2: y(t) }),
s("text", { class: "axis-text", x: m.l - 10, y: y(t) + 4, "text-anchor": "end" }, tickText(t)));
}
// Month labels on the x axis.
let lastMonth = "";
base.forEach((r, i) => {
const mo = r.monday.slice(0, 7);
const firstWeek = mo !== lastMonth;
lastMonth = mo;
if (!firstWeek) return;
const label = new Date(r.monday + "T00:00:00Z").toLocaleDateString("en-US", { month: "short", timeZone: "UTC" })
+ (r.monday.slice(5, 7) === "01" || i === 0 ? " " + r.monday.slice(0, 4) : "");
svg.append(s("line", { class: "tick", x1: xi(i), x2: xi(i), y1: m.t + ph, y2: m.t + ph + 5 }),
s("text", { class: "axis-text", x: xi(i), y: m.t + ph + 20, "text-anchor": "middle" }, label));
});
// Cushion (a threshold, so dashed) with its label at the right.
svg.append(s("line", { class: "cushion", x1: m.l, x2: m.l + pw, y1: y(c.cushion), y2: y(c.cushion) }),
narrow ? s("text", { class: "note-text", x: m.l + pw - 4, y: y(c.cushion) - 6, "text-anchor": "end" }, `Cushion ${Fmt.money(c.cushion)}`)
: s("text", { class: "note-text", x: m.l + pw + 8, y: y(c.cushion) + 4 }, `Cushion ${Fmt.money(c.cushion)}`));
// Event markers row above the plot: bills, aid, add deadline, spring break.
const events = [];
const bills = [...new Set(base.flatMap(r => r.billDates))].sort();
bills.forEach(bd => events.push({ x: xDate(bd), label: "Bill due", date: bd }));
events.push({ x: xDate(c.disb), label: "Aid arrives", date: c.disb });
if (CONFIG.term.lastDayToAdd >= base[0].monday && CONFIG.term.lastDayToAdd <= c.end) {
events.push({ x: xDate(CONFIG.term.lastDayToAdd), label: "Last day to add", date: CONFIG.term.lastDayToAdd });
}
if (sbIdx >= 0) events.push({ x: xi(sbIdx), label: "Spring break", date: sb0 });
events.sort((a, b) => a.x - b.x);
const rowEnds = [-Infinity, -Infinity];
for (const ev of events) {
if (ev.x < m.l - 1 || ev.x > m.l + pw + 1) continue;
const w = ev.label.length * 6.6;
const row = rowEnds.findIndex(end => ev.x - w / 2 > end + 6);
svg.append(s("line", { class: "event", x1: ev.x, x2: ev.x, y1: m.t - 6, y2: m.t + ph }));
if (row >= 0) {
rowEnds[row] = ev.x + w / 2;
svg.append(s("text", { class: "event-text", x: ev.x, y: m.t - 12 - row * 16, "text-anchor": "middle" }, ev.label));
}
}
// Lines.
for (const se of series) {
const d = se.rows.map((r, i) => `${i ? "L" : "M"}${xi(i).toFixed(1)},${y(r.cash).toFixed(1)}`).join("");
svg.append(s("path", { class: `line ${se.cls}`, d }));
}
// Markers on the "as is" line: first week below the cushion and the lowest week (counted weeks only).
const dot = (i, v, cls) => s("circle", { class: `dot ${cls}`, cx: xi(i), cy: y(v), r: 5 });
// Labels near either edge hang inward so they never run into the axis labels.
const label = (i, v, text, above) => {
const x = xi(i), nearLeft = x < m.l + 110, nearRight = x > m.l + pw - 110;
let ty = above ? y(v) - 12 : y(v) + 22;
if (ty > m.t + ph - 6) ty = y(v) - 12; // too close to the month labels: go above
if (ty < m.t + 14) ty = y(v) + 22; // too close to the top: go below
return s("text", { class: "mark-text", x: nearLeft ? x + 8 : nearRight ? x - 8 : x, y: ty,
"text-anchor": nearLeft ? "start" : nearRight ? "end" : "middle" }, text);
};
const ro = rec.run_out_week ? base.findIndex(r => r.monday === rec.run_out_week) : -1;
const lowIdx = base.findIndex(r => r.monday === rec.tightest_week);
const baseCls = series[0].cls;
if (lowIdx >= 0) {
svg.append(dot(lowIdx, base[lowIdx].cash, baseCls), label(lowIdx, base[lowIdx].cash, `Lowest: ${Fmt.money(base[lowIdx].cash)}`, false));
}
if (ro >= 0 && ro !== lowIdx) {
svg.append(dot(ro, base[ro].cash, baseCls), label(ro, base[ro].cash, `Below cushion from ${Fmt.dateShort(rec.run_out_week)}`, base[ro].cash > c.cushion - (hi - lo) * 0.1));
}
// End values at the right edge, unless they would collide (the legend and table still carry them).
const ends = series.map(se => ({ se, v: se.rows[n - 1].cash }));
const clash = ends.length === 2 && Math.abs(y(ends[0].v) - y(ends[1].v)) < 16;
if (!clash) {
ends.forEach(({ v }) => svg.append(s("text", { class: "end-text", x: xi(n - 1) + 8, y: y(v) + 4 }, Fmt.money(v))));
}
// Hover / keyboard readout: a crosshair that snaps to the nearest week.
const cross = s("line", { class: "cross", x1: 0, x2: 0, y1: m.t, y2: m.t + ph, visibility: "hidden" });
const focusDots = series.map(se => s("circle", { class: `dot ${se.cls}`, r: 5, visibility: "hidden" }));
const hit = s("rect", { class: "hit", x: m.l - step / 2, y: m.t - 40, width: pw + step, height: ph + 40 });
svg.append(cross, ...focusDots, hit);
const tip = h("div", { class: "chart-tip", role: "status", "aria-live": "polite", hidden: "" });
let current = -1;
function show(i) {
current = Math.max(0, Math.min(n - 1, i));
const x = xi(current);
cross.setAttribute("x1", x); cross.setAttribute("x2", x); cross.setAttribute("visibility", "visible");
series.forEach((se, k) => {
focusDots[k].setAttribute("cx", x); focusDots[k].setAttribute("cy", y(se.rows[current].cash));
focusDots[k].setAttribute("visibility", "visible");
});
const r0 = base[current];
const rows = [h("div", { class: "tip-head", text: `Week of ${Fmt.date(r0.monday)}` })];
for (const se of series.slice().reverse()) {
rows.push(h("div", { class: "tip-row" }, h("span", { class: `key ${se.cls}` }),
h("strong", { text: Fmt.money(se.rows[current].cash) }), h("span", { class: "muted", text: se.label })));
}
const extra = [];
if (r0.due) extra.push(`Bill payment ${Fmt.money(r0.due, true)}`);
if (fix && fix[current].due !== r0.due) extra.push(`Bill payment with the fix ${Fmt.money(fix[current].due, true)}`);
if (r0.inflow) extra.push(`Aid refund ${Fmt.money(r0.inflow, true)}`);
if (fix && fix[current].inflow && !r0.inflow) extra.push(`Aid refund with the fix ${Fmt.money(fix[current].inflow, true)}`);
extra.push(`Pay ${Fmt.money(r0.pay, true)}${fix && fix[current].pay !== r0.pay ? ` (${Fmt.money(fix[current].pay, true)} with the fix)` : ""}, living ${Fmt.money(r0.living, true)}`);
if (r0.monday < disbMon) extra.push("Before aid arrives: not counted toward your cushion");
rows.push(...extra.map(t => h("div", { class: "tip-note", text: t })));
tip.replaceChildren(...rows);
tip.hidden = false;
const box = root.getBoundingClientRect(), scale = box.width / W;
const left = x * scale;
tip.style.left = `${Math.min(Math.max(left + 14, 8), box.width - 268)}px`;
tip.style.top = `${(m.t + 4) * scale}px`;
if (left + 14 + 260 > box.width) tip.style.left = `${Math.max(8, left - 274)}px`;
}
function hide() {
cross.setAttribute("visibility", "hidden");
focusDots.forEach(d => d.setAttribute("visibility", "hidden"));
tip.hidden = true;
}
hit.addEventListener("pointermove", e => {
const pt = svg.getBoundingClientRect(), x = ((e.clientX - pt.left) / pt.width) * W;
show(Math.round((x - m.l) / step));
});
hit.addEventListener("pointerleave", () => { if (document.activeElement !== svg) hide(); });
svg.addEventListener("focus", () => show(current < 0 ? (lowIdx >= 0 ? lowIdx : 0) : current));
svg.addEventListener("blur", hide);
svg.addEventListener("keydown", e => {
if (e.key === "ArrowRight" || e.key === "ArrowLeft") { e.preventDefault(); show(current + (e.key === "ArrowRight" ? 1 : -1)); }
else if (e.key === "Home") { e.preventDefault(); show(0); }
else if (e.key === "End") { e.preventDefault(); show(n - 1); }
else if (e.key === "Escape") hide();
});
// Legend: a line key per series (none for a single series), plus the cushion and the shading.
const legend = h("div", { class: "chart-legend" });
if (series.length > 1) {
for (const se of series.slice().reverse()) legend.append(h("span", { class: "lg" }, h("span", { class: `key ${se.cls}` }), se.label));
}
legend.append(h("span", { class: "lg" }, h("span", { class: "key dashed" }), "Your cushion"),
h("span", { class: "lg" }, h("span", { class: "key below" }), "Below your cushion"));
if (disbIdx > 0) legend.append(h("span", { class: "lg" }, h("span", { class: "key box" }), "Before aid arrives (not counted)"));
// Table view: every number in the chart, no hovering needed.
const thead = h("tr", {}, ...["Week of", "Pay", "Living", "Bill payments", "Aid refund", ...series.map(se => `Cash: ${se.label.toLowerCase()}`)]
.map(t => h("th", { text: t })));
const tbody = h("tbody", {}, ...base.map((r, i) => h("tr", {},
h("td", { text: Fmt.date(r.monday) }), h("td", { text: Fmt.money(r.pay, true) }), h("td", { text: Fmt.money(r.living, true) }),
h("td", { text: r.due ? Fmt.money(r.due, true) : "—" }), h("td", { text: r.inflow ? Fmt.money(r.inflow, true) : "—" }),
...series.map(se => h("td", { text: Fmt.money(se.rows[i].cash, true) })))));
const table = h("details", { class: "chart-table" }, h("summary", { text: "Show the weekly numbers" }),
h("div", { class: "tbl" }, h("table", {}, h("thead", {}, thead), tbody)),
fix ? h("p", { class: "muted small", text: "Pay, living and bill columns are for \"if nothing changes\"; the fix changes your pay (extra hours) and bill payments (loans)." }) : null);
table.open = !!root.querySelector("details.chart-table[open]"); // a redraw (new option, slider) keeps it open
root.replaceChildren(legend, h("div", { class: "chart-box" }, svg, tip), table);
watch(root, R, W);
}
// The width to draw at: the chart box's own width, between 300 and 960.
function fitWidth(root) {
const w = Math.round(root.clientWidth || 0);
return w > 0 ? Math.max(300, Math.min(960, w)) : 960;
}
// Redraw when the box gets noticeably wider or narrower (window resized). Only the newest chart is watched.
let ro = null, current = null;
function watch(root, R, W) {
current = { root, R, W };
if (!("ResizeObserver" in window)) return;
if (!ro) ro = new ResizeObserver(() => {
if (!current || !current.root.isConnected) return;
if (Math.abs(fitWidth(current.root) - current.W) >= 24) draw(current.root, current.R);
});
ro.disconnect();
ro.observe(root);
}
return { draw };
})();
/* =====================================================================================
PAGE: welcome screen, four guided steps, the "Edit my numbers" drawer, save bar and dialogs.
===================================================================================== */
const UI = (() => {
const $ = id => document.getElementById(id);
let store, uid = 0, refreshers = {};
const view = { mode: "welcome", step: 0, schoolOpen: false, privateOpen: false, planOpen: false, moreOpen: false,
drawerOpen: false, sample: false, ratesOpen: false, pick: null, mix: null };
function h(tag, attrs = {}, ...kids) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") n.className = v; else if (k === "text") n.textContent = v; else n.setAttribute(k, v);
}
for (const k of kids) if (k != null && k !== false) n.append(k);
return n;
}
// Small inline SVG pictures (icons, the welcome sketch). Always decorative: hidden from screen readers.
const SVG_NS = "http://www.w3.org/2000/svg";
function sv(tag, attrs = {}, ...kids) {
const n = document.createElementNS(SVG_NS, tag);
for (const [k, v] of Object.entries(attrs)) n.setAttribute(k, v);
for (const k of kids) if (k != null) n.append(k);
return n;
}
const ICONS = {
check: ["M4 8.5l2.6 2.6L12 5.6"],
alert: ["M8 4.6v4", "M8 11.2v.1", "M8 1.8l6.4 11.4H1.6z"],
arrow: ["M2.5 8h10", "M9 4.5L12.5 8 9 11.5"],
calendar: ["M2.5 4h11v9.5h-11z", "M2.5 7h11", "M5.5 2.2v3", "M10.5 2.2v3"],
chart: ["M2 13.5h12", "M2.5 11l3.5-3.5 2.6 2.3L13.5 5"],
};
const icon = (name, cls = "stat-icon") => sv("svg", { class: cls, viewBox: "0 0 16 16", "aria-hidden": "true", focusable: "false" },
...ICONS[name].map(d => sv("path", { d })));
const chartIcon = () => icon("chart", "on-chart-icon");
// The answer and the welcome card enter once per visit (tasteskill: one entrance, never on scroll).
const entered = { answer: false, welcome: false };
function enterOnce(node, key) {
if (!entered[key]) { entered[key] = true; node.classList.add("enter"); }
return node;
}
// ---- "?" tips ----
function tip(key) {
const g = GLOSSARY[key];
if (!g) return null;
const id = "tip" + (++uid);
const btn = h("button", { type: "button", class: "tip", "aria-label": `What is ${g.term}?`, "aria-describedby": id, text: "?" });
const pop = h("span", { class: "tip-pop", role: "tooltip", id, text: g.text });
const wrap = h("span", { class: "tip-wrap" }, btn, pop);
btn.addEventListener("click", () => { wrap.classList.toggle("open"); placeTip(wrap); });
btn.addEventListener("blur", () => wrap.classList.remove("open"));
btn.addEventListener("keydown", e => { if (e.key === "Escape") wrap.classList.remove("open"); });
wrap.addEventListener("mouseenter", () => placeTip(wrap));
wrap.addEventListener("focusin", () => placeTip(wrap));
return wrap;
}
// Put an open tip just under its "?" (above it if there's no room below), at least 8px inside the window.
let activeTip = null;
function placeTip(wrap) {
const btn = wrap.querySelector(".tip"), pop = wrap.querySelector(".tip-pop"), gap = 6, edge = 8;
activeTip = wrap;
pop.style.visibility = "hidden"; pop.style.display = "block";
const b = btn.getBoundingClientRect(), w = pop.offsetWidth, ht = pop.offsetHeight;
const vw = document.documentElement.clientWidth, vh = window.innerHeight;
const left = Math.min(Math.max(edge, b.left + b.width / 2 - w / 2), vw - w - edge);
const below = b.bottom + gap, above = b.top - gap - ht;
const top = below + ht <= vh - edge || above < edge ? below : above;
pop.style.left = `${Math.round(Math.max(edge, left))}px`;
pop.style.top = `${Math.round(top)}px`;
pop.style.display = ""; pop.style.visibility = "";
}
// Keep an open tip with its "?" while the page or a table scrolls, or the window resizes.
const followTip = () => { if (activeTip && activeTip.isConnected && activeTip.matches(":hover, :focus-within, .open")) placeTip(activeTip); };
window.addEventListener("scroll", followTip, { capture: true, passive: true });
window.addEventListener("resize", followTip, { passive: true });
const termChip = key => h("span", { class: "term" }, GLOSSARY[key].term, tip(key));
// ---- Unsaved dot and status ----
function renderStatus() {
$("save-status").classList.toggle("unsaved", store.dirty);
const time = store.when ? store.when.toLocaleTimeString([], { hour: "numeric", minute: "2-digit" }) : "";
$("status-text").textContent = store.dirty ? "Unsaved changes"
: store.status === "saved" ? `Saved to a file at ${time}`
: store.status === "copied" ? `Copied at ${time}`
: store.status === "opened" ? `Opened ${store.name} at ${time}`
: store.status === "pasted" ? `Restored from pasted data at ${time}`
: store.status === "sample" ? `Showing sample student ${store.name || "Jordan"} (fictional)`
: "No changes yet";
// The one word narrow windows show beside the dot.
$("status-short").textContent = store.dirty ? "Unsaved"
: ({ saved: "Saved", copied: "Copied", opened: "Opened", pasted: "Restored", sample: "Sample" })[store.status] || "No changes";
document.title = (store.dirty ? "● " : "") + "Make It to May";
}
function showMsg(kind, title, items = [], extra = null) {
const box = $("file-msg");
box.className = "filemsg " + kind;
const body = h("div", { class: "msg-body" }, h("strong", { text: title }));
if (extra) body.append(" ", extra);
if (items.length) {
body.append(h("ul", {}, ...items.slice(0, 6).map(t => h("li", { text: t })),
items.length > 6 ? h("li", { text: `…and ${items.length - 6} more.` }) : null));
}
const close = h("button", { type: "button", class: "linkish", text: "Dismiss" });
close.addEventListener("click", () => { box.hidden = true; });
box.replaceChildren(body, close);
box.hidden = false;
}
function ask({ title, body, yes, no }) {
const d = $("confirm-dialog"), y = $("confirm-yes"), n = $("confirm-no");
$("confirm-title").textContent = title;
$("confirm-body").textContent = body;
y.textContent = yes;
n.textContent = no;
return new Promise(resolve => {
const finish = v => {
y.removeEventListener("click", onYes); n.removeEventListener("click", onNo); d.removeEventListener("cancel", onCancel);
if (d.open) d.close();
resolve(v);
};
const onYes = () => finish(true), onNo = () => finish(false), onCancel = e => { e.preventDefault(); finish(false); };
y.addEventListener("click", onYes); n.addEventListener("click", onNo); d.addEventListener("cancel", onCancel);
d.showModal();
n.focus();
});
}
const confirmReplace = () => ask({ title: "Replace your unsaved changes?",
body: "Opening this file replaces the numbers on the page. Changes you haven't saved will be lost.",
yes: "Open the file", no: "Keep editing" });
// ---- Save, Open, Copy, Paste, sample, start over ----
function save() {
const name = FileIO.download(store);
const copy = h("button", { type: "button", class: "linkish", text: "Copy your data instead" });
copy.addEventListener("click", openCopy);
showMsg("ok", `Saved ${name} to your downloads.`, [], h("span", {}, "No file appeared? ", copy));
}
function showPlan() {
view.mode = "plan";
view.sample = store.status === "sample" ? (store.name || "Jordan") : false;
view.pick = null; // new numbers: the chart starts on the recommendation and the sliders on the plan
view.mix = null;
view.drawerOpen = false;
render();
clearTimeout(resultsTimer); // render() just drew these numbers; skip the redraw the load had queued
window.scrollTo(0, 0);
// Move focus to the answer so keyboard and screen-reader users land on it.
// With numbers missing there's no headline yet: land on the missing-numbers card instead (it lives in #answer-slot).
const target = $("headline") || $("missing-title");
target?.focus({ preventScroll: true });
}
async function openChosenFile(file) {
const fail = errors => showMsg("error", `Couldn't open “${file.name}”. Your numbers are unchanged.`, errors);
if (file.size > Schema.MAX_CHARS) return fail(["This file is too large to be a Make It to May save file (over 1 MB)."]);
let text;
try { text = await file.text(); } catch { return fail(["The file couldn't be read."]); }
const r = await FileIO.tryOpen(store, text, confirmReplace, "opened", file.name);
if (r.cancelled) return;
if (!r.ok) return fail(r.errors);
showPlan();
showMsg("ok", `Opened “${file.name}”.`);
}
function openCopy() {
$("copy-text").value = Schema.serialize(store.data);
$("copy-msg").textContent = "";
$("copy-dialog").showModal();
$("copy-text").select();
}
async function doCopy() {
const ta = $("copy-text");
let ok = false;
try { await navigator.clipboard.writeText(ta.value); ok = true; } catch {
ta.focus(); ta.select();
try { ok = document.execCommand("copy"); } catch { ok = false; }
}
if (ok) {
store.markSaved("copied");
$("copy-msg").textContent = "Copied. Paste it into a note or a text file you keep.";
} else {
$("copy-msg").textContent = "Your browser blocked copying. Click in the box, press Ctrl+A, then Ctrl+C.";
}
}
function openPaste() {
$("paste-text").value = "";
$("paste-msg").replaceChildren();
$("paste-warn").hidden = !store.dirty;
$("paste-dialog").showModal();
}
async function doPaste() {
if (!$("paste-text").value.trim()) {
$("paste-msg").replaceChildren(h("strong", { text: "Paste your data first." }));
$("paste-text").focus();
return;
}
const r = await FileIO.tryOpen(store, $("paste-text").value, () => true, "pasted");
if (!r.ok) {
$("paste-msg").replaceChildren(h("strong", { text: "Couldn't restore. Your numbers are unchanged." }),
h("ul", {}, ...r.errors.slice(0, 6).map(t => h("li", { text: t }))));
return;
}
$("paste-dialog").close();
showPlan();
showMsg("ok", "Restored your numbers from the pasted data.");
}
// "Try a sample student" opens the picker; picking one loads it (after asking, if there are unsaved changes).
function trySample() {
const dlg = $("sample-dialog"), list = $("sample-list");
const current = store.status === "sample" ? store.name : "";
list.replaceChildren(...Sample.LIST.map(s => {
const b = h("button", { type: "button", class: "sample-pick", "aria-current": s.name === current ? "true" : "false" },
h("span", { class: "sp-name", text: s.name }),
h("span", { class: `chip ${s.tone === "good" ? "pass" : s.tone === "bad" ? "fail" : "fix"}`, text: s.tag }),
h("span", { class: "sp-desc", text: s.desc }));
b.addEventListener("click", () => { dlg.close(); loadSample(s); });
return b;
}));
dlg.showModal();
(list.querySelector('[aria-current="true"]') || list.firstElementChild)?.focus();
}
async function loadSample(s) {
if (store.dirty && !(await ask({ title: "Replace your unsaved changes?",
body: `Sample student ${s.name} replaces the numbers on the page. Changes you haven't saved will be lost.`,
yes: "Show the sample", no: "Keep editing" }))) return;
store.load(s.data(), "sample", s.name);
showPlan();
}
async function startOver() {
if (store.dirty && !(await ask({ title: "Start over?",
body: "This clears every number on the page. Changes you haven't saved will be lost.",
yes: "Start over", no: "Keep editing" }))) return;
store.load(Schema.defaults(), "new");
Object.assign(view, { mode: "welcome", step: 0, sample: false });
render();
window.scrollTo(0, 0);
}
// ---- Form controls ----
function afterChange(path, fd) {
const d = store.data;
let changed = false;
if (["payment.firstPayment", "payment.payments", "payment.dueDay"].includes(path)) {
d.payment.dates = Engine.planDates(d.payment.firstPayment, d.payment.payments, d.payment.dueDay);
refreshers["payment.dates"]?.();
changed = true;
}
if (path === "profile.graduationTerm" || path === "profile.graduationYear") {
const auto = "-" + CONFIG.product.springGraduationDay;
if (d.profile.graduationTerm === "spring" && d.profile.graduationYear) {
d.profile.graduationDate = d.profile.graduationYear + auto; changed = true;
} else if (d.profile.graduationTerm === "fall" && d.profile.graduationDate?.endsWith(auto)) {
d.profile.graduationDate = null; changed = true;
}
refreshers["profile.graduationDate"]?.();
}
if (changed) store.touch();
if (fd.rerender) redrawStep(path);
}
function control(fd, path, id, errEl, describedBy) {
const value = Schema.getPath(store.data, path);
const setErr = (msg, input) => {
errEl.textContent = msg || "";
errEl.hidden = !msg;
input.setAttribute("aria-invalid", msg ? "true" : "false");
};
const commit = (v, input) => {
const e = Schema.check(fd, v);
setErr(e, input);
if (!e) { store.set(path, v); afterChange(path, fd); }
};
const base = { id, "data-path": path, "aria-describedby": describedBy };
switch (fd.kind) {
case "money": case "num": case "int": {
const input = h("input", { ...base, type: "number", step: fd.kind === "int" ? "1" : String(fd.step ?? 0.01),
min: String(fd.min ?? 0), max: String(fd.max ?? 1000000), class: fd.kind === "money" ? "money" : "" });
input.value = value ?? "";
input.addEventListener("input", () => {
if (input.validity.badInput) return setErr(`${fd.label} must be a number.`, input);
if (input.value === "") return fd.nullable ? commit(null, input) : setErr(`${fd.label} is needed.`, input);
commit(Number(input.value), input);
});
return input;
}
case "date": {
const input = h("input", { ...base, type: "date" });
input.value = value ?? "";
input.addEventListener("change", () => {
if (input.value === "") return fd.nullable ? commit(null, input) : setErr(`${fd.label} is needed.`, input);
commit(input.value, input);
});
refreshers[path] = () => { input.value = Schema.getPath(store.data, path) ?? ""; setErr("", input); };
return input;
}
case "text": {
const input = h("input", { ...base, type: "text", maxlength: String(fd.max ?? 60) });
input.value = value ?? "";
input.addEventListener("input", () => commit(input.value, input));
return input;
}
case "bool":
if (!fd.nullable) {
const cb = h("input", { ...base, type: "checkbox" });
cb.checked = value === true;
cb.addEventListener("change", () => commit(cb.checked, cb));
return cb;
}
// an optional yes/no falls through to a select with "Not sure"
case "enum": {
const opts = fd.kind === "bool" ? [[true, "Yes"], [false, "No"]] : fd.options;
const sel = h("select", base);
if (fd.nullable) sel.append(h("option", { value: "", text: fd.kind === "bool" ? "Not sure" : "Choose…" }));
opts.forEach(([, label], i) => sel.append(h("option", { value: String(i), text: label })));
const idx = opts.findIndex(([v]) => v === value);
sel.value = idx >= 0 ? String(idx) : "";
sel.addEventListener("change", () => commit(sel.value === "" ? null : opts[+sel.value][0], sel));
return sel;
}
case "dates": case "numbers": return listControl(fd, path, id);
}
return h("span", { text: "?" });
}
function listControl(fd, path, id) {
const box = h("div", { class: "datelist", role: "group", "aria-labelledby": id + "-label", "data-path": path });
const isDates = fd.kind === "dates";
function draw() {
box.replaceChildren();
const list = Schema.getPath(store.data, path);
list.forEach((val, i) => {
const input = h("input", isDates ? { type: "date" }
: { type: "number", class: "short", step: String(fd.step ?? 1), min: String(fd.min ?? 0), max: String(fd.max ?? 1000000) });
input.setAttribute("aria-label", `${fd.label}: ${isDates ? "date" : "semester"} ${i + 1}`);
input.value = val;
input.addEventListener(isDates ? "change" : "input", () => {
const v = isDates ? input.value : (input.value === "" || input.validity.badInput ? NaN : Number(input.value));
const next = [...Schema.getPath(store.data, path)];
next[i] = v;
const bad = Schema.check(fd, next);
input.setAttribute("aria-invalid", bad ? "true" : "false");
if (!bad) store.set(path, next);
});
const rm = h("button", { type: "button", class: "linkish", text: "Remove", "aria-label": `Remove ${isDates ? "date" : "semester"} ${i + 1}` });
rm.addEventListener("click", () => {
const next = [...Schema.getPath(store.data, path)];
next.splice(i, 1);
store.set(path, next);
draw();
});
box.append(h("span", { class: "item" }, input, rm));
});
if (!list.length) box.append(h("span", { class: "muted small", text: "None." }));
if (list.length < fd.maxItems) {
const add = h("button", { type: "button", class: "btn secondary small-btn", text: fd.addLabel || "Add" });
add.addEventListener("click", () => {
const cur = Schema.getPath(store.data, path), last = cur[cur.length - 1];
let nextVal;
if (!isDates) nextVal = CONFIG.product.creditsPerSemester;
else if (fd.every === "month") nextVal = last ? Engine.addMonths(last, 1) : store.data.payment.firstPayment;
else nextVal = last ? Engine.toIso(Engine.toDay(last) + 7) : store.data.school.forecastStart;
store.set(path, [...cur, nextVal]);
draw();
});
box.append(add);
}
}
draw();
refreshers[path] = draw;
return box;
}
function fieldBlock(path) {
const fd = Schema.byPath[path];
const id = "f" + (++uid);
const err = h("p", { class: "err", id: id + "-err", hidden: "" });
const hint = fd.hint ? h("p", { class: "hint", id: id + "-hint", text: fd.hint }) : null;
const list = fd.kind === "dates" || fd.kind === "numbers";
const label = list ? h("span", { class: "label", id: id + "-label", text: fd.label }) : h("label", { for: id, text: fd.label });
const describedBy = [hint ? id + "-hint" : null, id + "-err"].filter(Boolean).join(" ");
return h("div", { class: "field" + (list ? " wide" : "") },
h("div", { class: "label-row" }, label, fd.tip ? tip(fd.tip) : null),
control(fd, path, id, err, describedBy), hint, err);
}
// ---- Awards table (step 3) ----
const RULE_TYPES = new Set(["grant", "scholarship"]);
function awardsEditor() {
const wrap = h("div", { class: "awards" });
const awards = store.data.awards;
if (awards.length) {
const cols = ["Name", "Type", "Amount this term", "Accepted", "Min GPA to keep", "Min credit hours to keep", "Have a Work-Study job"];
const body = h("tbody");
awards.forEach((a, i) => {
const tr = h("tr");
for (const fd of Schema.AWARD_FIELDS) {
const shown = (fd.path !== "minGpa" && fd.path !== "minCredits" && fd.path !== "hasJob")
|| (fd.path === "hasJob" ? a.type === "workstudy" : RULE_TYPES.has(a.type));
if (!shown) {
const why = fd.path === "hasJob" ? "—" : a.type === "kees" ? "KEES rules below" : "—";
tr.append(h("td", { class: "muted small", text: why }));
continue;
}
const id = "f" + (++uid);
const err = h("p", { class: "err", id: id + "-err", hidden: "" });
const ctrl = control(fd, `awards.${i}.${fd.path}`, id, err, id + "-err");
ctrl.setAttribute("aria-label", `Award ${i + 1}: ${fd.label}`);
tr.append(h("td", {}, ctrl, err));
}
const rm = h("button", { type: "button", class: "linkish", text: "Remove", "aria-label": `Remove award ${i + 1}` });
rm.addEventListener("click", () => { store.data.awards.splice(i, 1); store.touch(); redrawStep(); });
tr.append(h("td", {}, rm));
body.append(tr);
});
wrap.append(h("table", {}, h("thead", {}, h("tr", {}, ...cols.map(t => h("th", { text: t })), h("th", { text: "" }))), body));
} else {
wrap.append(h("p", { class: "muted small", text: "No awards yet. Add each grant, scholarship, KEES award, loan and Work-Study offer from your myUK Financial Aid page." }));
}
if (awards.length < 30) {
// One click per common award: name and type filled in, the cursor on the amount. "Other award" is a blank row.
const QUICK = [["Pell Grant", "Federal Pell Grant", "grant"], ["Scholarship", "Scholarship", "scholarship"], ["KEES", "KEES", "kees"],
["Subsidized loan", "Direct Subsidized Loan", "subsidized"], ["Unsubsidized loan", "Direct Unsubsidized Loan", "unsubsidized"],
["Work-Study", "Federal Work-Study", "workstudy"], ["Other award", "", "grant"]];
const buttons = QUICK.map(([label, name, type]) => {
const b = h("button", { type: "button", class: "btn secondary small-btn", text: `+ ${label}` });
b.addEventListener("click", () => {
store.data.awards.push({ ...Schema.newAward(), name, type });
store.touch();
redrawStep(`awards.${store.data.awards.length - 1}.${name ? "amount" : "name"}`);
});
return b;
});
// Outside the table's sideways-scrolling box, so the buttons never sit under its scrollbar.
return h("div", {}, wrap, h("div", { class: "quick-add", role: "group", "aria-label": "Add an award" },
h("span", { class: "quick-label", text: "Add an award:" }), ...buttons));
}
return wrap;
}
// ---- The four steps ----
const isPlan = d => d.payment.mode === "plan";
const STEPS = [
{ title: "About you", intro: "A few facts that set your federal loan limits and the rules your aid depends on.", sections: [
{ fields: ["profile.yearInSchool", "profile.dependency", "profile.gpa", "profile.creditHours",
"profile.graduationTerm", "profile.graduationYear", "profile.graduationDate"] },
] },
{ title: "Your bill", intro: "From your myUK Account Summary.", sections: [
{ title: "Charges", fields: ["bill.tuition", "bill.housing", "bill.meals", "bill.books", "bill.other"] },
{ title: "How you pay it", fields: ["payment.mode", ["payment.fullDue", d => !isPlan(d)]] },
// The plan's settings start folded (UK's plan filled in); the title line says what's assumed.
{ title: "Payment plan details", collapsible: "planOpen", when: isPlan,
fields: ["payment.firstPayment", "payment.payments", "payment.dueDay", "payment.fee", "payment.minBalance", "payment.dates"],
summary: d => {
const ds = [...(d.payment.dates || [])].filter(Boolean).sort(), n = ds.length;
const span = n ? (n > 1 ? `, ${Fmt.dateShort(ds[0])} to ${Fmt.dateShort(ds[n - 1])}` : `, ${Fmt.dateShort(ds[0])}`) : "";
const fee = d.payment.fee ? `, ${Fmt.money(d.payment.fee)} fee` : ", no fee";
return ` ${n} payment${n === 1 ? "" : "s"}${span}${fee}. Change if your school's plan differs.`;
} },
{ title: "School dates", collapsible: "schoolOpen", fields: ["school.termName", "school.forecastStart", "school.aidDate", "school.termEnd", "school.noPayWeeks"],
summary: d => ` ${d.school.termName}: aid arrives ${Fmt.date(d.school.aidDate)}, term ends ${Fmt.date(d.school.termEnd)}. Change if your school differs.` },
] },
{ title: "Your aid", intro: "Every award on your myUK Financial Aid page. Only accepted awards count toward your bill.",
terms: ["gift", "subsidized", "unsubsidized", "originationFee", "workstudy"], sections: [
{ title: "Awards", awards: true },
{ title: "For KEES", tip: "kees", when: d => d.awards.some(a => a.type === "kees"),
fields: ["profile.semesterCredits", "profile.fullTimeRecent"] },
{ title: "Federal loans you could still take", tip: "loanRoom",
fields: ["loans.subRoomOverride", "loans.unsubRoomOverride", "loans.priorTotal", "loans.priorSub"] },
{ title: "Private loan (last resort)", collapsible: "privateOpen",
summary: d => (d.private.rate === null ? " Optional. Leave this closed unless a lender has quoted you a rate."
: ` Quoted rate ${d.private.rate}%. Used only where federal loans and work can't cover your bills.`),
note: () => `Use federal, state and UK aid first. Ask UK Financial Aid about emergency aid and UK's own loans (${CONFIG.privateLoan.ukLoans.map(u => u.name).join(" and ")}). Most private loans need a cosigner unless you have a good credit history, and they don't have federal options for lowering or pausing payments.`,
fields: ["private.rate", "private.fee", "private.years", "private.graceMonths", "private.capitalize"] },
] },
{ title: "Your money", intro: "From your bank app and a pay stub. Plain numbers only; never a login.", sections: [
{ fields: ["money.cash", "money.hours", "money.wage", "money.takeHome", "money.safeMax", "money.living", "money.cushion"] },
{ title: "After you graduate", fields: ["payoff.mode", ["payoff.years", d => d.payoff.mode === "years"]] },
{ title: "More settings", collapsible: "moreOpen", fields: ["money.hoursCeiling"],
summary: d => ` The "Work more" option looks as high as ${d.money.hoursCeiling ?? CONFIG.product.hoursFlag} hours a week.` },
] },
];
// A folded section's title line ("4 payments, Jan 4 to Apr 22, $50 fee") follows edits made inside it.
let sectionSummaries = [];
function refreshSectionSummaries() {
sectionSummaries = sectionSummaries.filter(([el]) => el.isConnected);
for (const [el, fn] of sectionSummaries) el.textContent = fn(store.data);
}
function drawStep(container) {
refreshers = {};
sectionSummaries = [];
const st = STEPS[view.step], d = store.data;
const parts = [
h("h3", { class: "step-title", text: `Step ${view.step + 1} of ${STEPS.length}: ${st.title}` }),
h("p", { class: "muted step-intro", text: st.intro }),
st.terms ? h("p", { class: "terms small" }, "Terms: ", ...st.terms.map(termChip)) : null,
];
for (const sec of st.sections) {
if (sec.when && !sec.when(d)) continue;
const body = [];
if (sec.awards) body.push(awardsEditor());
if (sec.note) body.push(h("p", { class: "muted small", text: sec.note(d) }));
if (sec.fields) {
const paths = sec.fields.filter(e => typeof e === "string" || e[1](d)).map(e => (typeof e === "string" ? e : e[0]));
body.push(h("div", { class: "fields" }, ...paths.map(fieldBlock)));
}
if (sec.collapsible) {
const key = sec.collapsible; // view flag that remembers whether it's open
const sum = h("span", { class: "muted small", text: sec.summary(d) });
sectionSummaries.push([sum, sec.summary]); // kept current as numbers change (refreshSectionSummaries)
const det = h("details", { class: "step-section collapsible" },
h("summary", {}, h("strong", { text: sec.title }), sum),
...body);
det.open = view[key];
det.addEventListener("toggle", () => { view[key] = det.open; });
parts.push(det);
} else {
parts.push(h("section", { class: "step-section" },
sec.title ? h("h4", {}, sec.title, sec.tip ? tip(sec.tip) : null) : null, ...body));
}
}
container.replaceChildren(...parts.filter(Boolean));
}
// Which step (and folded section, if any) holds a field.
function stepOfPath(path) {
for (let i = 0; i < STEPS.length; i++) {
for (const sec of STEPS[i].sections) {
const paths = (sec.fields || []).map(e => (typeof e === "string" ? e : e[0]));
if (paths.includes(path)) return { step: i, open: sec.collapsible || null };
}
}
return null;
}
// Open the step that holds a field and put the cursor in it (from "still missing" links).
function goToField(path) {
const at = stepOfPath(path);
if (!at) return;
view.step = at.step;
if (at.open) view[at.open] = true;
if (view.mode === "plan") view.drawerOpen = true;
render();
const el = document.querySelector(`#step-body [data-path="${path}"]`);
// The box itself, or the first box in a list; an empty list (no payment dates yet) gets its "Add a date" button.
const target = el && (el.matches("input, select, textarea") ? el : el.querySelector("input, select, textarea, button"));
(target || document.querySelector("#step-body"))?.scrollIntoView({ block: "center" });
target?.focus({ preventScroll: true });
}
// A "still missing" list whose items link to their boxes.
const missingList = (items, paths) => h("ul", {}, ...items.map((t, i) => {
if (!paths || !paths[i]) return h("li", { text: t });
const b = h("button", { type: "button", class: "linkish inline", text: t });
b.addEventListener("click", () => goToField(paths[i]));
return h("li", {}, b);
}));
function redrawStep(focusPath) {
const body = $("step-body");
if (!body) return;
drawStep(body);
if (focusPath) body.querySelector(`[data-path="${focusPath}"]`)?.focus();
}
function stepNav() {
return h("ol", { class: "steps", "aria-label": "Steps" }, ...STEPS.map((st, i) => {
const b = h("button", { type: "button" }, h("span", { class: "num", text: String(i + 1) }), st.title);
if (i === view.step) b.setAttribute("aria-current", "step");
b.addEventListener("click", () => {
view.step = i;
if (view.mode === "plan") view.drawerOpen = true; // tabs live inside the open drawer
render();
$("app").querySelector(".steps [aria-current='step']")?.focus();
});
return h("li", {}, b);
}));
}
// ---- "What the planner knows so far" ----
function summaryNodes() {
const r = Inputs.derive(store.data);
const row = (label, value, tipKey, cls = "") => [h("dt", { class: cls }, label, tipKey ? tip(tipKey) : null), h("dd", { class: cls, text: value })];
const nodes = [h("h3", { text: "What the planner knows so far" })];
nodes.push(h("dl", {},
...row("Charges on your bill", Fmt.money(r.charges)),
...row("Grants, scholarships, KEES", r.gifts ? "−" + Fmt.money(r.gifts) : "$0", "gift"),
...row("Loans, after the fee", r.loansNet ? "−" + Fmt.money(r.loansNet) : "$0", "originationFee"),
...row(r.gap >= 0 ? "You owe after aid" : "Refund to you", Fmt.money(Math.abs(r.gap)), null, "total")));
nodes.push(h("h4", { text: r.plan ? "Payment plan" : "Due date" }));
if (r.schedule.length) {
nodes.push(h("table", { class: "mini" }, h("tbody", {}, ...r.schedule.map(([dt, amt]) =>
h("tr", {}, h("td", { text: Fmt.date(dt) }), h("td", { class: "num", text: Fmt.money(amt, true) }))))));
if (r.fee) nodes.push(h("p", { class: "muted small", text: `The first payment includes the ${Fmt.money(r.fee)} plan fee.` }));
} else {
nodes.push(h("p", { class: "muted small", text: r.gap < 0 ? `Nothing to pay. The extra comes to you around ${Fmt.date(store.data.school.aidDate)}.` : "Nothing to pay yet." }));
}
nodes.push(h("dl", {},
...row("Pay per week", `${Fmt.money(r.weeklyPay, true)} ${r.afterTax ? "after taxes" : "before taxes"}`, r.afterTax ? null : "takeHome"),
...row("Living costs per week", Fmt.money(r.weeklyLiving, true)),
...row("Subsidized loan you could still take", Fmt.money(r.room.sub), "subsidized"),
...row("Unsubsidized loan you could still take", Fmt.money(r.room.unsub), "unsubsidized"),
...row("Loan payments would start", Fmt.date(r.graceEnd), "grace")));
nodes.push(h("p", { class: "muted small", text: r.room.fromMyUK ? "Loan amounts: what you entered from myUK." : "Loan amounts: federal limits for your year, before any need test." }));
if (r.missing.length) {
nodes.push(h("div", { class: "missing" }, h("strong", { text: "Still needed for your results:" }), missingList(r.missing, r.missingAt)));
} else {
nodes.push(h("p", { class: "ready", text: "✓ Everything the forecast needs is here." }));
}
if (r.warnings.length) nodes.push(h("ul", { class: "warnings" }, ...r.warnings.map(t => h("li", { text: t }))));
if (r.notes.length) nodes.push(h("ul", { class: "notes muted small" }, ...r.notes.map(t => h("li", { text: t }))));
return nodes;
}
function renderSummaries() {
document.querySelectorAll(".summary-slot").forEach(slot => slot.replaceChildren(...summaryNodes()));
}
// ---- Views ----
function welcomeView() {
const enter = h("button", { type: "button", class: "btn big", text: "Enter my numbers" });
enter.addEventListener("click", () => { Object.assign(view, { mode: "wizard", step: 0 }); render(); });
const sample = h("button", { type: "button", class: "btn secondary big", text: "Try a sample student" });
sample.addEventListener("click", trySample);
const open = h("button", { type: "button", class: "linkish", text: "Open a saved file" });
open.addEventListener("click", () => $("open-input").click());
return enterOnce(h("div", { class: "card welcome" },
h("div", {},
h("h2", { text: "Will your money last until the semester ends?" }),
h("p", { text: "Four short steps, about five minutes, using numbers from myUK and a pay stub. The planner follows your cash week by week and finds the cheapest way to close any gap: borrow, work more, or do nothing." }),
h("div", { class: "choice-row" }, enter, sample, open),
h("p", { class: "muted small", text: "Nothing you type leaves this page. Save a file to keep your numbers." })),
welcomeArt()), "welcome");
}
// A sketch of what the planner draws (not anyone's numbers): cash that dips below the cushion, and the fix that doesn't.
function welcomeArt() {
return sv("svg", { class: "welcome-art", viewBox: "0 0 360 230", "aria-hidden": "true", focusable: "false" },
sv("rect", { class: "wa-panel", x: 0, y: 0, width: 360, height: 230, rx: 14 }),
...[60, 100, 140, 180].map(y => sv("line", { class: "wa-grid", x1: 24, x2: 336, y1: y, y2: y })),
sv("rect", { class: "wa-below", x: 24, y: 112, width: 312, height: 92 }),
sv("line", { class: "wa-cushion", x1: 24, x2: 336, y1: 112, y2: 112 }),
sv("text", { class: "wa-text", x: 332, y: 106, "text-anchor": "end" }, "Your cushion"),
sv("path", { class: "wa-s2", d: "M28 92 L66 100 L104 98 L130 132 L176 128 L206 160 L248 156 L276 184 L332 178" }),
sv("path", { class: "wa-s1", d: "M28 92 L66 84 L104 80 L130 88 L176 78 L206 80 L248 70 L276 74 L332 58" }),
sv("circle", { class: "wa-dot", cx: 130, cy: 132, r: 5 }),
sv("circle", { class: "wa-end", cx: 332, cy: 58, r: 5 }),
sv("text", { class: "wa-text", x: 28, y: 36 }, "Your cash, week by week"));
}
function wizardView() {
const body = h("div", { id: "step-body" });
drawStep(body);
const last = view.step === STEPS.length - 1;
const back = h("button", { type: "button", class: "btn secondary", text: "Back" });
back.hidden = view.step === 0;
back.addEventListener("click", () => { view.step -= 1; render(); window.scrollTo(0, 0); });
const next = h("button", { type: "button", class: "btn", text: last ? "See my plan" : `Next: ${STEPS[view.step + 1].title}` });
next.addEventListener("click", () => {
if (last) { showPlan(); return; }
view.step += 1;
render();
window.scrollTo(0, 0);
});
const sampleLink = h("button", { type: "button", class: "linkish", text: "Try a sample student instead" });
sampleLink.addEventListener("click", trySample);
return h("div", {},
h("div", { class: "title-row" }, h("h2", { text: "Your numbers" }), sampleLink),
stepNav(),
h("div", { class: "wizard-grid" },
h("div", { class: "card" }, body, h("div", { class: "step-actions" }, back, next)),
h("aside", { class: "card summary summary-slot", "aria-label": "What the planner knows so far" })));
}
// ---- Results (Stage 4) ----
let resultsTimer = null;
const scheduleResults = () => { clearTimeout(resultsTimer); resultsTimer = setTimeout(renderResults, 150); };
function optionCards(R) {
const { opts, c, rec, d } = R, r = opts.recommended, hrs = Results.hrs, gross = Results.gross;
const plan = Results.planName(R), fastYears = CONFIG.product.fastPayoffMonths / 12;
// Each card is one choice in a pick-one group: picking it puts that option on the chart (see Explore below).
// Named by its title and big figure; everything else on the card (costs, payments, warnings, notes) is its
// description, so screen readers hear the whole card, not just the name.
const card = (key, title, big, sub, body = [], cls = "") => {
const id = `opt${++uid}`;
return h("div", { class: "option " + cls, role: "radio", "data-key": key, "aria-checked": "false", tabindex: "-1",
"aria-labelledby": `${id}-t ${id}-b`, "aria-describedby": `${id}-d` },
h("h4", { id: `${id}-t` }, title, cls === "rec" ? h("span", { class: "badge", text: "Recommended" }) : null),
h("p", { class: "big", id: `${id}-b`, text: big }),
h("div", { class: "option-desc", id: `${id}-d` }, sub ? h("p", { class: "sub", text: sub }) : null, ...body),
h("p", { class: "on-chart", "aria-hidden": "true" }, chartIcon(), "On the chart"));
};
const chip = (text, kind) => h("span", { class: `chip ${kind}`, text });
const costs = p => {
const lines = [];
if (p.sub_net > 0) lines.push(h("p", { class: "small", text: `Subsidized: ${Fmt.money(gross(p.sub_net))} (${Fmt.money(p.sub_net)} after the fee)` }));
if (p.unsub_net > 0) lines.push(h("p", { class: "small", text: `Unsubsidized: ${Fmt.money(gross(p.unsub_net))} (${Fmt.money(p.unsub_net)} after the fee)` }));
lines.push(h("dl", { class: "costs" },
h("dt", { text: `Paid off over ${fastYears} years` }), h("dd", { text: `${Fmt.money(p.fast.pmt, true)} a month, ${Fmt.money(p.fast.cost)} interest and fees` }),
h("dt", { text: `On ${plan}` }), h("dd", { text: `${Fmt.money(p.plan.pmt, true)} a month, ${Fmt.money(p.plan.cost)} interest and fees` })));
return lines;
};
const hourChips = total => {
const chips = [];
if (total > c.safe_max) chips.push(chip(`Above your safe max of ${hrs(c.safe_max)}`, "warn"));
if (total > CONFIG.product.hoursFlag) chips.push(chip("Nearly impossible", "fail"));
else if (total > CONFIG.product.hoursWarn) chips.push(chip("More than a full-time job", "warn"));
return chips.length ? [h("p", { class: "chips" }, ...chips)] : [];
};
// Covered: nothing to compare.
if (rec.state === "covered") return h("p", { class: "covered-line", text: "You're covered: no extra hours or loans needed this term." });
// The recommendation is one of the two plain options when its numbers match exactly; that card gets the badge
// instead of repeating itself as "Your plan".
const recIsBorrow = (rec.state === "fixed_sub" || rec.state === "fixed_unsub") && !!opts.borrow && !!r
&& opts.borrow.sub_net === r.sub_net && opts.borrow.unsub_net === r.unsub_net;
const recIsWork = rec.state === "fixed_hours" && opts.hours_alone !== null && rec.extra_hours === opts.hours_alone
&& !(r && r.sub_net > 0);
// Why the "Work more" card can need far more hours than the answer's tradeoff line: that line spreads the loan's
// cash over the whole term; the card has to keep every week above the cushion, starting with the first short week.
// Only for the plain loan fix: in the hours-plus-loan mix, the tradeoff's hours replace just the loan, on top of the plan's.
const tradeShown = rec.state === "fixed_unsub" && r && r.V_plan !== null && rec.tradeoff_hours;
const whyNote = tradeShown && (opts.hours_alone === null || opts.hours_alone > rec.tradeoff_hours)
? [h("p", { class: "why-note", text: `Why not the ${hrs(rec.tradeoff_hours)} hours a week above? That spreads the loan's ${Fmt.money(rec.unsub_net)} over the whole term. You'd drop below your cushion ${Results.week(rec.run_out_week)}, before extra pay adds up.` })]
: [];
let work;
if (opts.hours_alone === null) {
work = card("work", "Work more", "Not enough on its own", `Even ${hrs(d.money.hoursCeiling)} hours a week wouldn't keep you above your cushion in time.`, whyNote);
} else {
const total = c.hours + opts.hours_alone;
work = card("work", "Work more", `+${hrs(opts.hours_alone)} hours a week`, `${hrs(total)} hours a week in total. No debt.`,
[...hourChips(total), ...whyNote], recIsWork ? "rec" : "");
}
let borrow;
if (!opts.borrow) borrow = card("borrow", "Borrow", "Not enough on its own", `Even all your remaining federal loan room leaves you ${Fmt.money(opts.borrow_short)} short.`);
else borrow = card("borrow", "Borrow", Fmt.money(opts.borrow.fast.gross),
recIsBorrow && rec.state === "fixed_sub" ? "Subsidized: no interest while you're in school." : "Federal loans, subsidized first. No extra hours.",
costs(opts.borrow), recIsBorrow ? "rec" : "");
if (recIsBorrow || recIsWork) return h("div", { class: "options two", role: "radiogroup", "aria-label": "Pick an option to show on the chart", "data-rec": recIsBorrow ? "borrow" : "work" }, work, borrow);
let best;
switch (rec.state) {
case "fixed_hours": {
const total = c.hours + rec.extra_hours;
best = card("plan", "Your plan", `+${hrs(rec.extra_hours)} hours a week`, `${hrs(total)} hours a week in total.`,
[...(r.sub_net > 0 ? costs(r) : [h("p", { class: "small", text: "No borrowing." })]), ...hourChips(total)], "rec");
break;
}
case "fixed_mix": {
const total = c.hours + rec.extra_hours;
best = card("plan", "Your plan", `+${hrs(rec.extra_hours)} hours and ${Fmt.money(r.fast.gross)}`, `${hrs(total)} hours a week, plus a loan.`,
[...costs(r), ...hourChips(total)], "rec");
break;
}
case "fixed_sub": case "fixed_unsub":
best = card("plan", "Your plan", `Borrow ${Fmt.money(r.fast.gross)}`, rec.state === "fixed_sub" ? "Subsidized: no interest while you're in school." : "No extra hours.", costs(r), "rec");
break;
default:
best = card("plan", "Your plan", "Not enough", `Still ${Fmt.money(rec.short_after_all)} short after working to your max and borrowing all your room. Contact UK Financial Aid about emergency aid.`, [], "rec");
}
return h("div", { class: "options", role: "radiogroup", "aria-label": "Pick an option to show on the chart", "data-rec": "plan" }, work, borrow, best);
}
// ---- Explore (Brian, Nov 12, 2026): pick a card, or move the sliders, to put that option on the chart. ----
// view.pick: "work" | "borrow" | "plan" | "mix" (null = the recommended card). view.mix: { hours, step } once a slider
// moves (null = start at the plan, and follow it as numbers change). Display only: every line is the engine's forecast.
let explore = null; // { R, chartRoot, chartCard, group, mixEl, readout, agTable }
const capOf = room => Math.floor(room * (1 - CONFIG.loan.fee) * 100) / 100; // most cash a loan room delivers
const loanCapOf = c => Engine.pyRound(capOf(c.sub_room) + capOf(c.unsub_room), 2);
// The hours and loan cash behind each choice, with its chart label.
function scenario(R, key) {
const { c, rec, opts, d } = R, hrs = Results.hrs;
switch (key) {
case "work":
return opts.hours_alone !== null ? { hours: opts.hours_alone, net: 0, label: `Work more: +${hrs(opts.hours_alone)} hours a week` }
: { hours: Math.max(0, d.money.hoursCeiling - c.hours), net: 0, label: `Work more: ${hrs(d.money.hoursCeiling)} hours a week` };
case "borrow":
return opts.borrow ? { hours: 0, net: Engine.pyRound(opts.borrow.sub_net + opts.borrow.unsub_net, 2), label: `Borrow ${Fmt.money(opts.borrow.fast.gross)}` }
: { hours: 0, net: loanCapOf(c), label: "Borrow all your federal loan room" };
case "mix": {
const m = mixValues(R);
return { hours: m.hours, net: m.net, label: `Your mix: +${hrs(m.hours)} hours, ${Fmt.money(m.gross)} loan` };
}
default:
if (rec.state === "covered") return { hours: 0, net: 0, label: "" };
if (rec.state === "short_beyond_limits") return { hours: Math.max(0, c.safe_max - c.hours), net: loanCapOf(c), label: "Your plan: safe max and all your loan room" };
return { hours: rec.extra_hours ?? 0, net: Engine.pyRound((rec.sub_net ?? 0) + (rec.unsub_net ?? 0), 2), label: "Your plan" };
}
}
// The sliders' values: extra hours (0 to the hours ceiling, in half hours) and loan cash ($10 steps up to all
// remaining federal room, subsidized first; the last step is the exact room).
function mixValues(R) {
const { c, d } = R, maxH = Math.max(0, d.money.hoursCeiling - c.hours), cap = loanCapOf(c), steps = Math.ceil(cap / 10);
const start = view.mix || (() => { const p = scenario(R, "plan"); return { hours: p.hours, step: Math.ceil(p.net / 10) }; })();
const hours = Math.min(Math.max(0, start.hours), maxH), step = Math.min(Math.max(0, start.step), steps);
const net = Engine.pyRound(Math.min(step * 10, cap), 2), subCap = capOf(c.sub_room);
const sub = Engine.pyRound(Math.min(net, subCap), 2), unsub = Engine.pyRound(net - sub, 2);
return { hours, step, steps, maxH, net, sub, unsub, gross: Results.gross(sub) + Results.gross(unsub) };
}
// Interest and fees for a subsidized + unsubsidized pair, paid off fast and on the student's plan (as the cards).
function priceMix(R, sub, unsub) {
const c = R.c, out = {};
for (const [label, months] of [["fast", CONFIG.product.fastPayoffMonths], ["plan", R.planMonths]]) {
const parts = (sub > 0 ? [Engine.loanCost(sub, c.grace_end, months, true, c.disb)] : [])
.concat(unsub > 0 ? [Engine.loanCost(unsub, c.grace_end, months, false, c.disb)] : []);
out[label] = { months, pmt: Engine.pyRound(Engine.pySum(parts.map(p => p.pmt)), 2), cost: Engine.pyRound(Engine.pySum(parts.map(p => p.cost)), 2) };
}
return out;
}
// Lowest counted week for a choice, against the cushion.
function lowPoint(R, s) {
const [S, low] = Engine.shortfall(Engine.forecast(R.c, s.hours, s.net), R.c.cushion, R.c.disb);
return { S, cash: low[2], week: low[1] };
}
// Put the current choice on the chart and keep the cards, mix panel, readout and After-graduation column in step.
let readoutTimer = null;
function applyPick({ glow = false } = {}) {
if (!explore) return;
const { R, chartRoot, chartCard, group, mixEl, readout, jump, yExtra, agTable } = explore;
const covered = R.rec.state === "covered", recKey = group ? group.dataset.rec : null;
const keys = group ? [...group.querySelectorAll("[data-key]")].map(el => el.dataset.key) : [];
const pick = view.pick === "mix" || keys.includes(view.pick) ? view.pick : recKey;
if (group) {
const focusKey = keys.includes(pick) ? pick : recKey;
group.querySelectorAll("[data-key]").forEach(el => {
el.setAttribute("aria-checked", el.dataset.key === pick ? "true" : "false");
el.tabIndex = el.dataset.key === focusKey ? 0 : -1;
});
}
mixEl.classList.toggle("is-on", pick === "mix");
const s = pick && !(covered && pick !== "mix") ? scenario(R, pick) : null;
const label = s ? s.label + (pick === recKey ? " (recommended)" : "") : "";
Chart.draw(chartRoot, { ...R, fix: s ? Engine.forecastDetail(R.c, s.hours, s.net) : null, fixLabel: label, yExtra });
const flash = () => { chartCard.classList.remove("flash"); void chartCard.offsetWidth; chartCard.classList.add("flash"); };
if (glow) flash();
// Under the cards: what the chart above is showing, with a link up to it.
if (jump) {
const title = group.querySelector(`[data-key="${pick}"] h4`)?.firstChild?.textContent;
const name = pick === "mix" ? "your mix" : `"${title || "Your plan"}"`;
const see = h("button", { type: "button", class: "linkish inline", text: "See it on the chart" });
see.addEventListener("click", () => { chartCard.scrollIntoView({ block: "start" }); flash(); });
jump.replaceChildren(chartIcon(), ` Showing ${name} on the chart above. `, see);
}
if (agTable) agTable.dataset.pick = pick === "work" ? "nothing_extra" : "this_plan";
// The readout waits a moment so a dragged slider is read out once, not at every step.
clearTimeout(readoutTimer);
readoutTimer = setTimeout(() => {
if (!s) { readout.replaceChildren(covered ? "Move a slider below to see what extra hours or a loan would do." : ""); return; }
const lp = lowPoint(R, s), cushion = Fmt.money(R.c.cushion);
const where = lp.S > 0 ? `about ${Fmt.money(lp.S)} below your ${cushion} cushion.`
: lp.cash - R.c.cushion < 0.5 ? `right at your ${cushion} cushion.` : `${Fmt.money(lp.cash - R.c.cushion)} above your ${cushion} cushion.`;
readout.replaceChildren(h("strong", { text: "On the chart: " }), `${label}. Your lowest week would be ${Fmt.money(lp.cash)} (${Fmt.dateShort(lp.week)}), ${where}`);
}, 200);
}
let applyQueued = false;
// Coalesce slider moves into one redraw every ~30ms (a timer, not requestAnimationFrame, which pauses in hidden tabs).
const queueApply = () => { if (!applyQueued) { applyQueued = true; setTimeout(() => { applyQueued = false; applyPick(); }, 30); } };
// Cards: click, Enter or Space picks; arrow keys move to the next card and pick it (a radio group).
function wireCards(group) {
const cards = () => [...group.querySelectorAll("[data-key]")];
const choose = (el, glow = true) => { view.pick = el.dataset.key; applyPick({ glow }); };
group.addEventListener("click", e => { const el = e.target.closest("[data-key]"); if (el) choose(el); });
group.addEventListener("keydown", e => {
const el = e.target.closest("[data-key]");
if (!el) return;
const list = cards(), i = list.indexOf(el);
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); choose(el); }
else if (["ArrowRight", "ArrowDown", "ArrowLeft", "ArrowUp"].includes(e.key)) {
e.preventDefault();
const next = list[(i + (e.key === "ArrowRight" || e.key === "ArrowDown" ? 1 : list.length - 1)) % list.length];
choose(next, false);
next.focus();
}
});
}
// "Try your own mix": two sliders that put any hours-and-loan combination on the chart.
function mixPanel(R) {
const hrs = Results.hrs, m0 = mixValues(R);
const hoursIn = h("input", { type: "range", id: "mix-hours", min: "0", max: String(m0.maxH), step: "0.5", value: String(m0.hours) });
const loanIn = h("input", { type: "range", id: "mix-loan", min: "0", max: String(m0.steps), step: "1", value: String(m0.step) });
hoursIn.disabled = m0.maxH <= 0;
loanIn.disabled = m0.steps <= 0;
const hoursOut = h("output", { class: "mix-value", for: "mix-hours" }), loanOut = h("output", { class: "mix-value", for: "mix-loan" });
const chips = h("p", { class: "chips" }), cost = h("p", { class: "mix-cost small" });
const el = h("section", { class: "mix", "aria-labelledby": "mix-title" },
h("div", { class: "mix-head" }, h("h4", { id: "mix-title", text: "Try your own mix" }),
h("span", { class: "on-chart", "aria-hidden": "true" }, chartIcon(), "On the chart")),
h("p", { class: "muted small mix-intro", text: "Move either slider to put your own mix on the chart. Loans here are federal only, subsidized first." }),
h("div", { class: "mix-row" }, h("label", { for: "mix-hours", text: "Extra hours a week" }), hoursIn, hoursOut),
h("div", { class: "mix-row" }, h("label", { for: "mix-loan", text: "Federal loan this term" }), loanIn, loanOut),
chips, cost);
const show = () => {
const m = mixValues(R), total = R.c.hours + m.hours, safe = R.c.safe_max;
hoursOut.textContent = `+${hrs(m.hours)} (${hrs(total)} total)`;
hoursIn.setAttribute("aria-valuetext", `${hrs(m.hours)} extra hours a week, ${hrs(total)} in total`);
loanOut.textContent = m.net > 0 ? `${Fmt.money(m.gross)} (${Fmt.money(m.net)} after the fee)` : "$0";
loanIn.setAttribute("aria-valuetext", m.net > 0 ? `${Fmt.money(m.gross)} loan, ${Fmt.money(m.net)} after the fee` : "No loan");
const c = [];
if (total > safe) c.push(h("span", { class: "chip warn", text: `Above your safe max of ${hrs(safe)}` }));
if (total > CONFIG.product.hoursFlag) c.push(h("span", { class: "chip fail", text: "Nearly impossible" }));
else if (total > CONFIG.product.hoursWarn) c.push(h("span", { class: "chip warn", text: "More than a full-time job" }));
chips.replaceChildren(...c);
chips.hidden = !c.length;
if (m.steps <= 0) cost.textContent = "No federal loan room left this term.";
else if (m.net <= 0) cost.textContent = "No loan.";
else {
const p = priceMix(R, m.sub, m.unsub), kinds = [m.sub > 0 ? `${Fmt.money(Results.gross(m.sub))} subsidized` : "", m.unsub > 0 ? `${Fmt.money(Results.gross(m.unsub))} unsubsidized` : ""].filter(Boolean).join(" + ");
cost.textContent = `Loan: ${kinds}. About ${Fmt.money(p.fast.cost)} in interest and fees over ${CONFIG.product.fastPayoffMonths / 12} years once payments start (${Fmt.money(p.fast.pmt, true)} a month), or ${Fmt.money(p.plan.cost)} on ${Results.planName(R)} (${Fmt.money(p.plan.pmt, true)} a month).`;
}
};
const onMove = () => { view.mix = { hours: +hoursIn.value, step: +loanIn.value }; view.pick = "mix"; show(); queueApply(); };
hoursIn.addEventListener("input", onMove);
loanIn.addEventListener("input", onMove);
// Page Up / Page Down jump 5 hours or $500 (arrow keys still move half an hour or $10).
const bigSteps = (input, by) => input.addEventListener("keydown", e => {
if (e.key !== "PageUp" && e.key !== "PageDown") return;
e.preventDefault();
input.value = String(Math.min(+input.max, Math.max(+input.min, +input.value + (e.key === "PageUp" ? by : -by))));
onMove();
});
bigSteps(hoursIn, 5);
bigSteps(loanIn, 50);
show();
return el;
}
// Shown only when the answer's tradeoff line doesn't already give the same value per hour.
// If the tradeoff line already gives a per-hour figure, a second, different one would only confuse (e.g. $6.81 vs
// $4.22 when subsidized loans plus hours is the fix), so the line is left out.
function valueLine(R) {
const trade = Results.tradeoff(R) || "";
return /\$[\d,]+\.\d\d/.test(trade) ? "" : valueLineText(R);
}
function valueLineText(R) {
const r = R.opts.recommended, plan = Results.planName(R);
if (r && r.sub_net + r.unsub_net > 0 && r.V_plan !== null) {
return `Value of an hour: each hour you work instead of borrowing saves about ${Fmt.money(r.V_plan, true)} in interest and fees, on ${plan}.`;
}
if (R.rec.state === "fixed_hours" && R.opts.borrow && R.opts.borrow.V_plan !== null) {
return `Value of an hour: borrowing instead would cost about ${Fmt.money(R.opts.borrow.V_plan, true)} for each hour of work it replaces, on ${plan}.`;
}
return "";
}
// ---- Aid you're protecting (Stage 5) ----
function aidSection() {
const d = store.data, A = Inputs.aidStatus(d), K = CONFIG.kees;
const statusChip = st => h("span", { class: `chip ${st === "safe" ? "pass" : st === "risk" ? "fail" : "warn"}`,
text: st === "safe" ? "✓ Safe" : st === "risk" ? "At risk" : "Check" });
const parts = [
h("h3", { class: "flush" }, "Aid you're protecting"),
h("p", { class: "muted", text: "These awards come with rules. Every estimate on this page assumes you keep them. If you lose one, mark it not accepted under \"Edit my numbers\" to see your new plan." }),
];
if (A.total > 0) parts.push(h("p", { class: "aid-total" }, h("strong", { text: Fmt.money(A.total) }), " a year depends on keeping your GPA and credit hours."));
if (A.rows.length) {
parts.push(h("div", { class: "tbl flush-tbl" }, h("table", { class: "aid-table" },
h("thead", {}, h("tr", {}, ...["Award", "Per year", "To keep it", "Status"].map(t => h("th", { text: t })))),
h("tbody", {}, ...A.rows.map(r => h("tr", {},
h("td", { text: r.name }), h("td", { class: "num", text: Fmt.money(r.perYear) }), h("td", { text: r.rule }),
h("td", {}, statusChip(r.status), " ", h("span", { class: "small", text: r.detail }))))))));
}
if (A.kees) {
const k = A.kees, gpa = d.profile.gpa;
const lad = [
[`${K.fullGpa.toFixed(1)} or higher`, "Full award"],
[`${K.minGpa.toFixed(1)} to ${(K.fullGpa - 0.01).toFixed(2)}, on track to graduate`, "Full award"],
[`${K.minGpa.toFixed(1)} to ${(K.fullGpa - 0.01).toFixed(2)}, not on track, full-time in one of your last two terms`, `${K.partialShare * 100}% of the award`],
[`${K.minGpa.toFixed(1)} to ${(K.fullGpa - 0.01).toFixed(2)}, otherwise`, "No award"],
[`Below ${K.minGpa.toFixed(1)}`, "No award"],
];
const youRows = k.row === "2or3" ? [2, 3] : k.row === "1to3" ? [1, 2, 3] : k.row === null ? [] : [k.row];
const ladder = h("table", { class: "ladder" },
h("thead", {}, h("tr", {}, h("th", { text: "Cumulative GPA at the end of spring" }), h("th", { text: "Next year's KEES" }), h("th", { text: "" }))),
h("tbody", {}, ...lad.map(([cond, result], i) => h("tr", { class: youRows.includes(i) ? "you" : "" },
h("td", { text: cond }), h("td", { text: result }), h("td", { class: "small", text: youRows.includes(i) ? "◀ You" : "" })))));
let status;
if (gpa === null) status = "Add your GPA in step 1 to see where you are on the ladder.";
else if (k.share === 1) status = `At a ${gpa.toFixed(2)} GPA you keep the full award next year (${Fmt.money(k.perYear)}).`;
else if (k.share === K.partialShare) status = `At a ${gpa.toFixed(2)} GPA and not on track, you'd keep half next year (${Fmt.money(k.perYear * K.partialShare)} of ${Fmt.money(k.perYear)}).`;
else if (k.share === 0) status = `At a ${gpa.toFixed(2)} GPA you'd lose next year's award (${Fmt.money(k.perYear)}).`;
else if (k.row === "2or3") status = `At a ${gpa.toFixed(2)} GPA and not on track, you'd keep half (${Fmt.money(k.perYear * K.partialShare)}) if you were full-time in one of your last two terms, otherwise none. Answer that question in step 3.`;
else status = `At a ${gpa.toFixed(2)} GPA, next year's award depends on whether you're on track. Add your year in school in step 1.`;
let track = "";
if (k.onTrack !== null) {
const have = `You'll have ${k.earned} earned credit hours by the end of this term (${k.past} before${k.assumed ? `, assumed at ${CONFIG.product.creditsPerSemester} a semester` : ""}, plus ${k.term} now)`;
track = k.need === null
? `UK doesn't check "on track to graduate" in your first year, so you count as on track. ${have}.`
: `UK's on-track rule for year ${Math.min(k.year, 4)}${k.year > 4 ? " and later" : ""}: at least ${k.need} earned credit hours by the end of spring. ${have}: ${k.onTrack ? "on track" : `${k.need - k.earned} short`}.`;
}
parts.push(h("section", { class: "kees" },
h("h4", {}, "KEES ", tip("kees"), h("span", { class: "muted small", text: ` ${Fmt.money(k.perYear)} a year (${Fmt.money(k.perTerm)} this term)` })),
h("p", { class: "kees-status", text: status }),
track ? h("p", { class: "small", text: track }) : null,
fold({ key: "kees-rules", title: "See the KEES rules", note: "who keeps the full award, half, or none", level: 5 },
h("div", { class: "tbl flush-tbl" }, ladder),
h("p", { class: "muted small", text: `KEES is checked once a year, at the end of spring, on your cumulative GPA. It pays for at most ${K.maxTerms} terms, and must be used within ${K.yearsFromHighSchool} years of your high school graduation. UK's KEES page also lists ${K.minGpa.toFixed(1)} as a full-award line; this planner uses ${K.fullGpa.toFixed(1)} until that's confirmed.` }))));
}
if (!A.rows.length && !A.kees) {
parts.push(h("p", { text: "None of your awards list a GPA or credit-hour rule. If one does, add the rule under \"Edit my numbers\", step 3." }));
}
const under = A.under.filter(u => u.total > 0);
if (under.length) {
parts.push(h("section", { class: "under12" }, fold(
{ key: "under12", title: "What dropping below 12 credit hours would cost this term", note: "This planner never recommends it.", level: 4 },
h("p", { class: "small", text: "The amounts are this term's aid you'd lose:" }),
h("div", { class: "tbl flush-tbl" }, h("table", { class: "aid-table" },
h("thead", {}, h("tr", {}, ...["Credit hours", "Awards with a 12-hour rule", "KEES (prorated)", "Total this term"].map(t => h("th", { text: t })))),
h("tbody", {}, ...A.under.map(u => h("tr", {},
h("td", { text: String(u.hours) }), h("td", { class: "num", text: u.rules ? "−" + Fmt.money(u.rules) : "$0" }),
h("td", { class: "num", text: u.kees ? "−" + Fmt.money(u.kees) : "$0" }),
h("td", { class: "num strong", text: "−" + Fmt.money(u.total) })))))),
h("p", { class: "muted small", text: `UK says KEES "will reduce proportionally" at 6 to 11 credit hours; the planner uses hours ÷ 12. Under ${K.minHours} hours it pays nothing that term. Pell grants and federal loan limits can also shrink below full-time; ask UK Financial Aid for your numbers.` }))));
}
return h("div", { class: "card aid-card" }, ...parts);
}
// ---- After graduation (Stage 6) ----
function afterGradSection(R) {
const d = store.data, four = R.four, fy = R.fy, hrs = Results.hrs, c = R.c, pv = R.priv, shorts = R.shorts;
const privInstead = !!four.nothing_extra.private, privThis = !!four.this_plan.private;
const plans = [["full_offer", "Accept the full loan offer"], ["this_plan", "This plan"],
["nothing_extra", privInstead ? "Private loan instead" : "Borrow nothing extra"]];
const extra = fy.extra_sub + fy.extra_unsub > 0;
const safe = hrs(c.safe_max), o = R.opts;
const springs = fy.years.filter(y => y.spring !== null).length;
const sub = {
full_offer: "The most you could borrow each year",
this_plan: privThis ? "All your federal room, plus a private loan for the rest"
: R.rec.state === "short_beyond_limits" ? (extra ? "All your remaining federal room, again each spring" : "No federal loan room left this term")
: extra ? "This term's fix, again each spring" : "No new loans this term",
nothing_extra: privInstead ? "The same money as this plan, from a private lender"
: o.hours_alone === 0 ? "No extra hours needed this term"
: o.safe_hours_alone !== null ? `Needs +${hrs(o.safe_hours_alone)} hours a week this term`
: o.hours_alone !== null ? `Would take +${hrs(o.hours_alone)} hours a week, over your ${safe}-hour safe max`
: "Even the most hours you'd consider can't close this term's gap",
};
const shortCol = k => shorts[k] > 0;
const anyShort = plans.some(([k]) => shortCol(k)), anyPriv = privInstead || privThis;
const length = x => {
const fed = fy.own_years ? `${x.months / 12} years (your plan)` : `${x.months / 12}-year standard`;
if (!x.private) return fed;
return x.sub_borrowed + x.unsub_borrowed > 0 ? `${fed}; private ${x.private.months / 12} years` : `Private ${x.private.months / 12} years`;
};
const rowsDef = [
anyShort ? [`Still short each spring, even at your ${safe}-hour safe max`, (x, k) => Fmt.money(shorts[k]), "strong short-row"] : null,
["Subsidized borrowed", x => Fmt.money(x.sub_borrowed), "", "subsidized"],
["Unsubsidized borrowed", x => Fmt.money(x.unsub_borrowed), "", "unsubsidized"],
anyPriv ? ["Private borrowed", x => Fmt.money(x.private ? x.private.borrowed : 0), "", "privateLoan"] : null,
["Total borrowed", x => Fmt.money(x.borrowed), "strong"],
["Fees taken out first", x => Fmt.money(x.fees), "", "originationFee"],
["Interest built up before payments start", x => Fmt.money(x.accrued), "", "grace"],
["Repayment", x => length(x)],
["Monthly payment", x => Fmt.money(x.payment, true), "strong"],
["Total interest", x => Fmt.money(x.interest)],
["Total you repay", x => Fmt.money(x.total_repaid), "strong"],
["Paid off", x => Fmt.monthYear(x.payoff_date)],
].filter(Boolean);
const cellClass = (k, isShortRow) => [`col-${k}`, k === "this_plan" ? "this" : "", shortCol(k) ? (isShortRow ? "has-short" : "is-short") : ""].filter(Boolean).join(" ");
const table = h("table", { class: "compare" },
h("thead", {}, h("tr", {}, h("th", { text: "" }), ...plans.map(([k, name]) =>
h("th", { class: `col-${k}${k === "this_plan" ? " this" : ""}` }, h("span", { class: "plan-name", text: name }), h("span", { class: "plan-sub", text: sub[k] }),
shortCol(k) ? h("span", { class: "plan-flag", text: "Doesn't cover your bills" }) : null)))),
h("tbody", {}, ...rowsDef.map(([label, fmt, cls, tipKey]) => h("tr", { class: cls || "" },
h("th", { scope: "row" }, label, tipKey ? tip(tipKey) : null),
...plans.map(([k]) => h("td", { class: cellClass(k, (cls || "").includes("short-row")), text: fmt(four[k], k) }))))));
// The verdict never lets a plan that leaves you short look like the cheap choice (Brian, Nov 12, 2026).
const cost = x => Engine.pyRound(x.interest + x.fees, 2);
const vsNothing = cost(four.this_plan) - cost(four.nothing_extra), vsFull = cost(four.full_offer) - cost(four.this_plan);
const gradText = Fmt.date(d.profile.graduationDate);
const byGrad = s => (springs > 1 ? `, about ${Fmt.money(s * springs)} over your ${springs} springs` : "");
const verdicts = [];
if (shortCol("this_plan")) {
verdicts.push(`Even this plan, with all your federal room and working ${safe} hours a week, leaves you about ${Fmt.money(shorts.this_plan)} short each spring${byGrad(shorts.this_plan)}. Talk to UK Financial Aid about emergency aid and UK's own loans.`
+ (shortCol("full_offer") ? "" : " The full federal offer would cover it, if your school offers you that much."));
} else if (privThis) {
verdicts.push(`Federal loans can't cover it all, so this plan adds a ${Fmt.money(four.this_plan.private.cash_each_spring)} private loan each spring at the ${Results.pct(pv.rate)} you were quoted.`);
}
if (four.compare) {
const k = four.compare, diff = k.private - k.federal;
verdicts.push(`Getting the same ${Fmt.money(k.cash_each_spring)} each spring from a private lender at ${Results.pct(pv.rate)} would cost about ${Fmt.money(k.private)} in interest and fees, against about ${Fmt.money(k.federal)} for this plan's federal loans, both repaid over ${k.months / 12} years: ${diff >= 0 ? `about ${Fmt.money(diff)} more` : `about ${Fmt.money(-diff)} less`}.`
+ (diff < 0 ? " That's cheaper only on paper: most private loans need a cosigner, and you'd give up federal options for lowering or pausing payments." : ""));
} else if (shortCol("nothing_extra") && extra && !shortCol("this_plan")) {
verdicts.push(`Borrowing nothing extra looks cheaper only because it leaves you about ${Fmt.money(shorts.nothing_extra)} short each spring, even working ${safe} hours a week${byGrad(shorts.nothing_extra)}. This plan covers your bills${shortCol("full_offer") ? "" : ` and costs about ${Fmt.money(vsFull)} less in interest and fees than accepting the full offer`}.`);
} else if (!shortCol("this_plan") && !privThis) {
verdicts.push(extra
? `Over the life of the loans, this plan costs about ${Fmt.money(vsNothing)} more in interest and fees than borrowing nothing extra, and about ${Fmt.money(vsFull)} less than accepting the full offer.`
: `This plan borrows nothing new, so it matches "Borrow nothing extra". Accepting the full offer would cost about ${Fmt.money(vsFull)} more in interest and fees.`);
}
const verdict = verdicts.join(" ");
const first = +d.school.termEnd.slice(0, 4) + (+d.school.termEnd.slice(5, 7) >= 7 ? 1 : 0);
const notes = [
`Assumes every year until you graduate (${gradText}) looks like this one: the same loans you've accepted${extra ? ", plus this term's new loan again each spring" : ""}. Update your numbers each year for a sharper estimate.`,
`${(CONFIG.loan.rate * 100).toFixed(2)}% interest and a ${(CONFIG.loan.fee * 100).toFixed(3)}% fee are the 2026–27 federal values. Later years' rates are set each July 1; change them below when they're announced.`,
"The full offer is the federal maximum for each year in school. Your real offer may be lower, especially for subsidized loans, which depend on need.",
`Fall loan dates use UK's calendar for 2026 and 2027, then Aug 23 each year (an estimate).`,
"Interest that builds up while you're in school isn't added to your balance when payments start (true for Direct Loans since July 2023; still to be confirmed).",
];
if (fy.years[fy.years.length - 1].spring === null) notes.push("You graduate in the fall, so your last year has a fall loan only.");
if (fy.prior.length) notes.push("Loans from earlier years are assumed to have the same rate (an estimate).");
if (anyShort) notes.push(`"Still short each spring" repeats this term's shortfall (below your ${Fmt.money(c.cushion)} cushion) every spring, working up to your safe max. A plan that leaves you short isn't really cheaper: that money still has to come from somewhere.`);
if (anyPriv) {
notes.push(`Private loan: the ${Results.pct(pv.rate)} fixed rate you were quoted${pv.fee > 0 ? `, a ${Results.pct(pv.fee)} fee` : ", no fee"}; interest builds daily from each spring's aid date${pv.capitalize ? " and is added to your balance when payments start" : " and is paid off first once payments start"}; payments start ${pv.graceMonths} months after graduation; repaid over ${pv.years ? `${pv.years} years (your choice)` : "the same length as your federal loans"}. Each spring is assumed to need the same private loan. Check your lender's actual terms.`);
notes.push("Most private loans need a cosigner unless you have a good credit history, and they don't have federal options for lowering or pausing payments. The monthly payment adds federal and private payments while both are being repaid.");
} else if (shortCol("nothing_extra") && !pv) {
notes.push("If a lender has quoted you a private loan rate, you can enter it under Your aid (Private loan) to compare. For most students, federal loans are the better option.");
}
// Later years' rate and fee, editable (blank = the 2026–27 value).
const rateRow = (y, i) => {
const label = `${first - 1 + i}–${String(first + i).slice(2)}`;
const cell = (key, dflt, step) => {
if (i === 0) return h("td", { class: "muted", text: `${dflt} (set)` });
const fd = Schema.byPath[`future.${key}`];
const path = `future.${key}.${i}`;
const input = h("input", { type: "number", step, min: String(fd.min), max: String(fd.max), placeholder: String(dflt),
"data-path": path, "aria-label": `${key === "rates" ? "Interest rate" : "Fee"} for ${label}, percent` });
const cur = d.future[key][i];
input.value = cur === null || cur === undefined ? "" : String(cur);
input.addEventListener("input", () => {
const list = [...d.future[key]];
while (list.length <= i) list.push(null);
list[i] = input.value === "" ? null : input.validity.badInput ? NaN : Number(input.value);
const bad = Schema.check(fd, list);
input.setAttribute("aria-invalid", bad ? "true" : "false");
if (!bad) store.set(`future.${key}`, list);
});
return h("td", {}, input);
};
return h("tr", {}, h("td", { text: label }), h("td", { text: y.level === 3 ? "3rd or later" : `${y.level === 1 ? "1st" : "2nd"}` }),
h("td", { text: `${Fmt.money(y.accepted_sub + y.accepted_unsub)} a year` }),
cell("rates", (CONFIG.loan.rate * 100).toFixed(2), "0.01"), cell("fees", (CONFIG.loan.fee * 100).toFixed(3), "0.001"));
};
const rates = h("details", { class: "rates" }, h("summary", { text: "Change rates for later school years" }),
h("div", { class: "tbl flush-tbl" }, h("table", { class: "rates-table" },
h("thead", {}, h("tr", {}, ...["School year", "Year in school", "Loans you've accepted", "Interest rate (%)", "Fee (%)"].map(t => h("th", { text: t })))),
h("tbody", {}, ...fy.years.map(rateRow)))),
h("p", { class: "muted small", text: "Leave a box blank to use the 2026–27 value." }));
rates.open = view.ratesOpen;
rates.addEventListener("toggle", () => { view.ratesOpen = rates.open; });
return h("div", { class: "card after-grad" },
h("h3", { class: "flush", text: "After graduation" }),
h("p", { class: "muted", text: `If you borrow like this every year until you graduate. Loan payments start ${Fmt.date(fy.grace_end)}.` }),
h("div", { class: "tbl flush-tbl" }, table),
h("p", { class: "verdict", text: verdict }),
fold({ key: "ag-notes", title: "What this table assumes", note: `${notes.length} notes`, level: 4 },
h("ul", { class: "notes muted small" }, ...notes.map(t => h("li", { text: t })))),
rates);
}
// A closed-by-default section: its title (and a short note on what's inside) shows; the rest opens on click.
// Open ones stay open while the results redraw.
const folds = {};
function fold({ key, title, note, level = 3 }, ...content) {
const d = h("details", { class: "fold", "data-fold": key },
h("summary", {}, h(`h${level}`, { class: "fold-title", text: title }), note ? h("span", { class: "fold-note", text: note }) : null),
h("div", { class: "fold-body" }, ...content));
d.open = !!folds[key];
d.addEventListener("toggle", () => { folds[key] = d.open; });
return d;
}
// Printing opens every closed section, then puts them back.
let printOpened = [];
window.addEventListener("beforeprint", () => {
printOpened = [...document.querySelectorAll("details.fold:not([open])")];
printOpened.forEach(d => { d.open = true; });
});
window.addEventListener("afterprint", () => { printOpened.forEach(d => { d.open = false; }); printOpened = []; });
// One answer tile (problem or fix). The same tiles show big in the answer card and small beside the editor.
const statTile = t => h("div", { class: `stat ${t.tone}` },
h("p", { class: "stat-label" }, icon(t.icon), t.label),
h("p", { class: `stat-figure${t.words ? " words" : ""}`, text: t.figure }),
h("p", { class: "stat-sub", text: t.sub }));
// The answer beside the editor (and pinned above it in narrow windows), refreshed with every result.
// A changed answer glows once and is read out politely, but only while the editor is open.
let lastLive = "";
function renderLive(sm) {
const text = sm ? sm.tiles.map(t => `${t.label}: ${t.figure}, ${t.sub}`).join(". ") + "." : "A few numbers are still missing.";
const changed = lastLive !== "" && text !== lastLive;
lastLive = text;
const glow = el => { el.classList.remove("flash"); void el.offsetWidth; el.classList.add("flash"); };
document.querySelectorAll(".live-answer").forEach(box => {
box.replaceChildren(sm ? h("div", { class: "stats" }, ...sm.tiles.map(statTile)) : h("p", { class: "muted small", text }));
if (changed) glow(box);
});
document.querySelectorAll(".live-strip").forEach(strip => {
strip.replaceChildren(h("span", { class: "strip-head", text: "Your answer now:" }),
...(sm ? sm.tiles.map(t => h("span", { class: `strip-item ${t.tone}` }, icon(t.icon), t.label, h("strong", { text: t.figure })))
: [h("span", { text: "a few numbers are still missing" })]));
if (changed) glow(strip);
});
const say = $("live-announce");
if (say && changed && view.drawerOpen) say.textContent = `Your answer now: ${text}`;
}
function renderResults() {
const slot = $("results"), answerSlot = $("answer-slot");
if (!slot || !answerSlot) return;
// Keep the cursor where it was if the student is typing inside the results (later-year rates).
const active = document.activeElement;
const keepPath = active && slot.contains(active) ? active.getAttribute("data-path") : null;
// If the answer (or the missing-numbers card) had focus, the redrawn one gets it back.
const keepAnswer = active && (active.id === "headline" || active.id === "missing-title");
queueMicrotask(() => {
if (keepPath) slot.querySelector(`[data-path="${keepPath}"]`)?.focus();
if (keepAnswer) ($("headline") || $("missing-title"))?.focus({ preventScroll: true });
});
let R;
try { R = Results.compute(store.data); } catch (err) {
answerSlot.replaceChildren(h("div", { class: "card" }, h("p", { text: "Something in your numbers stops the forecast. Check the dates under \"Edit my numbers\"." })));
slot.replaceChildren();
renderLive(null);
return;
}
if (!R.ready) {
const go = h("button", { type: "button", class: "btn", text: "Finish my numbers" });
go.addEventListener("click", () => goToField(R.inputs.missingAt[0])); // the first missing box, not the last step used
answerSlot.replaceChildren(h("div", { class: "card missing-card" },
h("h2", { class: "flush", id: "missing-title", tabindex: "-1", text: "A few numbers are still missing" }),
missingList(R.inputs.missing, R.inputs.missingAt), go));
slot.replaceChildren();
renderLive(null);
return;
}
const hd = Results.headline(R), trade = Results.tradeoff(R);
const chartRoot = h("div", { class: "chart" });
const notes = [...hd.lines, ...R.inputs.warnings];
const edit = h("button", { type: "button", class: "btn secondary", text: "Edit my numbers" });
edit.addEventListener("click", () => {
view.drawerOpen = true;
const dr = document.querySelector("details.drawer");
if (dr) { dr.open = true; dr.scrollIntoView({ block: "start" }); dr.querySelector(".steps [aria-current='step']")?.focus(); }
});
const sm = Results.summary(R);
answerSlot.replaceChildren(
h("h2", { class: "sr-only", text: "Your results" }),
enterOnce(h("div", { class: `card answer ${sm.tone === "good" ? "is-covered" : "is-short"}` },
h("p", { class: "eyebrow", text: `${store.data.school.termName}, through ${Fmt.date(R.c.end)}` }),
// The tiles repeat the headline's numbers, so screen readers hear the full sentence once instead.
h("div", { class: "stats", "aria-hidden": "true" }, ...sm.tiles.map(statTile)),
h("p", { class: "headline", id: "headline", tabindex: "-1", text: hd.main }),
trade ? h("p", { class: "tradeoff", text: trade }) : null,
notes.length ? h("ul", { class: "follow" }, ...notes.map(t => h("li", { text: t }))) : null,
h("p", { class: "muted small", text: "Estimates assume you keep the aid you have now. Educational use only; not financial advice." }),
h("p", { class: "answer-actions" }, edit)), "answer"));
// The chart card holds the chart, what's on it, and the "Try your own mix" sliders, so a slider and the line it
// moves fit on one screen (Brian, Nov 12, 2026). The option cards stay below, with a link back up to the chart.
const cardsEl = optionCards(R), group = cardsEl.getAttribute("role") === "radiogroup" ? cardsEl : null;
const mixEl = mixPanel(R), readout = h("p", { class: "pick-readout", role: "status", "aria-live": "polite" });
const chartCard = h("div", { class: "card chart-card" }, h("h3", { class: "flush", text: "Your cash, week by week" }), chartRoot, readout, mixEl);
const jump = group ? h("p", { class: "pick-jump" }) : null;
slot.replaceChildren(
chartCard,
h("div", { class: "card options-card" }, h("h3", { class: "flush", text: "Your options" }),
group ? h("p", { class: "muted small pick-hint", text: "Pick an option to see it on the chart above. To try your own mix of hours and a loan, use the sliders under the chart." }) : null,
cardsEl, jump,
valueLine(R) ? h("p", { class: "value-line", text: valueLine(R) }) : null,
h("p", { class: "muted small", text: "This planner never suggests dropping below 12 credit hours, credit cards, payday loans or investments, and never recommends a private loan while you still have federal loans left." })),
aidSection(),
afterGradSection(R));
// One y-axis for these numbers: wide enough for "if nothing changes" and every card's line, so switching cards
// never rescales the chart (a slider can still stretch it while its line is off the chart).
const yExtra = (group ? [...group.querySelectorAll("[data-key]")].map(el => el.dataset.key) : [])
.flatMap(k => { const s = scenario(R, k); return Engine.forecast(R.c, s.hours, s.net).map(r => r[2]); });
explore = { R, chartRoot, chartCard, group, mixEl, readout, jump, yExtra, agTable: slot.querySelector("table.compare") };
if (group) wireCards(group);
applyPick(); // draws the chart with the picked option (the recommended one unless the student picked another)
renderLive(sm);
}
function planView() {
const parts = [];
if (view.sample) {
const s = Sample.LIST.find(x => x.name === view.sample) || Sample.byKey("jordan");
const another = h("button", { type: "button", class: "linkish inline", text: "try another sample" });
another.addEventListener("click", trySample);
const own = h("button", { type: "button", class: "linkish inline", text: "start over with your own numbers" });
own.addEventListener("click", startOver);
parts.push(h("p", { class: "note sample-note" }, h("strong", { text: `Sample student: ${s.name} (fictional). ` }),
`${s.desc} Change any number under "Edit my numbers" to see what happens, `, another, ", or ", own, "."));
}
// The answer, then the editor right under it, then the details (chart, options, aid, after graduation).
const body = h("div", { id: "step-body" });
drawStep(body);
const restart = h("button", { type: "button", class: "linkish", text: "Start over" });
restart.addEventListener("click", startOver);
const done = h("button", { type: "button", class: "btn", text: "Done, see my results" });
const drawer = h("details", { class: "card drawer" },
h("summary", {}, "Edit my numbers", h("span", { class: "drawer-hint", text: "The answer updates as you type." })),
h("div", { class: "live-strip", "aria-hidden": "true" }),
stepNav(),
h("div", { class: "edit-grid" },
body,
h("aside", { class: "live-panel summary", "aria-label": "Your answer and what the planner knows" },
h("p", { class: "live-head", "aria-hidden": "true", text: "Your answer now" }),
h("div", { class: "live-answer", "aria-hidden": "true" }),
h("div", { class: "summary-slot" }))),
h("div", { class: "edit-actions" }, done, restart),
h("p", { class: "sr-only", id: "live-announce", role: "status", "aria-live": "polite" }));
drawer.open = view.drawerOpen;
drawer.addEventListener("toggle", () => { view.drawerOpen = drawer.open; });
done.addEventListener("click", () => {
drawer.open = false;
view.drawerOpen = false;
document.querySelector(".answer")?.scrollIntoView({ block: "start" });
$("headline")?.focus({ preventScroll: true });
});
parts.push(h("section", { "aria-label": "Your results" },
h("div", { id: "answer-slot" }), drawer, h("div", { id: "results" })));
return h("div", {}, ...parts);
}
function render() {
const app = $("app");
app.replaceChildren(view.mode === "welcome" ? welcomeView() : view.mode === "wizard" ? wizardView() : planView());
renderSummaries();
if (view.mode === "plan") renderResults();
}
// ---- How this works (Stage 7): every formula in plain words, every source with its link and date ----
function renderHow() {
const L = CONFIG.loan, P = CONFIG.plan, T = CONFIG.term, K = CONFIG.kees, A = CONFIG.limits;
const pct = (x, d) => `${(x * 100).toFixed(d)}%`;
const rate = pct(L.rate, 2), fee = pct(L.fee, 3);
const tiers = CONFIG.standardTiers.map(([lim, mo]) => `${mo / 12} years under ${Fmt.money(lim)}`).join(", ")
+ `, ${CONFIG.standardTopMonths / 12} years above that`;
const dm = (iso, year = false) => (year ? Fmt.date(iso) : Fmt.dateShort(iso));
const lim = dep => [1, 2, 3].map(l => Fmt.money(A.annual[dep][l][0])).join(" / ");
const subLim = [1, 2, 3].map(l => Fmt.money(A.annual.dependent[l][1])).join(" / ");
const values = {
rate: `${rate} fixed, for loans first paid out Jul 1, 2026 to Jun 30, 2027`,
fee: `${fee}, for loans first paid out through Sep 30, 2027`,
limits: `Per year (1st / 2nd / 3rd year and later): dependent ${lim("dependent")}, independent ${lim("independent")}; subsidized up to ${subLim}. Lifetime: ${Fmt.money(A.aggregate.dependent)} dependent, ${Fmt.money(A.aggregate.independent)} independent, ${Fmt.money(A.aggregateSub)} of it subsidized.`,
limits2627: "The same undergraduate limits apply in 2026–27.",
interest: `Subsidized: no interest in school or the ${L.graceMonths}-month grace period. Unsubsidized: daily interest from the day it's paid out.`,
tiers: `For loans made after July 1, 2026: ${tiers}.`,
cap: "No interest is added to the balance when payments start (Direct Loans since July 2023). Still to be confirmed.",
kees: `${K.fullGpa.toFixed(1)}+ GPA keeps the full award; ${K.minGpa.toFixed(1)}–${(K.fullGpa - 0.01).toFixed(2)} depends on being on track (${K.onTrackHours[2]} / ${K.onTrackHours[3]} / ${K.onTrackHours[4]} earned hours in years 2 / 3 / 4); below ${K.minGpa.toFixed(1)} none. Checked at the end of spring. Proportional at ${K.minHours}–11 credit hours. At most ${K.maxTerms} terms, within ${K.yearsFromHighSchool} years of high school.`,
spring: `Classes start ${dm(T.classesStart)}; last day to add ${dm(T.lastDayToAdd)}; spring break ${dm(T.springBreak[0])}–${dm(T.springBreak[1])}; term ends ${dm(T.end, true)}.`,
fall: `Fall 2026 starts ${dm(T.fallStarts[2026], true)}; fall 2027 starts ${dm(T.fallStarts[2027], true)}.`,
plan: `${P.payments} payments a semester: the first when you enroll, the rest by the ${P.dueDay}nd. ${Fmt.money(P.enrollmentFee)} fee. Balance of ${Fmt.money(P.minBalance)} or more.`,
planFaq: "The spring plan opens the first week of January. Without a plan, the bill is due the 22nd of the month it's billed.",
privateCfpb: "Most private student loans need a cosigner unless you have a good credit history. For most students, federal Direct Loans are the better option. Private loans have no set rate, so the planner uses only a rate you were quoted.",
ukLoans: `Use federal, state and UK aid before private loans. UK's own loans: ${CONFIG.privateLoan.ukLoans.map(u => `${u.name} (${u.who}, ${+(u.rate * 100).toFixed(2)}%)`).join("; ")}.`,
};
const steps = [
["What you owe after aid", `Charges on your bill, minus accepted grants, scholarships and KEES, minus each accepted loan after its ${fee} origination fee. Work-Study is paid as wages, so it's never taken off the bill.`],
["Week by week", `Each week: cash = last week's cash + pay − living costs − bill payments due that week + any aid refund. Pay = hours × wage × your take-home ratio (take-home ÷ (hours × wage) from a pay stub, or 1, "before taxes", without one). Weekly living costs = monthly × 12 ÷ 52. On a payment plan, what you owe is split equally across the payment dates (any leftover cent on the first), and the plan fee is added to the first payment.`],
["Short by", "Your cushion minus your lowest week, counting from the week your aid arrives. Earlier weeks are shown but not counted, because no loan or extra hours can reach them in time. A week that ends at $0 is never \"covered\"."],
["Cheapest fix first", "The planner tries, in order: your unused subsidized loan (no interest until after school), extra hours up to your safe max (no debt), the smallest unsubsidized loan, then working up to your safe max plus the smallest unsubsidized loan. It searches in steps of $10 of cash and half an hour a week, and stops at the first answer that keeps every counted week at or above your cushion. If nothing works, it tells you how much is still missing."],
["How a new loan reaches you", `It arrives on your aid date, lowers the bill payments still to come (equally), and anything above what you owe comes back to you as a refund that week. Amount to accept = cash you need ÷ (1 − ${fee}), rounded up to the dollar.`],
["What a loan costs", `Unsubsidized interest builds daily from the day it's paid out until ${L.graceMonths} months after graduation: amount × ${rate} × days ÷ 365. Subsidized loans build none. That interest isn't added to the balance. In repayment, each month's interest = balance × rate ÷ 12, payments clear unpaid interest first, and the monthly payment is the level amount that reaches $0 in the last month. Cost = everything you repay − the cash you received, so it includes the fee.`],
["How long you repay", `${CONFIG.product.fastPayoffMonths / 12} years for the fast payoff. Otherwise your own number of years, or the standard plan: ${tiers}, based on the total you'd owe under this plan.`],
["Value of an hour", "Loan cost ÷ (loan cash ÷ (wage × take-home ratio)): the interest and fees each hour of work saves you if you work instead of borrowing."],
["Try other options", "Picking an option card, or moving the hours and loan sliders under the chart, redraws the chart from the same weekly forecast with those extra hours or that loan. Slider loans are federal only and use your subsidized room first; their cost uses the same loan math as the cards. The chart's scale covers every card's line, so switching cards doesn't rescale it. The headline always shows the recommended fix."],
["Aid you're protecting", `Each accepted award with a GPA or credit-hour rule, plus KEES, counted twice for a full year. KEES next year: ${K.fullGpa.toFixed(1)}+ keeps it; ${K.minGpa.toFixed(1)}–${(K.fullGpa - 0.01).toFixed(2)} keeps it if you're on track, half if not but you were full-time in one of your last two terms, otherwise none; below ${K.minGpa.toFixed(1)} none. On track uses UK's table: year 1 isn't checked; years 2, 3 and 4 or later need ${K.onTrackHours[2]}, ${K.onTrackHours[3]} and ${K.onTrackHours[4]} earned credit hours by the end of spring (past semesters as you enter them, or ${CONFIG.product.creditsPerSemester} each if blank, plus this term).`],
["After graduation", "Every year until you graduate repeats this one: the loans you've accepted (plus this term's new loan each spring under \"this plan\"), capped by the yearly and lifetime limits. \"Full offer\" is the federal maximum for each year in school. Each loan is repaid over the same number of months; the monthly payment is their total. \"Borrow nothing extra\" counts only if extra hours up to your safe max cover your bills; if they can't, the table shows how short it leaves you each spring and marks it \"Doesn't cover your bills\", so it can't look like the cheap choice."],
["Private loans (last resort)", `Never the recommended fix, and only with a rate a lender quoted you (there's no typical rate to assume). Used in two places: to cover what's still missing after working up to your safe max and borrowing all your federal room, and in "After graduation" as "Private loan instead" (the same money as this plan's new loans, from a private lender) when extra hours can't close the gap. Amount to borrow = cash you need ÷ (1 − fee), rounded up. Interest builds daily from the aid date until ${CONFIG.privateLoan.graceMonths} months after graduation (editable) and, unless you untick it, is added to the balance when payments start. Repaid with a level payment over your own private-loan years, or as long as your federal loans so the two compare fairly. The comparison sentence prices only the new money, both over the same length, because more federal debt also moves all your federal loans to a longer standard term.`],
];
const assumptions = [
"Built for UK's spring 2027 term. Every school setting can be changed for another school or term.",
"Aid arrives on the first day of classes unless you change the date. Your fall loans equal your spring loans when checking yearly limits.",
"You keep the aid you have now. If you lose an award, mark it not accepted to see the new plan.",
"Taxes aren't calculated; a pay stub's take-home pay already includes them.",
"Never included: credit cards, payday loans, investments, or dropping below 12 credit hours. Private loans appear only as a last resort, at a rate you enter, and never as the recommended fix.",
];
const run = h("button", { type: "button", class: "btn secondary", text: "Run the test cases" });
run.addEventListener("click", () => $("run-tests").click());
$("how").replaceChildren(
h("h2", { id: "how-title", class: "flush", text: "How this works" }),
h("p", { class: "muted", text: "Every number on this page comes from the steps below. A separate reference model (reference_model.py) computes the same numbers, and the test cases check that the two agree." }),
fold({ key: "how-steps", title: "The math, step by step", note: `${steps.length} steps` },
h("ol", { class: "how-steps" }, ...steps.map(([t, body]) => h("li", {}, h("strong", { text: t + ". " }), body)))),
fold({ key: "how-sources", title: "Where the numbers come from", note: `${CONFIG.sources.length} sources, each with its link and the date it was checked` },
h("p", { class: "muted small", text: `Each was read from its source on ${Fmt.date(CONFIG.checked)}. Links open in a new tab; if a link doesn't open, copy the address.` }),
h("div", { class: "tbl flush-tbl" }, h("table", { class: "sources" },
h("thead", {}, h("tr", {}, h("th", { text: "What" }), h("th", { text: "Value used" }), h("th", { text: "Checked" }))),
h("tbody", {}, ...CONFIG.sources.map(src => h("tr", {},
h("td", {}, h("strong", { text: src.what }), h("br"),
h("a", { href: src.url, target: "_blank", rel: "noopener noreferrer", class: "url", text: src.url })),
h("td", { text: values[src.key] || "" }),
h("td", { class: "nowrap", text: Fmt.date(src.checked || CONFIG.checked) }))))))),
fold({ key: "how-assumes", title: "What the planner assumes", note: `${assumptions.length} assumptions` },
h("ul", {}, ...assumptions.map(t => h("li", { text: t })))),
h("h3", { class: "check-title", text: "Check the math" }),
h("p", {}, "Test mode reruns every reference case and shows expected and actual numbers side by side. ", run));
}
function init(s) {
store = s;
renderHow();
store.on(() => { renderStatus(); renderSummaries(); refreshSectionSummaries(); if (view.mode === "plan") scheduleResults(); });
render();
renderStatus();
$("save-btn").addEventListener("click", save);
$("open-btn").addEventListener("click", () => $("open-input").click());
$("open-input").addEventListener("change", e => {
const file = e.target.files[0];
e.target.value = "";
if (file) openChosenFile(file);
});
$("copy-btn").addEventListener("click", openCopy);
$("copy-do").addEventListener("click", doCopy);
$("copy-close").addEventListener("click", () => $("copy-dialog").close());
$("paste-btn").addEventListener("click", openPaste);
$("sample-close").addEventListener("click", () => $("sample-dialog").close());
// Skip to the planner: the answer if there is one, else the welcome or form, else the main area.
$("skip-link").addEventListener("click", () => {
const t = $("headline") || $("missing-title") || document.querySelector("#app h2, #app h3") || $("main");
if (t !== $("main") && !t.hasAttribute("tabindex")) t.setAttribute("tabindex", "-1");
t.focus();
});
// "More" menu (narrow windows): each item presses the real Copy or Paste button; Escape or a click elsewhere closes it.
const more = $("more-menu");
more.querySelectorAll("[data-proxy]").forEach(b => b.addEventListener("click", () => {
more.open = false;
$(b.dataset.proxy).click();
}));
more.addEventListener("keydown", e => { if (e.key === "Escape" && more.open) { more.open = false; more.querySelector("summary").focus(); } });
document.addEventListener("click", e => { if (more.open && !more.contains(e.target)) more.open = false; });
$("paste-do").addEventListener("click", doPaste);
$("paste-close").addEventListener("click", () => $("paste-dialog").close());
}
return { init, render, view, stepOfPath };
})();
</script>
<script>
"use strict";
/* =====================================================================================
TEST MODE (?test=1): runs every reference-model case and shows expected vs actual.
Money must match within $1 and monthly payments to the cent; the page also counts exact matches.
===================================================================================== */
// TEST-DATA-START (generated by embed_test_data.py from `python reference_model.py --json`; do not edit by hand)
const TEST_DATA = {"cases":{"Maya":{"input":{"gap":2068.5,"cash0":2600,"hours":10,"wage":11,"k":0.92,"living":200,"cushion":300,"safe_max":12,"due":["2027-01-15"],"sub_room":0,"unsub_room":2000,"grace_end":"2030-11-07"},"output":{"gap":2068.5,"tightest_week":"2027-01-11","min_cash":641.6,"run_out_week":null,"S":0,"weeks_counted":17,"pre_aid_negative_week":null,"state":"covered","spare":341.6}},"Dee":{"input":{"gap":2263.21,"cash0":1300,"hours":6,"wage":11.5,"k":0.9,"living":250,"cushion":400,"safe_max":10,"due":["2027-01-15"],"sub_room":2000,"unsub_room":2000,"grace_end":"2029-11-07"},"output":{"gap":2263.21,"tightest_week":"2027-01-11","min_cash":-954.39,"run_out_week":"2027-01-11","S":1354.39,"weeks_counted":17,"pre_aid_negative_week":null,"state":"fixed_sub","sub_net":1360,"sub_2yr":{"gross":1375,"accrued":0,"days":1031,"pmt":61.26,"total":1470.24,"cost":110.24},"sub_10yr":{"gross":1375,"accrued":0,"days":1031,"pmt":15.63,"total":1875.6,"cost":515.6}}},"Sam":{"input":{"gap":1279.07,"cash0":400,"hours":10,"wage":13,"k":1.0,"living":300,"cushion":300,"safe_max":16,"due":["2027-01-15","2027-02-15","2027-03-15","2027-04-15"],"sub_room":0,"unsub_room":2000,"grace_end":"2028-11-07"},"output":{"gap":1279.07,"tightest_week":"2027-04-12","min_cash":32.48,"run_out_week":"2027-01-11","S":267.52,"weeks_counted":17,"pre_aid_negative_week":null,"state":"fixed_hours","extra_hours":4.0}},"Jordan":{"input":{"gap":3893.5,"cash0":150,"hours":8,"wage":12,"k":0.93,"living":160,"cushion":500,"safe_max":12,"due":["2027-01-15","2027-02-15","2027-03-15","2027-04-15"],"sub_room":0,"unsub_room":6000,"grace_end":"2030-11-07"},"output":{"gap":3893.5,"tightest_week":"2027-04-12","min_cash":-2958.1,"run_out_week":"2027-01-11","S":3458.1,"weeks_counted":17,"pre_aid_negative_week":null,"state":"fixed_unsub","unsub_net":4140,"unsub_2yr":{"gross":4185,"accrued":1043.6,"days":1396,"pmt":232.22,"total":5573.28,"cost":1433.28},"V_2yr":3.86,"unsub_10yr":{"gross":4185,"accrued":1043.6,"days":1396,"pmt":58.5,"total":7020.0,"cost":2880.0},"V_10yr":7.76,"tradeoff_hours":21.8,"unsub_if_work_to_max":4050}},"Riley":{"input":{"gap":3500.21,"cash0":400,"hours":12,"wage":12,"k":0.93,"living":200,"cushion":300,"safe_max":12,"due":["2027-01-15"],"sub_room":0,"unsub_room":0,"grace_end":"2030-11-07"},"output":{"gap":3500.21,"tightest_week":"2027-01-11","min_cash":-2924.67,"run_out_week":"2027-01-11","S":3224.67,"weeks_counted":17,"pre_aid_negative_week":null,"state":"short_beyond_limits","short_after_all":3224.67}},"Casey":{"input":{"gap":2473.78,"cash0":600,"hours":8,"wage":12,"k":0.92,"living":200,"cushion":300,"safe_max":14,"due":["2027-01-04","2027-02-22","2027-03-22","2027-04-22"],"plan_fee":50.0,"start":"2026-11-09","no_pay_weeks":["2026-12-14","2026-12-21","2026-12-28","2027-01-04"],"sub_room":0,"unsub_room":2000,"grace_end":"2029-11-07"},"output":{"gap":2473.78,"tightest_week":"2027-04-19","min_cash":-1264.98,"run_out_week":"2027-01-11","S":1564.98,"weeks_counted":17,"pre_aid_negative_week":"2027-01-04","state":"fixed_mix","unsub_net":250,"extra_hours":6.0,"unsub_2yr":{"gross":253,"accrued":46.59,"days":1031,"pmt":13.32,"total":319.68,"cost":69.68},"V_2yr":3.08,"unsub_10yr":{"gross":253,"accrued":46.59,"days":1031,"pmt":3.37,"total":404.4,"cost":154.4},"V_10yr":6.82,"tradeoff_hours":1.3,"alt_extra_hours":3.0,"alt_unsub_net":1978.86}},"Jordan (UK plan)":{"input":{"gap":3893.5,"cash0":150,"hours":8,"wage":12,"k":0.93,"living":160,"cushion":500,"safe_max":12,"due":["2027-01-11","2027-02-22","2027-03-22","2027-04-22"],"sub_room":0,"unsub_room":6000,"grace_end":"2030-11-07","plan_fee":50.0},"output":{"gap":3893.5,"tightest_week":"2027-04-19","min_cash":-2955.74,"run_out_week":"2027-01-11","S":3455.74,"weeks_counted":17,"pre_aid_negative_week":null,"state":"fixed_unsub","unsub_net":4140,"unsub_2yr":{"gross":4185,"accrued":1043.6,"days":1396,"pmt":232.22,"total":5573.28,"cost":1433.28},"V_2yr":3.86,"unsub_10yr":{"gross":4185,"accrued":1043.6,"days":1396,"pmt":58.5,"total":7020.0,"cost":2880.0},"V_10yr":7.76,"tradeoff_hours":21.8,"unsub_if_work_to_max":4050}},"Riley (some room left)":{"input":{"gap":3500.21,"cash0":400,"hours":12,"wage":12,"k":0.93,"living":200,"cushion":300,"safe_max":14,"due":["2027-01-15"],"sub_room":0,"unsub_room":500,"grace_end":"2030-11-07"},"output":{"gap":3500.21,"tightest_week":"2027-01-11","min_cash":-2924.67,"run_out_week":"2027-01-11","S":3224.67,"weeks_counted":17,"pre_aid_negative_week":null,"state":"short_beyond_limits","short_after_all":2685.32}}},"plans":{"UK Fall 2026 example":{"kind":"bills","input":{"gap":11356.0,"due":["2026-08-05","2026-09-22","2026-10-22","2026-11-22"],"plan_fee":50.0,"disb":"2026-08-05"},"output":[["2026-08-05",2889.0],["2026-09-22",2839.0],["2026-10-22",2839.0],["2026-11-22",2839.0]],"expected":[["2026-08-05",2889.0],["2026-09-22",2839.0],["2026-10-22",2839.0],["2026-11-22",2839.0]]},"UK Spring 2027 default":{"kind":"dates","input":["2027-01-04",4,22],"output":["2027-01-04","2027-02-22","2027-03-22","2027-04-22"],"expected":["2027-01-04","2027-02-22","2027-03-22","2027-04-22"]},"Short months (due the 31st)":{"kind":"dates","input":["2027-01-31",3,31],"output":["2027-01-31","2027-02-28","2027-03-31"],"expected":["2027-01-31","2027-02-28","2027-03-31"]}},"kees_more":{"on_track":[{"input":[1,30],"output":true,"expected":true},{"input":[1,9],"output":true,"expected":true},{"input":[2,48],"output":true,"expected":true},{"input":[2,47],"output":false,"expected":false},{"input":[3,75],"output":true,"expected":true},{"input":[3,71.5],"output":false,"expected":false},{"input":[4,120],"output":true,"expected":true},{"input":[4,119],"output":false,"expected":false},{"input":[5,130],"output":true,"expected":true}],"under_12":[{"input":[12,[{"type":"grant","amount":3500,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"grant","amount":1900,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"scholarship","amount":4215,"accepted":true,"min_gpa":3.0,"min_credits":12},{"type":"kees","amount":750,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"subsidized","amount":1750,"accepted":true,"min_gpa":null,"min_credits":null}]],"output":0.0},{"input":[11,[{"type":"grant","amount":3500,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"grant","amount":1900,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"scholarship","amount":4215,"accepted":true,"min_gpa":3.0,"min_credits":12},{"type":"kees","amount":750,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"subsidized","amount":1750,"accepted":true,"min_gpa":null,"min_credits":null}]],"output":4277.5},{"input":[9,[{"type":"grant","amount":3500,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"grant","amount":1900,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"scholarship","amount":4215,"accepted":true,"min_gpa":3.0,"min_credits":12},{"type":"kees","amount":750,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"subsidized","amount":1750,"accepted":true,"min_gpa":null,"min_credits":null}]],"output":4402.5},{"input":[6,[{"type":"grant","amount":3500,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"grant","amount":1900,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"scholarship","amount":4215,"accepted":true,"min_gpa":3.0,"min_credits":12},{"type":"kees","amount":750,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"subsidized","amount":1750,"accepted":true,"min_gpa":null,"min_credits":null}]],"output":4590.0},{"input":[5,[{"type":"grant","amount":3500,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"grant","amount":1900,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"scholarship","amount":4215,"accepted":true,"min_gpa":3.0,"min_credits":12},{"type":"kees","amount":750,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"subsidized","amount":1750,"accepted":true,"min_gpa":null,"min_credits":null}]],"output":4965.0}]},"options":{"Maya, 10-year plan":{"input":["Maya",60,120],"output":{"state":"covered","hours_alone":0,"borrow":null,"borrow_short":0,"recommended":null,"safe_hours_alone":0,"nothing_extra_short":0,"private_net":0}},"Dee, 10-year plan":{"input":["Dee",60,120],"output":{"state":"fixed_sub","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":1271.59,"private_net":0,"borrow":{"sub_net":1360,"unsub_net":0,"fast":{"months":24,"gross":1375,"pmt":61.26,"cost":110.24},"plan":{"months":120,"gross":1375,"pmt":15.63,"cost":515.6},"V_plan":3.92},"borrow_short":0,"recommended":{"sub_net":1360,"unsub_net":0,"fast":{"months":24,"gross":1375,"pmt":61.26,"cost":110.24},"plan":{"months":120,"gross":1375,"pmt":15.63,"cost":515.6},"V_plan":3.92,"extra_hours":0}}},"Sam, 10-year plan":{"input":["Sam",60,120],"output":{"state":"fixed_hours","hours_alone":4.0,"safe_hours_alone":4.0,"nothing_extra_short":0,"private_net":0,"borrow":{"sub_net":0.0,"unsub_net":400,"fast":{"months":24,"gross":405,"pmt":20.17,"cost":84.08},"plan":{"months":120,"gross":405,"pmt":5.13,"cost":215.6},"V_plan":7.01},"borrow_short":0,"recommended":{"sub_net":0,"unsub_net":0,"fast":{"months":24,"gross":0,"pmt":0,"cost":0},"plan":{"months":120,"gross":0,"pmt":0,"cost":0},"V_plan":null,"extra_hours":4.0}}},"Jordan, 10-year plan":{"input":["Jordan",60,120],"output":{"state":"fixed_unsub","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":2788.5,"private_net":0,"borrow":{"sub_net":0.0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":120,"gross":4185,"pmt":58.5,"cost":2880.0},"V_plan":7.76},"borrow_short":0,"recommended":{"sub_net":0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":120,"gross":4185,"pmt":58.5,"cost":2880.0},"V_plan":7.76,"extra_hours":0}}},"Riley, 10-year plan":{"input":["Riley",60,120],"output":{"state":"short_beyond_limits","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":3224.67,"private_net":3230,"borrow":null,"borrow_short":3224.67,"recommended":null}},"Casey, 10-year plan":{"input":["Casey",60,120],"output":{"state":"fixed_mix","hours_alone":7.5,"safe_hours_alone":null,"nothing_extra_short":240.18,"private_net":0,"borrow":null,"borrow_short":176.5,"recommended":{"sub_net":0,"unsub_net":250,"fast":{"months":24,"gross":253,"pmt":13.32,"cost":69.68},"plan":{"months":120,"gross":253,"pmt":3.37,"cost":154.4},"V_plan":6.82,"extra_hours":6.0}}},"Jordan (UK plan), 10-year plan":{"input":["Jordan (UK plan)",60,120],"output":{"state":"fixed_unsub","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":2741.5,"private_net":0,"borrow":{"sub_net":0.0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":120,"gross":4185,"pmt":58.5,"cost":2880.0},"V_plan":7.76},"borrow_short":0,"recommended":{"sub_net":0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":120,"gross":4185,"pmt":58.5,"cost":2880.0},"V_plan":7.76,"extra_hours":0}}},"Riley (some room left), 10-year plan":{"input":["Riley (some room left)",60,120],"output":{"state":"short_beyond_limits","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":3180.03,"private_net":2690,"borrow":null,"borrow_short":2729.96,"recommended":null}},"Jordan (UK plan), 15-year plan":{"input":["Jordan (UK plan)",60,180],"output":{"state":"fixed_unsub","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":2741.5,"private_net":0,"borrow":{"sub_net":0.0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":180,"gross":4185,"pmt":44.5,"cost":3870.0},"V_plan":10.43},"borrow_short":0,"recommended":{"sub_net":0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":180,"gross":4185,"pmt":44.5,"cost":3870.0},"V_plan":10.43,"extra_hours":0}}},"Jordan (UK plan), 40-hour ceiling":{"input":["Jordan (UK plan)",40,180],"output":{"state":"fixed_unsub","hours_alone":null,"safe_hours_alone":null,"nothing_extra_short":2741.5,"private_net":0,"borrow":{"sub_net":0.0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":180,"gross":4185,"pmt":44.5,"cost":3870.0},"V_plan":10.43},"borrow_short":0,"recommended":{"sub_net":0,"unsub_net":4140,"fast":{"months":24,"gross":4185,"pmt":232.22,"cost":1433.28},"plan":{"months":180,"gross":4185,"pmt":44.5,"cost":3870.0},"V_plan":10.43,"extra_hours":0}}}},"aid":{"Sample student (Jordan)":{"input":[{"type":"grant","amount":3500,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"grant","amount":1900,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"scholarship","amount":4215,"accepted":true,"min_gpa":3.0,"min_credits":12},{"type":"kees","amount":750,"accepted":true,"min_gpa":null,"min_credits":null},{"type":"subsidized","amount":1750,"accepted":true,"min_gpa":null,"min_credits":null}],"output":9930,"expected":9930},"Rule on an award not accepted":{"input":[{"type":"scholarship","amount":2000,"accepted":false,"min_gpa":3.0,"min_credits":null},{"type":"grant","amount":1000,"accepted":true,"min_gpa":null,"min_credits":12}],"output":2000,"expected":2000}},"room":{"Maya":{"input":["dependent",1,3500,0],"output":{"sub_room":0,"unsub_room":2000}},"Dee":{"input":["dependent",2,2500,0],"output":{"sub_room":2000,"unsub_room":2000}},"Sam":{"input":["dependent",3,5500,0],"output":{"sub_room":0,"unsub_room":2000}},"Jordan":{"input":["independent",1,3500,0],"output":{"sub_room":0,"unsub_room":6000}},"Riley":{"input":["independent",1,3500,6000],"output":{"sub_room":0,"unsub_room":0}},"Casey":{"input":["dependent",2,4500,0],"output":{"sub_room":0,"unsub_room":2000}},"Jordan (UK plan)":{"input":["independent",1,3500,0],"output":{"sub_room":0,"unsub_room":6000}}},"kees":[{"input":[3.1,null,null],"output":1.0,"expected":1.0},{"input":[2.8,true,null],"output":1.0,"expected":1.0},{"input":[2.8,false,true],"output":0.5,"expected":0.5},{"input":[2.8,false,false],"output":0.0,"expected":0.0},{"input":[2.4,null,null],"output":0.0,"expected":0.0}],"four_year":{"Jordan 4yr":{"input":{"dependency":"independent","grace_end":"2030-11-07","own_years":null,"prior":[],"extra_sub":0,"extra_unsub":4185,"years":[{"level":1,"fall":"2026-08-24","spring":"2027-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":2,"fall":"2027-08-23","spring":"2028-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2028-08-23","spring":"2029-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2029-08-23","spring":"2030-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0}]},"output":{"full_offer":{"sub_borrowed":19000,"unsub_borrowed":26000,"borrowed":45000,"fees":475.64,"accrued":4059.73,"months":180,"payment":424.38,"total_repaid":76388.4,"interest":31388.4,"payoff_date":"2045-11-07"},"this_plan":{"sub_borrowed":14000,"unsub_borrowed":16740,"borrowed":30740,"fees":324.96,"accrued":2535.74,"months":180,"payment":288.02,"total_repaid":51843.6,"interest":21103.6,"payoff_date":"2045-11-07"},"nothing_extra":{"sub_borrowed":14000,"unsub_borrowed":0,"borrowed":14000,"fees":148.0,"accrued":0.0,"months":120,"payment":159.12,"total_repaid":19094.4,"interest":5094.4,"payoff_date":"2040-11-07"}}},"Jordan 4yr, fall graduation":{"input":{"dependency":"independent","grace_end":"2030-06-18","own_years":null,"prior":[],"extra_sub":0,"extra_unsub":4185,"years":[{"level":1,"fall":"2026-08-24","spring":"2027-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":2,"fall":"2027-08-23","spring":"2028-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2028-08-23","spring":"2029-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2029-08-23","spring":null,"rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0}]},"output":{"full_offer":{"sub_borrowed":16250,"unsub_borrowed":22500,"borrowed":38750,"fees":409.58,"accrued":3301.45,"months":180,"payment":364.06,"total_repaid":65530.8,"interest":26780.8,"payoff_date":"2045-06-18"},"this_plan":{"sub_borrowed":12250,"unsub_borrowed":12555,"borrowed":24805,"fees":262.22,"accrued":1993.02,"months":120,"payment":303.21,"total_repaid":36385.2,"interest":11580.2,"payoff_date":"2040-06-18"},"nothing_extra":{"sub_borrowed":12250,"unsub_borrowed":0,"borrowed":12250,"fees":129.5,"accrued":0.0,"months":120,"payment":139.23,"total_repaid":16707.6,"interest":4457.6,"payoff_date":"2040-06-18"}}},"Dee 4yr":{"input":{"dependency":"dependent","grace_end":"2029-11-07","own_years":5,"prior":[{"gross":1250,"sub":true,"rate":0.0652,"fee":0.01057,"disb":"2025-08-27"},{"gross":1250,"sub":true,"rate":0.0652,"fee":0.01057,"disb":"2026-01-12"}],"extra_sub":1375,"extra_unsub":0,"years":[{"level":2,"fall":"2026-08-26","spring":"2027-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":2500,"accepted_unsub":0},{"level":3,"fall":"2027-08-25","spring":"2028-01-10","rate":0.0652,"fee":0.01057,"accepted_sub":2500,"accepted_unsub":0},{"level":3,"fall":"2028-08-23","spring":"2029-01-08","rate":0.0652,"fee":0.01057,"accepted_sub":2500,"accepted_unsub":0}]},"output":{"full_offer":{"sub_borrowed":18000,"unsub_borrowed":6000,"borrowed":24000,"fees":253.68,"accrued":764.19,"months":60,"payment":484.38,"total_repaid":29062.8,"interest":5062.8,"payoff_date":"2034-11-07"},"this_plan":{"sub_borrowed":14125,"unsub_borrowed":0,"borrowed":14125,"fees":149.3,"accrued":0.0,"months":60,"payment":276.52,"total_repaid":16591.2,"interest":2466.2,"payoff_date":"2034-11-07"},"nothing_extra":{"sub_borrowed":10000,"unsub_borrowed":0,"borrowed":10000,"fees":105.68,"accrued":0.0,"months":60,"payment":195.76,"total_repaid":11745.6,"interest":1745.6,"payoff_date":"2034-11-07"}}},"Jordan 4yr, private instead":{"input":{"dependency":"independent","grace_end":"2030-11-07","own_years":null,"prior":[],"extra_sub":0,"extra_unsub":4185,"years":[{"level":1,"fall":"2026-08-24","spring":"2027-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":2,"fall":"2027-08-23","spring":"2028-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2028-08-23","spring":"2029-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2029-08-23","spring":"2030-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0}],"private":{"rate":0.095,"fee":0.0,"months":null,"capitalize":true,"grace_end":"2030-11-07","cash":{"this_plan":0,"nothing_extra":4140}}},"output":{"full_offer":{"sub_borrowed":19000,"unsub_borrowed":26000,"borrowed":45000,"fees":475.64,"accrued":4059.73,"months":180,"payment":424.38,"total_repaid":76388.4,"interest":31388.4,"payoff_date":"2045-11-07"},"this_plan":{"sub_borrowed":14000,"unsub_borrowed":16740,"borrowed":30740,"fees":324.96,"accrued":2535.74,"months":180,"payment":288.02,"total_repaid":51843.6,"interest":21103.6,"payoff_date":"2045-11-07"},"nothing_extra":{"sub_borrowed":14000,"unsub_borrowed":0,"borrowed":30560,"fees":148.0,"accrued":3655.0,"months":120,"payment":370.21,"total_repaid":57090.6,"interest":26530.6,"payoff_date":"2045-11-07","private":{"cash_each_spring":4140,"loans":4,"borrowed":16560,"fees":0.0,"accrued":3655.0,"months":180,"payment":211.09,"total_repaid":37996.2,"interest":21436.2,"payoff_date":"2045-11-07"}},"compare":{"months":180,"cash_each_spring":4140,"federal":13306.16,"private":21436.2}}},"Riley 4yr, private for the rest":{"input":{"dependency":"independent","grace_end":"2030-11-07","own_years":null,"prior":[],"extra_sub":0,"extra_unsub":0,"years":[{"level":1,"fall":"2026-08-24","spring":"2027-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":6000},{"level":2,"fall":"2027-08-23","spring":"2028-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":6000},{"level":3,"fall":"2028-08-23","spring":"2029-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":6000},{"level":3,"fall":"2029-08-23","spring":"2030-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":6000}],"private":{"rate":0.12,"fee":0.02,"months":60,"capitalize":false,"grace_end":"2030-11-07","cash":{"this_plan":3230,"nothing_extra":3230}}},"output":{"full_offer":{"sub_borrowed":19000,"unsub_borrowed":26000,"borrowed":45000,"fees":475.64,"accrued":4134.75,"months":180,"payment":424.91,"total_repaid":76483.8,"interest":31483.8,"payoff_date":"2045-11-07"},"this_plan":{"sub_borrowed":14000,"unsub_borrowed":24000,"borrowed":51184,"fees":665.36,"accrued":7612.81,"months":180,"payment":730.22,"total_repaid":87278.4,"interest":36094.4,"payoff_date":"2045-11-07","private":{"cash_each_spring":3230,"loans":4,"borrowed":13184,"fees":263.68,"accrued":3675.62,"months":60,"payment":368.01,"total_repaid":22080.6,"interest":8896.6,"payoff_date":"2035-11-07"}},"nothing_extra":{"sub_borrowed":14000,"unsub_borrowed":24000,"borrowed":51184,"fees":665.36,"accrued":7612.81,"months":180,"payment":730.22,"total_repaid":87278.4,"interest":36094.4,"payoff_date":"2045-11-07","private":{"cash_each_spring":3230,"loans":4,"borrowed":13184,"fees":263.68,"accrued":3675.62,"months":60,"payment":368.01,"total_repaid":22080.6,"interest":8896.6,"payoff_date":"2035-11-07"}}}}},"private":{"Same terms as a federal unsubsidized loan":{"input":[4140,"2027-01-11","2030-11-07",0.0652,0.01057,120,false],"output":{"gross":4185,"accrued":1043.6,"days":1396,"pmt":58.5,"total":7020.0,"fee":44.24,"cost":2880.0},"expected":{"gross":4185,"accrued":1043.6,"days":1396,"pmt":58.5,"total":7020.0,"cost":2880.0}},"Jordan: $4,140 at a fictional 9.5%, interest added":{"input":[4140,"2027-01-11","2030-11-07",0.095,0.0,180,true],"output":{"gross":4140,"accrued":1504.24,"days":1396,"pmt":58.94,"total":10609.2,"fee":0.0,"cost":6469.2}},"Riley: the rest at a fictional 11%, 10 years":{"input":[3230,"2027-01-11","2030-11-07",0.11,0.0,120,true],"output":{"gross":3230,"accrued":1358.9,"days":1396,"pmt":63.21,"total":7585.2,"fee":0.0,"cost":4355.2}},"Riley (some room left): 3% fee, 5 years, interest not added":{"input":[2690,"2027-01-11","2030-11-07",0.11,0.03,60,false],"output":{"gross":2774,"accrued":1167.06,"days":1396,"pmt":83.39,"total":5003.4,"fee":83.22,"cost":2313.4}}},"constants":{"RATE":0.0652,"FEE":0.01057,"PLAN_FEE":50.0,"PRIVATE_GRACE_MONTHS":6}};
// TEST-DATA-END
const Tests = (() => {
const CENT_KEYS = new Set(["pmt", "payment"]);
const MONEY_KEYS = new Set(["gap", "min_cash", "S", "spare", "sub_net", "unsub_net", "gross", "accrued", "total",
"cost", "unsub_if_work_to_max", "alt_unsub_net", "short_after_all", "sub_room", "unsub_room", "borrowed",
"sub_borrowed", "unsub_borrowed", "fees", "total_repaid", "interest", "V_2yr", "V_10yr",
"nothing_extra_short", "private_net", "cash_each_spring", "fee", "federal", "private"]);
function flatten(obj, prefix = "", out = {}) {
if (obj === null || typeof obj !== "object" || Array.isArray(obj)) { out[prefix || "value"] = obj; return out; }
for (const [k, v] of Object.entries(obj)) {
const p = prefix ? prefix + "." + k : k;
if (v !== null && typeof v === "object" && !Array.isArray(v)) flatten(v, p, out); else out[p] = v;
}
return out;
}
function rule(path) {
const leaf = path.split(".").pop();
if (CENT_KEYS.has(leaf)) return { label: "to the cent", tol: 0.005 };
if (MONEY_KEYS.has(leaf)) return { label: "within $1", tol: 1 };
return { label: "exact", tol: 0 };
}
function compare(expected, actual) {
const e = flatten(expected), a = flatten(actual);
const keys = [...new Set([...Object.keys(e), ...Object.keys(a)])];
return keys.map(path => {
const ev = e[path], av = a[path], r = rule(path);
const exact = JSON.stringify(ev) === JSON.stringify(av);
let ok = exact;
if (!ok && typeof ev === "number" && typeof av === "number") ok = Math.abs(ev - av) <= r.tol;
return { path, ev, av, rule: r.label, ok, exact, missing: !(path in e) || !(path in a) };
});
}
const fmt = v => v === undefined ? "(missing)" : v === null ? "none" : String(v);
function el(tag, attrs = {}, ...kids) {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (k === "class") n.className = v; else if (k === "text") n.textContent = v; else n.setAttribute(k, v);
}
for (const k of kids) if (k != null) n.append(k);
return n;
}
function block(title, subtitle, rows) {
const passed = rows.filter(r => r.ok).length, allOk = passed === rows.length;
const d = el("details", { class: "case" });
if (!allOk) d.open = true;
d.append(el("summary", {},
el("strong", { text: title }),
subtitle ? el("span", { class: "muted", text: subtitle }) : null,
el("span", { class: "count" },
el("span", { class: "chip " + (allOk ? "pass" : "fail"), text: `${passed}/${rows.length} pass` }))));
const tbody = el("tbody");
for (const r of rows) {
tbody.append(el("tr", {},
el("td", { class: "path", text: r.path }),
el("td", { text: fmt(r.ev) }),
el("td", { text: fmt(r.av) }),
el("td", { class: "muted", text: r.exact ? "exact" : r.rule }),
el("td", {}, el("span", { class: "chip " + (r.ok ? "pass" : "fail"), text: r.ok ? "pass" : "fail" }))));
}
d.append(el("div", { class: "tbl" },
el("table", {},
el("thead", {}, el("tr", {}, ...["Field", "Expected (Python)", "Actual (this page)", "Rule", ""].map(h => el("th", { text: h })))),
tbody)));
return { node: d, rows };
}
function run() {
if (!TEST_DATA) throw new Error("Test data is missing. Run embed_test_data.py.");
const T = TEST_DATA, blocks = { cases: [], plans: [], room: [], kees: [], four: [], consts: [] };
for (const [name, c] of Object.entries(T.cases)) {
blocks.cases.push(block(name, c.output.state.replace(/_/g, " "), compare(c.output, Engine.solve(c.input))));
}
for (const [name, p] of Object.entries(T.plans || {})) {
const actual = p.kind === "bills" ? Engine.billsByDate(p.input) : Engine.planDates(...p.input);
blocks.plans.push(block(name, p.kind === "bills" ? "amount due on each date" : "payment dates",
compare({ "matches Python": p.output, "matches expected": p.expected },
{ "matches Python": actual, "matches expected": actual })));
}
for (const [name, r] of Object.entries(T.room)) {
const actual = Engine.loanRoom(...r.input);
const inCase = T.cases[name].input;
const rows = compare(r.output, actual).concat(compare(
{ matches_case_input: true },
{ matches_case_input: actual.sub_room === inCase.sub_room && actual.unsub_room === inCase.unsub_room }));
blocks.room.push(block(name, `${r.input[0]}, year ${r.input[1]}`, rows));
}
const keesRows = [];
T.kees.forEach(k => {
const [g, t, f] = k.input, actual = Engine.keesNextYear(g, t, f);
const label = `GPA ${g.toFixed(2)}, on track ${fmt(t)}, full-time recently ${fmt(f)}`;
keesRows.push(...compare({ [label]: k.expected }, { [label]: actual }));
});
blocks.kees.push(block("KEES ladder", "share of next year's award kept", keesRows));
blocks.opts = [];
for (const [name, o] of Object.entries(T.options || {})) {
const [caseName, ceiling, months] = o.input;
blocks.opts.push(block(name, `ceiling ${ceiling} hours, ${months / 12}-year plan`,
compare(o.output, Engine.options(T.cases[caseName].input, ceiling, months))));
}
const aidRows = [];
for (const [name, a] of Object.entries(T.aid || {})) {
const actual = Engine.aidAtRisk(a.input);
aidRows.push(...compare({ [`${name} (Python)`]: a.output, [`${name} (expected)`]: a.expected },
{ [`${name} (Python)`]: actual, [`${name} (expected)`]: actual }));
}
blocks.aid = [block("Aid at risk", "$ a year that depends on a GPA or credit-hour rule", aidRows)];
if (T.kees_more) {
const km = T.kees_more, kRows = [];
km.on_track.forEach(t => {
const [y, e] = t.input, label = `On track: year ${y}, ${e} earned credit hours`;
kRows.push(...compare({ [label]: t.expected }, { [label]: Engine.keesOnTrack(y, e) }));
});
km.under_12.forEach(t => {
const label = `Aid lost this term at ${t.input[0]} credit hours (sample)`;
kRows.push(...compare({ [label]: t.output }, { [label]: Engine.under12Cost(t.input[1], t.input[0]) }));
});
blocks.aid.push(block("KEES on track and the under-12 what-if", "Stage 5", kRows));
}
for (const [name, fy] of Object.entries(T.four_year)) {
blocks.four.push(block(name, Object.keys(fy.output).join(" · ").replace(/_/g, " "),
compare(fy.output, Engine.fourYear(fy.input))));
}
for (const [name, p] of Object.entries(T.private || {})) {
const actual = Engine.privateCost(...p.input);
let rows = compare(p.output, actual);
if (p.expected) {
const pick = Object.fromEntries(Object.keys(p.expected).map(k => [k, actual[k]]));
rows = rows.concat(compare(Object.fromEntries(Object.entries(p.expected).map(([k, v]) => ["federal loan_cost." + k, v])),
Object.fromEntries(Object.entries(pick).map(([k, v]) => ["federal loan_cost." + k, v]))));
}
blocks.four.push(block(name, "one private loan", rows));
}
blocks.consts.push(block("Constants", "CONFIG vs reference_model.py", compare(
T.constants, { RATE: CONFIG.loan.rate, FEE: CONFIG.loan.fee, PLAN_FEE: CONFIG.plan.enrollmentFee,
PRIVATE_GRACE_MONTHS: CONFIG.privateLoan.graceMonths })));
blocks.page = [block("Save and Open", "page checks (no Python equivalent)", pageChecks()),
block("Your inputs", "form numbers → engine inputs", inputChecks())];
return blocks;
}
// Save/Open pass-fail rules, checked without touching the page's real data.
function same(a, b) {
if (a === b) return true;
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
if (Array.isArray(a) !== Array.isArray(b)) return false;
const ka = Object.keys(a), kb = Object.keys(b);
return ka.length === kb.length && ka.every(k => Object.prototype.hasOwnProperty.call(b, k) && same(a[k], b[k]));
}
function pageChecks() {
const rows = [];
const add = (name, expected, actual, ok) => rows.push({ path: name, ev: expected, av: actual, rule: "page check", ok, exact: ok });
const sample = Schema.example();
for (const [name, data] of [["a filled-in record", sample], ["a blank page", Schema.defaults()]]) {
const text = Schema.serialize(data), r = Schema.parse(text), head = JSON.parse(text);
const ok = r.ok && same(r.data, data);
add(`Save then Open restores everything (${name})`, "identical data", ok ? "identical data" : (r.ok ? "data differs" : r.errors[0]), ok);
const tagged = head.app === Schema.APP_ID && head.schemaVersion === 1;
add(`Saved file carries app name and schemaVersion (${name})`, "make-it-to-may, 1", `${head.app}, ${head.schemaVersion}`, tagged);
}
const good = JSON.parse(Schema.serialize(sample));
const mutate = fn => { const o = structuredClone(good); fn(o); return JSON.stringify(o); };
const bad = [
["not JSON", "this is not json", "isn't valid JSON"],
["an empty file", "", "empty"],
["a list instead of a save file", "[1, 2, 3]", "doesn't look like"],
["another app's file", mutate(o => { o.app = "something-else"; }), "doesn't look like"],
["no version number", mutate(o => { delete o.schemaVersion; }), "no version number"],
["a newer version", mutate(o => { o.schemaVersion = 2; }), "newer version"],
["wage typed as words", mutate(o => { o.data.money.wage = "twelve"; }), "Hourly wage"],
["GPA above 4.0", mutate(o => { o.data.profile.gpa = 5; }), "Cumulative GPA"],
["an impossible date", mutate(o => { o.data.school.termEnd = "2027-02-30"; }), "Last day of the term"],
["term ending before aid arrives", mutate(o => { o.data.school.termEnd = "2027-01-01"; }), "end after aid arrives"],
["an unknown award type", mutate(o => { o.data.awards[0].type = "lottery"; }), "Award 1"],
["31 awards", mutate(o => { o.data.awards = Array(31).fill(o.data.awards[0]); }), "at most 30"],
["a missing section", mutate(o => { delete o.data.money; }), "Cash on hand"],
["a file over 1 MB", "{\"app\":\"" + "x".repeat(1000001) + "\"}", "too large"],
["a blank file over 1 MB", " ".repeat(1000001), "too large"],
];
for (const [name, text, needle] of bad) {
const r = Schema.parse(text);
const ok = !r.ok && r.errors.join(" ").includes(needle);
add(`Rejects ${name}`, `rejected, mentions “${needle}”`, r.ok ? "accepted" : r.errors[0], ok);
}
// An invalid file must leave current data untouched (and still unsaved).
const store = createStore(Schema.example());
store.set("money.cash", 123.45);
const before = JSON.stringify(store.data);
let confirmAsked = false;
FileIO.tryOpen(store, mutate(o => { o.data.profile.gpa = 9; }), () => { confirmAsked = true; return true; }, "opened");
const untouched = JSON.stringify(store.data) === before && store.dirty && !confirmAsked;
add("Invalid file leaves current data untouched", "unchanged, still unsaved",
untouched ? "unchanged, still unsaved" : "changed", untouched);
// Unsaved flag through a normal session.
const s = createStore(Schema.defaults()), seen = [];
seen.push(s.dirty);
s.set("money.wage", 12); seen.push(s.dirty);
s.markSaved("saved"); seen.push(s.dirty);
s.set("money.hours", 8); seen.push(s.dirty);
s.load(Schema.example(), "opened"); seen.push(s.dirty);
const flow = seen.map(d => (d ? "unsaved" : "saved")).join(", ");
add("Unsaved flag: start, edit, save, edit, open", "saved, unsaved, saved, unsaved, saved", flow,
flow === "saved, unsaved, saved, unsaved, saved");
// Leaving the page: warn only when there are unsaved changes.
const warns = dirty => {
const st = createStore(Schema.defaults());
if (dirty) st.touch();
const ev = new Event("beforeunload", { cancelable: true });
FileIO.leaveGuard(st)(ev);
return ev.defaultPrevented;
};
const leave = `${warns(true) ? "warns" : "no warning"} / ${warns(false) ? "warns" : "no warning"}`;
add("Leaving the page: unsaved / saved", "warns / no warning", leave, leave === "warns / no warning");
// A file saved before "credits per semester" existed still opens (it gets an empty list).
const older = Schema.parse(mutate(o => { delete o.data.profile.semesterCredits; o.data.profile.earnedHours = 30; }));
const olderOk = older.ok && Array.isArray(older.data.profile.semesterCredits) && older.data.profile.semesterCredits.length === 0;
add("Opens a file saved before semester credits were added", "opens, empty credit list", olderOk ? "opens, empty credit list" : (older.ok ? "opens, wrong list" : older.errors[0]), olderOk);
return rows;
}
// What the student types becomes exactly the reference model's inputs.
function inputChecks() {
const rows = [];
const add = (name, expected, actual, ok) => rows.push({ path: name, ev: expected, av: actual, rule: "page check", ok, exact: ok });
const want = TEST_DATA.cases["Jordan (UK plan)"];
const jordan = Inputs.derive(Sample.jordan());
const got = Engine.solve(jordan.case);
add("Sample student gives the same results as test case Jordan (UK plan)", "identical results",
same(got, want.output) ? "identical results" : "different results", same(got, want.output));
// Every sample in the picker rebuilds its test case: the same inputs (take-home rates to 1e-9, since the page divides
// take-home by hours × wage) and identical results. Its tag must name the answer the planner actually gives.
const near = (a, b) => typeof a === "number" && typeof b === "number" ? Math.abs(a - b) < 1e-9 : JSON.stringify(a) === JSON.stringify(b);
const TAG = { covered: /^Covered$/, fixed_sub: /subsidized loan/, fixed_hours: /more hours a week/, fixed_unsub: /unsubsidized loan/,
fixed_mix: /hours and a loan/, short_beyond_limits: /^Short after all federal loans$/ };
for (const s of Sample.LIST) {
const tc = TEST_DATA.cases[s.testCase], D = Inputs.derive(s.data());
const off = D.ready ? Object.keys(tc.input).filter(k => !near(D.case[k], tc.input[k])) : ["not ready"];
const res = D.ready ? Engine.solve(D.case) : null;
const okRun = !off.length && res && same(res, tc.output);
add(`Sample ${s.name} rebuilds test case ${s.testCase}`, "same inputs, identical results",
okRun ? "same inputs, identical results" : `differs: ${off.join(", ") || "results"}`, okRun);
const st = tc.output.state, hoursOk = st !== "fixed_hours" || s.tag.includes(Results.hrs(tc.output.extra_hours));
const okTag = TAG[st].test(s.tag) && hoursOk;
add(`Sample ${s.name}'s tag matches its answer (${st})`, "matches", okTag ? "matches" : `"${s.tag}"`, okTag);
}
// Picking a card puts its hours or loan on the chart. A card that says it works must keep every counted week at or
// above the cushion; one that says "Not enough on its own" must not, even at the hours ceiling or all federal room.
// Every "still missing" item links to a real field that sits in one of the four steps.
{
const blank = Schema.defaults();
blank.payoff.mode = "years"; blank.payment.dates = []; blank.money.hours = 10; // also asks for wage, plan dates, payoff years
const D = Inputs.derive(blank);
const unmapped = D.missing.filter((t, i) => !D.missingAt[i] || !Schema.byPath[D.missingAt[i]] || !UI.stepOfPath(D.missingAt[i]));
const okMap = D.missing.length === D.missingAt.length && D.missing.length >= 10 && !unmapped.length;
add("Every missing number links to its box in the form", `${D.missing.length} items, all linked`,
okMap ? `${D.missing.length} items, all linked` : `unlinked: ${unmapped.join("; ") || "count mismatch"}`, okMap);
}
// A forecast that starts after the aid date gets a warning (a new loan would have no week to arrive in); the sample doesn't.
{
const late = Sample.jordan(); late.school.forecastStart = "2027-01-18";
const warned = d => Inputs.derive(d).warnings.some(w => w.startsWith("Your forecast starts after your aid date"));
const okLate = warned(late) && !warned(Sample.jordan());
add("A forecast starting after the aid date is flagged (the sample isn't)", "flagged only when late",
okLate ? "flagged only when late" : `late ${warned(late)}, sample ${warned(Sample.jordan())}`, okLate);
}
for (const s of Sample.LIST) {
const R = Results.compute(s.data());
if (!R.ready || R.rec.state === "covered") continue;
const { c, opts, rec, d } = R;
const short = (hh, net) => Engine.shortfall(Engine.forecast(c, hh, net), c.cushion, c.disb)[0];
const cap = Engine.pyRound(Math.floor(c.sub_room * (1 - CONFIG.loan.fee) * 100) / 100 + Math.floor(c.unsub_room * (1 - CONFIG.loan.fee) * 100) / 100, 2);
const work = opts.hours_alone !== null ? short(opts.hours_alone, 0) === 0 : short(Math.max(0, d.money.hoursCeiling - c.hours), 0) > 0;
const borrow = opts.borrow ? short(0, opts.borrow.sub_net + opts.borrow.unsub_net) === 0 : short(0, cap) > 0;
const plan = rec.state === "short_beyond_limits" ? short(Math.max(0, c.safe_max - c.hours), cap) > 0
: short(rec.extra_hours ?? 0, (rec.sub_net ?? 0) + (rec.unsub_net ?? 0)) === 0;
const ok = work && borrow && plan;
add(`Sample ${s.name}: each option card's chart line matches what the card says`, "work, borrow, plan all match",
ok ? "work, borrow, plan all match" : `work ${work}, borrow ${borrow}, plan ${plan}`, ok);
}
const facts = r => `gap ${r.gap}, k ${r.k}, loan room ${r.sub}/${r.unsub}, payments start ${r.grace}`;
const wantFacts = facts({ gap: want.input.gap, k: want.input.k, sub: want.input.sub_room, unsub: want.input.unsub_room, grace: want.input.grace_end });
const gotFacts = facts({ gap: jordan.gap, k: jordan.k, sub: jordan.room.sub, unsub: jordan.room.unsub, grace: jordan.graceEnd });
add("Sample student's inputs to the engine", wantFacts, gotFacts, wantFacts === gotFacts);
const wantDue = want.input.due.join(", ") + ", fee " + want.input.plan_fee;
const gotDue = jordan.case.due.join(", ") + ", fee " + jordan.case.plan_fee;
add("Sample student's payment dates and fee", wantDue, gotDue, wantDue === gotDue);
add("Sample student has nothing missing", "nothing missing", jordan.missing.join("; ") || "nothing missing", jordan.ready);
const blank = Inputs.derive(Schema.defaults());
add("Blank page lists what's still needed", "not ready; asks for cash on hand",
blank.ready ? "ready" : `not ready; ${blank.missing.length} items`, !blank.ready && blank.missing.includes("Cash on hand"));
const variant = fn => { const d = Sample.jordan(); fn(d); return Inputs.derive(d); };
const ws = variant(d => { d.awards.push({ name: "Work-Study", type: "workstudy", amount: 1500, accepted: true, minGpa: null, minCredits: null, hasJob: true }); });
add("Work-Study is never credited to the bill", `gap ${jordan.gap}`, `gap ${ws.gap}`, ws.gap === jordan.gap);
const unacc = variant(d => { d.awards[0].accepted = false; });
const unaccWant = Engine.pyRound(jordan.gap + 3500, 2);
add("Awards not accepted don't count", `gap ${unaccWant}`, `gap ${unacc.gap}`, unacc.gap === unaccWant);
const full = variant(d => { d.payment.mode = "full"; });
const fullGot = `${full.case.due.join(", ")}, ${"plan_fee" in full.case ? "fee " + full.case.plan_fee : "no fee"}`;
add("Pay in full: one due date, no plan fee", "2027-01-22, no fee", fullGot, fullGot === "2027-01-22, no fee");
const ov = variant(d => { d.loans.subRoomOverride = 1000; d.loans.unsubRoomOverride = 2500; });
add("myUK loan amounts replace the federal default", "1000 / 2500", `${ov.case.sub_room} / ${ov.case.unsub_room}`,
ov.case.sub_room === 1000 && ov.case.unsub_room === 2500);
const noStub = variant(d => { d.money.takeHome = null; });
add("No pay stub: pay counted before taxes (k = 1)", "k 1, before taxes", `k ${noStub.k}, ${noStub.afterTax ? "after" : "before"} taxes`,
noStub.k === 1 && !noStub.afterTax);
const grad = variant(d => { d.profile.graduationDate = "2029-12-18"; });
add("Payments start 6 months after graduation", "2030-06-18", String(grad.graceEnd), grad.graceEnd === "2030-06-18");
const rt = Schema.parse(Schema.serialize(Sample.jordan()));
const rtOk = rt.ok && same(rt.data, Sample.jordan());
add("Sample student saves and reopens unchanged", "identical data", rtOk ? "identical data" : "differs", rtOk);
// Stage 4: the chart's weekly breakdown, the payoff plan and the sample's headline.
const detailOk = Object.values(TEST_DATA.cases).every(tc =>
same(Engine.forecastDetail(tc.input).map(r => r.cash), Engine.forecast(tc.input).map(r => r[2])));
add("Chart's weekly numbers equal the engine's, every test case", "identical", detailOk ? "identical" : "different", detailOk);
const R = Results.compute(Sample.jordan());
const py4 = TEST_DATA.four_year["Jordan 4yr"].output.this_plan;
const fourGot = `$${R.four.this_plan.borrowed} borrowed, ${R.four.this_plan.months} months`;
const fourWant = `$${py4.borrowed} borrowed, ${py4.months} months`;
add("Sample student's four-year total sets the standard term", fourWant, fourGot, fourGot === fourWant);
const wantOpts = TEST_DATA.options["Jordan (UK plan), 15-year plan"].output;
add("Sample student's option cards (15-year plan)", "same as Python", same(R.opts, wantOpts) ? "same as Python" : "different", same(R.opts, wantOpts));
const hl = Results.headline(R).main;
const hlWant = "You'll drop below your $500 cushion the week of Jan 11, about $3,456 short. Cheapest fix: borrow $4,185 unsubsidized ($4,140 after the fee). It costs about $1,433 in interest and fees if you pay it off over 2 years once payments start.";
add("Sample student's headline", hlWant, hl, hl === hlWant);
const tr = Results.tradeoff(R);
const trWant = "Working about 22 more hours a week instead is worth about $10.43 an hour in interest and fees saved, while $9,930 a year of your aid depends on keeping your GPA.";
add("Sample student's tradeoff line", trWant, tr, tr === trWant);
// Stage 5: aid you're protecting.
const A = Inputs.aidStatus(Sample.jordan());
const aGot = `${A.rows.map(r => `${r.name} ${r.perYear} ${r.status}`).join("; ")}; KEES ${A.kees.perYear} share ${A.kees.share}, ${A.kees.earned} earned, needs ${A.kees.need}, on track ${A.kees.onTrack}; total ${A.total}`;
const aWant = "University scholarship 8430 safe; KEES 1500 share 1, 30 earned, needs null, on track true; total 9930";
add("Sample student's aid you're protecting", aWant, aGot, aGot === aWant);
const u12 = A.under.map(u => `${u.hours}h ${u.total}`).join(", ");
const u12Want = TEST_DATA.kees_more.under_12.filter(t => t.input[0] !== 12 && t.input[0] !== 5).map(t => `${t.input[0]}h ${t.output}`).join(", ");
add("Sample student's under-12 table matches the reference model", u12Want, u12, u12 === u12Want);
const aidVariant = fn => { const d = Sample.jordan(); fn(d); return Inputs.aidStatus(d); };
const low = aidVariant(d => { d.profile.gpa = 2.9; });
const lowGot = `${low.rows[0].status}, KEES share ${low.kees.share}`;
add("GPA 2.90, on track: scholarship at risk, KEES full", "risk, KEES share 1", lowGot, lowGot === "risk, KEES share 1");
// A 2nd-year with 30 earned before + 15 now = 45, under UK's 48: not on track.
const behind = d => { d.profile.yearInSchool = 2; d.profile.semesterCredits = [12, 12, 6]; d.profile.gpa = 2.8; };
const half = aidVariant(d => { behind(d); d.profile.fullTimeRecent = true; });
const halfGot = `${half.kees.earned} of ${half.kees.need}, on track ${half.kees.onTrack}, share ${half.kees.share}`;
add("Year 2, GPA 2.80, 45 of 48 hours, full-time recently: half of KEES", "45 of 48, on track false, share 0.5", halfGot, halfGot === "45 of 48, on track false, share 0.5");
const unsure = aidVariant(d => { behind(d); d.profile.fullTimeRecent = null; });
add("Not sure about full-time recently: both ladder rows shown", "2or3", String(unsure.kees.row), unsure.kees.row === "2or3");
const none = aidVariant(d => { d.profile.gpa = 2.4; });
add("GPA 2.40: next year's KEES lost", "share 0", `share ${none.kees.share}`, none.kees.share === 0);
const assumed = aidVariant(d => { d.profile.semesterCredits = []; d.profile.yearInSchool = 3; d.profile.graduationDate = "2028-05-07"; });
const assumedGot = `${assumed.kees.past} past (assumed ${assumed.kees.assumed}), ${assumed.kees.earned} earned of ${assumed.kees.need}, on track ${assumed.kees.onTrack}`;
const assumedWant = "75 past (assumed true), 90 earned of 72, on track true";
add("No credits entered: 15 a semester assumed (3rd year, spring)", assumedWant, assumedGot, assumedGot === assumedWant);
// Stage 6: the page builds exactly the reference model's four-year inputs, and gets the same results.
for (const [label, fixture, fn] of [
["spring graduation", "Jordan 4yr", () => {}],
["fall graduation", "Jordan 4yr, fall graduation", d => { d.profile.graduationTerm = "fall"; d.profile.graduationDate = "2029-12-18"; }],
]) {
const d = Sample.jordan(); fn(d);
const fy = Inputs.fourYearInput(d, 0, 4185), want = TEST_DATA.four_year[fixture];
add(`Four-year inputs from the sample (${label})`, "same as reference_model.py", same(fy, want.input) ? "same as reference_model.py" : "different", same(fy, want.input));
const got4 = Engine.fourYear(fy);
add(`Four-year results from the sample (${label})`, "same as reference_model.py", same(got4, want.output) ? "same as reference_model.py" : "different", same(got4, want.output));
}
const rated = Sample.jordan(); rated.future.rates = [null, 7]; rated.future.fees = [null, null, 1.5];
const rfy = Inputs.fourYearInput(rated, 0, 4185);
const rGot = rfy.years.map(y => `${y.rate}/${y.fee}`).join(", ");
const rWant = `${CONFIG.loan.rate}/${CONFIG.loan.fee}, 0.07/${CONFIG.loan.fee}, ${CONFIG.loan.rate}/0.015, ${CONFIG.loan.rate}/${CONFIG.loan.fee}`;
add("Later-year rates and fees you enter replace the defaults", rWant, rGot, rGot === rWant);
const oldFile = JSON.parse(Schema.serialize(Sample.jordan()));
delete oldFile.data.future;
const reopened = Schema.parse(JSON.stringify(oldFile));
const reOk = reopened.ok && same(reopened.data.future, { rates: [], fees: [] });
add("Opens a file saved before later-year rates existed", "opens with blank rates", reOk ? "opens with blank rates" : (reopened.ok ? "wrong defaults" : reopened.errors[0]), reOk);
// Private loans (Brian, Nov 12, 2026): a last resort, only with a quoted rate.
const noPrivFile = JSON.parse(Schema.serialize(Sample.jordan()));
delete noPrivFile.data.private;
const np = Schema.parse(JSON.stringify(noPrivFile));
const npOk = np.ok && same(np.data.private, Schema.defaults().private);
add("Opens a file saved before private loans existed", "opens with no private loan", npOk ? "opens with no private loan" : (np.ok ? "wrong defaults" : np.errors[0]), npOk);
const noRate = Results.compute(Sample.jordan());
const nrGot = `private in plans: ${!!(noRate.four.this_plan.private || noRate.four.nothing_extra.private)}; short each spring ${noRate.shorts.full_offer}/${noRate.shorts.this_plan}/${noRate.shorts.nothing_extra}`;
const nrWant = `private in plans: false; short each spring 0/0/${TEST_DATA.options["Jordan (UK plan), 15-year plan"].output.nothing_extra_short}`;
add("No quoted rate: no private loan anywhere; borrowing nothing extra shows how short it leaves you", nrWant, nrGot, nrGot === nrWant);
const quoted = Sample.jordan(); quoted.private.rate = 9.5;
const Rq = Results.compute(quoted), wantPq = TEST_DATA.four_year["Jordan 4yr, private instead"];
add("Quoted 9.5%: four-year inputs match reference_model.py (Jordan 4yr, private instead)", "same as reference_model.py",
same(Rq.fy, wantPq.input) ? "same as reference_model.py" : "different", same(Rq.fy, wantPq.input));
add("Quoted 9.5%: four-year results match reference_model.py", "same as reference_model.py",
same(Rq.four, wantPq.output) ? "same as reference_model.py" : "different", same(Rq.four, wantPq.output));
const recSame = same(Rq.rec, R.rec) && Results.headline(Rq).main === hl;
add("A quoted private rate never changes the recommended fix or the headline", "unchanged", recSame ? "unchanged" : "changed", recSame);
const lastResort = Rq.shorts.nothing_extra === 0 && Rq.four.nothing_extra.private && !Rq.four.this_plan.private;
add("With a rate, the private loan replaces only \"borrow nothing extra\" (this plan stays federal)", "true", String(!!lastResort), !!lastResort);
// Stage 7: sources and the rules every entry must pass.
const how = document.getElementById("how");
const srcRows = how ? [...how.querySelectorAll("table.sources tbody tr")] : [];
const srcOk = srcRows.length === CONFIG.sources.length && CONFIG.sources.every(s => /^https:\/\//.test(s.url))
&& srcRows.every(tr => tr.children[1].textContent.trim().length > 0);
add("Every source is listed with a value and an https link", `${CONFIG.sources.length} sources`, `${srcRows.length} listed${srcOk ? "" : " (missing a value or link)"}`, srcOk);
const csp = document.querySelector('meta[http-equiv="Content-Security-Policy"]')?.content || "";
const cspOk = /default-src 'none'/.test(csp) && !/connect-src|https?:/.test(csp);
add("The page blocks every network request", "default-src 'none'", cspOk ? "default-src 'none'" : csp || "no policy", cspOk);
const firstLine = document.documentElement.previousSibling?.previousSibling;
const copyOk = document.firstChild?.nodeType === Node.COMMENT_NODE && document.firstChild.data.trim() === "Copyright (c) 2026 Brian Dennis. Released under the MIT License.";
add("First line is the copyright notice", "Copyright (c) 2026 Brian Dennis. Released under the MIT License.", copyOk ? "Copyright (c) 2026 Brian Dennis. Released under the MIT License." : String(firstLine && firstLine.data), copyOk);
// Look in the planner's own code (the first two scripts), not in this test script.
const scripts = [...document.scripts].slice(0, 2).map(s => s.textContent).join("\n");
const todo = scripts.includes("TO" + "DO");
add("No TODO left in the code", "none", todo ? "found" : "none", !todo);
return rows;
}
function render(target) {
let blocks;
try { blocks = run(); } catch (err) {
target.append(el("div", { class: "banner fail", text: "Tests could not run: " + err.message }));
return { pass: 0, total: 0, exact: 0 };
}
const all = Object.values(blocks).flat().flatMap(b => b.rows);
const pass = all.filter(r => r.ok).length, exact = all.filter(r => r.exact).length;
target.append(
el("h2", { text: "Test mode" }),
el("p", { class: "legend muted", text: "Each number below was computed twice: by reference_model.py (expected) and by this page (actual). Money must match within $1; monthly payments to the cent." }),
el("div", { class: "banner " + (pass === all.length ? "pass" : "fail"),
text: pass === all.length
? `All ${all.length} checks pass (${exact} exact matches).`
: `${all.length - pass} of ${all.length} checks fail.` }));
const sections = [["Semester cases", blocks.cases], ["Option cards", blocks.opts], ["Aid at risk", blocks.aid],
["Payment plan schedule", blocks.plans],
["Loan room from federal limits", blocks.room],
["KEES renewal ladder", blocks.kees], ["Four-year view and private loans", blocks.four], ["Constants", blocks.consts],
["Save, Open and your inputs", blocks.page]];
for (const [title, list] of sections) {
target.append(el("h2", { text: title }));
list.forEach(b => target.append(b.node));
}
window.__testSummary = { pass, total: all.length, exact };
return window.__testSummary;
}
return { run, render, compare };
})();
/* =====================================================================================
PAGE START
===================================================================================== */
(function start() {
const Live = createStore(Schema.defaults());
UI.init(Live);
window.addEventListener("beforeunload", FileIO.leaveGuard(Live));
const app = document.getElementById("app"), tests = document.getElementById("tests"), how = document.getElementById("how");
// Test mode opens in place (no navigation: hosted pages can't change the visitor's tab).
function showTests() {
app.hidden = true;
how.hidden = true;
tests.hidden = false;
tests.replaceChildren();
const back = document.createElement("button");
back.type = "button";
back.className = "btn secondary back";
back.textContent = "Back to the planner";
back.addEventListener("click", () => { tests.hidden = true; app.hidden = false; how.hidden = false; window.scrollTo(0, 0); });
tests.append(back);
Tests.render(tests);
window.scrollTo(0, 0);
}
document.getElementById("run-tests").addEventListener("click", showTests);
if (new URLSearchParams(location.search).get("test") === "1") showTests();
})();
</script>
</body>
</html>
Websites this page contacts when it runs — fonts, chart libraries, data. Found by reading its source.
Published on Globefin under the MIT License. You may copy, change, and reuse this page, including commercially — just keep the notice below with it.
Copyright © 2026 Brian Dennis. Licensed under the MIT License. Published on Globefin.
Provided as is, without warranty. Any external libraries it loads keep their own licences. Terms →
Scripts run, but the demo has its own throwaway origin. It can't read your session or cookies, can't reach the page around it, and can't navigate your tab. Don't enter real passwords or personal data into any demo.