<!-- 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>
<style>
:root {
--bg: #f7f6f2; --surface: #ffffff; --ink: #1c2230; --muted: #5a6374; --line: #dde1e8;
--accent: #1f5fa8; --good: #1b6e40; --good-bg: #e3f2e9; --bad: #a8261d; --bad-bg: #fbe7e4;
--warn: #7a5200; --warn-bg: #fff1d6; --code-bg: #eef1f5; --dot-unsaved: #d97706; --field-bg: #fdfdfc;
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #11141a; --surface: #191e26; --ink: #e7eaf0; --muted: #a2aab8; --line: #2b323d;
--accent: #86b8ff; --good: #82d4a3; --good-bg: #15301f; --bad: #ff9d93; --bad-bg: #3a1916;
--warn: #f1c36a; --warn-bg: #342910; --code-bg: #222934; --dot-unsaved: #f5a623; --field-bg: #12161d;
color-scheme: dark;
}
}
:root[data-theme="dark"] {
--bg: #11141a; --surface: #191e26; --ink: #e7eaf0; --muted: #a2aab8; --line: #2b323d;
--accent: #86b8ff; --good: #82d4a3; --good-bg: #15301f; --bad: #ff9d93; --bad-bg: #3a1916;
--warn: #f1c36a; --warn-bg: #342910; --code-bg: #222934; --dot-unsaved: #f5a623; --field-bg: #12161d;
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.5 system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
.wrap { max-width: 1040px; margin: 0 auto; padding: 0 24px; }
a { color: var(--accent); }
header.site { background: var(--surface); border-bottom: 1px solid var(--line); padding: 20px 0 16px; }
.eyebrow { margin: 0; font-size: 13px; letter-spacing: .04em; text-transform: uppercase; color: var(--muted); }
h1 { margin: 4px 0 8px; font-size: 28px; line-height: 1.2; }
h2 { font-size: 20px; margin: 28px 0 8px; }
.who { margin: 0 0 12px; color: var(--ink); }
.note { margin: 0; padding: 10px 12px; border-radius: 8px; background: var(--warn-bg); color: var(--ink); font-size: 14px; }
.note strong { color: var(--warn); }
main { padding: 8px 0 32px; }
.card { background: var(--surface); border: 1px solid var(--line); border-radius: 12px; padding: 16px; margin: 16px 0; }
.muted { color: var(--muted); }
.btn { font: inherit; font-weight: 600; padding: 8px 16px; border-radius: 8px; border: 1px solid var(--accent);
background: var(--accent); color: var(--surface); cursor: pointer; }
.btn.secondary { background: transparent; color: var(--accent); }
.btn.back { margin-top: 16px; }
.linkish { font: inherit; background: none; border: 0; color: var(--accent); text-decoration: underline; cursor: pointer; padding: 8px 6px; }
.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: 16px 0 28px; font-size: 14px; color: var(--muted); }
footer p { margin: 6px 0; }
/* Test mode */
.banner { padding: 12px 14px; border-radius: 10px; 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: 10px; 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: 6px 8px; border-bottom: 1px solid var(--line); vertical-align: top; }
th { color: var(--muted); font-weight: 600; white-space: nowrap; }
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; }
/* Your numbers (simple form; Stage 3 turns it into the guided form) */
fieldset.group { border: 1px solid var(--line); border-radius: 12px; background: var(--surface); margin: 16px 0; padding: 8px 20px 18px; }
fieldset.group > legend { font-weight: 700; font-size: 18px; padding: 0 6px; }
.group-note { margin: 0 0 12px; }
.fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 14px 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 {
width: 100%; font: inherit; padding: 6px 8px; border: 1px solid var(--line); border-radius: 6px;
background: var(--field-bg); color: var(--ink); }
.field input[type="checkbox"], .awards input[type="checkbox"] { width: auto; }
.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: 960px; }
.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: var(--surface); border-top: 1px solid var(--line); box-shadow: 0 -2px 12px rgba(0,0,0,.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; }
.filemsg { margin: 0 0 10px; padding: 10px 12px; border-radius: 8px; font-size: 14px; display: flex; gap: 12px; align-items: flex-start; }
.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: 12px; background: var(--surface); color: var(--ink); width: min(640px, calc(100% - 48px)); padding: 20px 24px; }
dialog::backdrop { background: rgba(0,0,0,.45); }
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; }
.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; }
</style>
</head>
<body>
<header class="site">
<div class="wrap">
<p class="eyebrow">Kentucky PFM Challenge · Debt</p>
<h1>Make It to May</h1>
<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"><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.</p>
</div>
</header>
<main class="wrap" id="main">
<section id="app">
<div class="card">
<h2 style="margin-top:0">Under construction</h2>
<p>The math engine and saving are built. The guided form, the weekly chart and your options come next. For now you can type numbers below, save them to a file and open them again.</p>
<p><button type="button" class="btn" id="run-tests">Run the test cases</button></p>
<p class="muted small">The tests check every number this page computes against the reference model, plus saving and opening. You can also open the page with <code>?test=1</code> at the end of its address.</p>
</div>
<h2>Your numbers</h2>
<p class="muted small">Plain numbers from myUK or a pay stub. Never a bank login. School settings start with the University of Kentucky's spring 2027 dates and payment plan; change them if your school is different.</p>
<div id="editor"></div>
</section>
<section id="tests" hidden></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></p>
<div class="file-actions">
<button type="button" class="btn" id="save-btn">Save to file</button>
<button type="button" class="btn secondary" id="open-btn">Open file</button>
<button type="button" class="linkish" id="copy-btn">Copy data</button>
<button type="button" class="linkish" id="paste-btn">Paste data</button>
<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="confirm-dialog" aria-labelledby="confirm-title">
<h2 id="confirm-title">Replace your unsaved changes?</h2>
<p>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>
</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: 12+ credit hours full; 6–11 prorated (assumed hours ÷ 12, VERIFY); 1–5 none. Same source.
fullTimeHours: 12, minHours: 6,
// Max 8 academic terms (400% lifetime, = 8 full-time semesters), used by the earlier of finishing a
// bachelor's degree or 5 years from high school graduation. Text supplied by Brian, Nov 11, 2026
// (KHEAA administers KEES). TODO: confirm source URL.
maxTerms: 8, lifetimePercent: 400, yearsFromHighSchool: 5,
},
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",
},
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",
},
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 completed semester 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) };
}
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) };
}
// ---- 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;
}
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 = {};
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));
cumSub += sub;
cumTotal += sub + unsub;
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));
for (const [when, part] of [[y.fall, fall], [y.spring, amt - fall]]) {
if (part > 0) loans.push({ gross: part, sub: isSub, rate: y.rate, fee: y.fee, disb: when });
}
}
});
const total = pySum(loans.map(l => l.gross));
const months = fy.own_years ? fy.own_years * 12 : standardMonths(total);
out[plan] = payoff(loans, fy.grace_end, months);
}
return out;
}
return { pyRound, pySum, toDay, toIso, monday, addMonths, planDates, graceEndFrom, netOfFee, gap, splitInstallments,
billSchedule, billsByDate, forecast, shortfall, preAidDip, levelPayment, loanCost, grid, solve, loanRoom,
standardMonths, keesNextYear, keesTermShare, payoff, fourYear };
})();
// 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: its label, type and allowed range. The form and the file check both use this list.
const GROUPS = [
{ id: "about", title: "About you", fields: [
f("profile.yearInSchool", "Year in school", "enum", { options: [[1, "1st year"], [2, "2nd year"], [3, "3rd year"], [4, "4th year or more"]] }),
f("profile.dependency", "FAFSA dependency status", "enum", { options: [["independent", "Independent"], ["dependent", "Dependent"]] }),
f("profile.graduationTerm", "Expected graduation term", "enum", { options: [["spring", "Spring"], ["fall", "Fall"]] }),
f("profile.graduationYear", "Expected graduation year", "int", { min: 2026, max: 2040 }),
f("profile.graduationDate", "Graduation date", "date"),
f("profile.gpa", "Cumulative GPA", "num", { min: 0, max: 4, step: 0.01 }),
f("profile.creditHours", "Credit hours this term", "num", { min: 0, max: 30, step: 0.5 }),
f("profile.earnedHours", "Credit hours earned so far", "num", { min: 0, max: 300, step: 0.5 }),
f("profile.fullTimeRecent", "Full-time (12+ hours) in one of your last two terms", "bool"),
f("profile.creditGoal", "Credit hours you need to graduate", "num", { min: 0, max: 300, step: 0.5 }),
] },
{ id: "term", title: "Your school and term", note: "Starts with UK's spring 2027 calendar. Change these if your school is different.", fields: [
f("school.termName", "Term", "text", { nullable: false, max: 40 }),
f("school.forecastStart", "Start the forecast on", "date", { nullable: false }),
f("school.aidDate", "Aid arrives (disbursement date)", "date", { nullable: false }),
f("school.termEnd", "Last day of the term", "date", { nullable: false }),
f("school.noPayWeeks", "Weeks with no paycheck (for example, winter break)", "dates", { nullable: false, maxItems: 40, addLabel: "Add a week", every: "week" }),
] },
{ id: "bill", title: "Your bill and how you pay it", note: "Payment plan settings start with UK's real plan (4 payments, the 22nd, $50 fee). Not every school has a monthly plan; pick \"Pay in full\" if yours doesn't.", fields: [
money("bill.tuition", "Tuition and fees"),
money("bill.housing", "Housing"),
money("bill.meals", "Meal plan"),
money("bill.books", "Books (if billed)"),
money("bill.other", "Other billed charges"),
f("payment.mode", "How you pay the bill", "enum", { nullable: false, options: [["plan", "Monthly payment plan"], ["full", "Pay in full by the due date"]] }),
f("payment.fullDue", "Due date if paying in full", "date", { nullable: false }),
f("payment.firstPayment", "First plan payment (when you enroll)", "date", { nullable: false }),
f("payment.payments", "Number of plan 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 }),
money("payment.minBalance", "Plan minimum balance", { nullable: false }),
f("payment.dates", "Plan payment dates (rebuilt when you change the plan settings)", "dates", { nullable: false, maxItems: 12, addLabel: "Add a date", every: "month" }),
] },
{ id: "aid", title: "Your aid this term", awards: true, fields: [
money("loans.priorTotal", "Federal loans from earlier years (total)"),
money("loans.priorSub", "…of which subsidized"),
money("loans.subRoomOverride", "Subsidized loan room myUK offers (optional)"),
money("loans.unsubRoomOverride", "Unsubsidized loan room myUK offers (optional)"),
] },
{ id: "money", title: "Your money", fields: [
money("money.cash", "Cash on hand today", { min: -100000 }),
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 (from a pay stub, optional)", { max: 20000 }),
f("money.safeMax", "Most hours a week you can work without hurting grades", "num", { min: 0, max: 100, step: 0.5 }),
f("money.hoursCeiling", "Highest weekly hours to consider", "num", { nullable: false, min: 1, max: 168, step: 0.5 }),
money("money.living", "Living costs outside the bill, per month"),
money("money.cushion", "Emergency cushion to keep"),
] },
{ id: "payoff", title: "After school", fields: [
f("payoff.mode", "Payoff plan", "enum", { nullable: false, options: [["standard", "Standard plan (length set by total debt)"], ["years", "Pay it off in my own number of years"]] }),
f("payoff.years", "Years to pay off", "int", { min: 1, max: 30 }),
] },
];
const FIELDS = GROUPS.flatMap(g => g.fields);
const AWARD_FIELDS = [
f("name", "Name", "text", { nullable: false, max: 60 }),
f("type", "Type", "enum", { nullable: false, options: AWARD_TYPES }),
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 });
const fmtNum = n => 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)} to ${fmtNum(max)}.`;
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).`;
}
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) {
const v = getPath(raw, fd.path), 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, earnedHours: null, fullTimeRecent: null, creditGoal: 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 },
};
}
// 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, earnedHours: 30, fullTimeRecent: true, creditGoal: 120 });
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 });
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, 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 };
})();
/* =====================================================================================
PAGE: the save bar, dialogs and the simple form (Stage 3 turns the form into the guided steps).
===================================================================================== */
const UI = (() => {
const $ = id => document.getElementById(id);
let store, uid = 0;
const refreshers = {};
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;
}
// ---- 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}`
: "No changes yet";
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;
}
// ---- Save, Open, Copy, Paste ----
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 confirmReplace() {
const d = $("confirm-dialog"), yes = $("confirm-yes"), no = $("confirm-no");
return new Promise(resolve => {
const finish = v => {
yes.removeEventListener("click", onYes); no.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); };
yes.addEventListener("click", onYes); no.addEventListener("click", onNo); d.addEventListener("cancel", onCancel);
d.showModal();
no.focus();
});
}
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);
renderEditor();
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() {
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();
renderEditor();
showMsg("ok", "Restored your numbers from the pasted data.");
}
// ---- Simple form ----
function afterChange(path) {
const p = store.data;
if (["payment.firstPayment", "payment.payments", "payment.dueDay"].includes(path)) {
p.payment.dates = Engine.planDates(p.payment.firstPayment, p.payment.payments, p.payment.dueDay);
refreshers["payment.dates"]?.();
}
if ((path === "profile.graduationTerm" || path === "profile.graduationYear") &&
p.profile.graduationTerm === "spring" && p.profile.graduationYear) {
p.profile.graduationDate = `${p.profile.graduationYear}-${CONFIG.product.springGraduationDay}`;
refreshers["profile.graduationDate"]?.();
}
}
function control(fd, path, id, errEl) {
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); }
};
switch (fd.kind) {
case "money": case "num": case "int": {
const input = h("input", { id, type: "number", step: fd.kind === "int" ? "1" : String(fd.step ?? 0.01),
min: String(fd.min ?? 0), max: String(fd.max ?? 1000000), "aria-describedby": errEl.id });
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", { id, type: "date", "aria-describedby": errEl.id });
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", { id, type: "text", maxlength: String(fd.max ?? 60), "aria-describedby": errEl.id });
input.value = value ?? "";
input.addEventListener("input", () => commit(input.value, input));
return input;
}
case "bool":
if (!fd.nullable) {
const cb = h("input", { id, type: "checkbox" });
cb.checked = value === true;
cb.addEventListener("change", () => commit(cb.checked, cb));
return cb;
}
// falls through: an optional yes/no is a select with "Not sure"
case "enum": {
const opts = fd.kind === "bool" ? [[true, "Yes"], [false, "No"]] : fd.options;
const sel = h("select", { id, "aria-describedby": errEl.id });
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": return dateList(fd, path, id);
}
return h("span", { text: "?" });
}
function dateList(fd, path, id) {
const box = h("div", { class: "datelist", role: "group", "aria-labelledby": id + "-label" });
function draw() {
box.replaceChildren();
const list = Schema.getPath(store.data, path);
list.forEach((date, i) => {
const input = h("input", { type: "date", "aria-label": `${fd.label}, date ${i + 1}` });
input.value = date;
input.addEventListener("change", () => {
const ok = Schema.isDate(input.value);
input.setAttribute("aria-invalid", ok ? "false" : "true");
if (!ok) return;
const next = [...Schema.getPath(store.data, path)];
next[i] = input.value;
store.set(path, next);
});
const rm = h("button", { type: "button", class: "linkish", text: "Remove", "aria-label": `Remove date ${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", text: fd.addLabel || "Add" });
add.addEventListener("click", () => {
const cur = Schema.getPath(store.data, path), last = cur[cur.length - 1];
const nextDate = fd.every === "month"
? (last ? Engine.addMonths(last, 1) : store.data.payment.firstPayment)
: (last ? Engine.toIso(Engine.toDay(last) + 7) : store.data.school.forecastStart);
store.set(path, [...cur, nextDate]);
draw();
});
box.append(add);
}
}
draw();
refreshers[path] = draw;
return box;
}
function fieldBlock(fd) {
const id = "f" + (++uid);
const err = h("p", { class: "err", id: id + "-err", hidden: "" });
const label = fd.kind === "dates" ? h("span", { class: "label", id: id + "-label", text: fd.label })
: h("label", { for: id, text: fd.label });
return h("div", { class: "field" + (fd.kind === "dates" ? " wide" : "") }, label, control(fd, fd.path, id, err), err);
}
function awardsEditor() {
const wrap = h("div", { class: "awards" });
function draw() {
wrap.replaceChildren();
const awards = store.data.awards;
const body = h("tbody");
awards.forEach((a, i) => {
const tr = h("tr");
for (const fd of Schema.AWARD_FIELDS) {
const id = "f" + (++uid);
const err = h("p", { class: "err", id: id + "-err", hidden: "" });
const ctrl = control(fd, `awards.${i}.${fd.path}`, 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(); draw(); });
tr.append(h("td", {}, rm));
body.append(tr);
});
if (awards.length) {
wrap.append(h("table", {},
h("thead", {}, h("tr", {}, ...Schema.AWARD_FIELDS.map(fd => h("th", { text: fd.label })), 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) {
const add = h("button", { type: "button", class: "btn secondary", text: "Add an award" });
add.addEventListener("click", () => { store.data.awards.push(Schema.newAward()); store.touch(); draw(); });
wrap.append(h("p", {}, add));
}
}
draw();
return wrap;
}
function renderEditor() {
const root = $("editor");
root.replaceChildren();
for (const g of Schema.GROUPS) {
const fs = h("fieldset", { class: "group" }, h("legend", { text: g.title }),
g.note ? h("p", { class: "group-note muted small", text: g.note }) : null,
h("div", { class: "fields" }, ...g.fields.map(fieldBlock)));
if (g.awards) fs.append(awardsEditor());
root.append(fs);
}
}
function init(s) {
store = s;
store.on(renderStatus);
renderEditor();
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);
$("paste-do").addEventListener("click", doPaste);
$("paste-close").addEventListener("click", () => $("paste-dialog").close());
}
return { init, renderEditor };
})();
</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}}},"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"]}},"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}}},"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-26","spring":"2027-01-11","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":2,"fall":"2027-08-25","spring":"2028-01-10","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2028-08-23","spring":"2029-01-08","rate":0.0652,"fee":0.01057,"accepted_sub":3500,"accepted_unsub":0},{"level":3,"fall":"2029-08-22","spring":"2030-01-07","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":4064.2,"months":180,"payment":424.43,"total_repaid":76397.4,"interest":31397.4,"payoff_date":"2045-11-07"},"this_plan":{"sub_borrowed":14000,"unsub_borrowed":16740,"borrowed":30740,"fees":324.96,"accrued":2541.72,"months":180,"payment":288.06,"total_repaid":51850.8,"interest":21110.8,"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"}}},"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"}}}},"constants":{"RATE":0.0652,"FEE":0.01057,"PLAN_FEE":50.0}};
// 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"]);
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));
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))));
}
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 })));
blocks.page = [block("Save and Open", "page checks (no Python equivalent)", pageChecks())];
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");
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], ["Payment plan schedule", blocks.plans],
["Loan room from federal limits", blocks.room],
["KEES renewal ladder", blocks.kees], ["Four-year view", blocks.four], ["Constants", blocks.consts],
["Save and Open", 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");
// Test mode opens in place (no navigation: hosted pages can't change the visitor's tab).
function showTests() {
app.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; });
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.