feat(lex): Payment view — every year, proposed apart from final, charts (S1)
Some checks failed
CI / lint (push) Successful in 1m36s
CI / notebooks-smoke (push) Successful in 2m42s
Deploy / changes (push) Successful in 29s
CI / test (push) Has started running
Deploy / report (push) Has been cancelled
Deploy / notebooks (push) Has been cancelled
Deploy / zotero (push) Has been cancelled
Deploy / docs (push) Has been cancelled
Deploy / api (push) Has been cancelled
Deploy / bcda (push) Has been cancelled
Deploy / llm (push) Has been cancelled
Deploy / mc (push) Has been cancelled
Infra CI / zotero (push) Successful in 37s
Infra CI / notebooks (push) Successful in 1m40s
Infra CI / docs (push) Successful in 1m56s
Infra CI / api (push) Successful in 3m29s
Infra CI / llm (push) Successful in 1m25s
Infra CI / bcda (push) Successful in 3m57s
Infra CI / mc (push) Successful in 31s

This commit is contained in:
kert
2026-11-13 04:12:20 -05:00
parent 9a1385eebe
commit 3f6b44a33b
2 changed files with 325 additions and 5 deletions

View File

@@ -1,10 +1,232 @@
// lex · Payment view. A stub until S1 Task 8 fills it in.
// lex · Payment view: national non-facility payment = non-facility total RVUs
// x conversion factor, one column per year on file.
//
// A view module exports needs (the API slices it reads), render(data, state)
// returning markup, and optionally mount(root, data, state, nav).
// Proposed values sit in their own hatched column (with a "proposed" header),
// before that year's final column, and are never blended with final values.
// Every code group shows by default; the Active/Deleted/Linked buttons only
// filter (S1-P2). The metric and group buttons are UI state, not URL state.
import { esc, int, money, n2 } from "./fmt.js";
import { citeHtml, factHtml } from "./cite.js";
export const needs = ["header", "payment"];
export function render() {
return `<p class="muted">This view is being built.</p>`;
const METRICS = [
["pay_nf", "Payment $"],
["work", "Work RVU"],
["total_nf", "Total RVU (non-facility)"],
];
const GROUPS = [
["active", "Active"],
["deleted", "Deleted"],
["linked", "Linked"],
];
const ui = { metric: "pay_nf", group: "all" };
const byId = (a, b) => parseInt(String(a.id).slice(1), 10) - parseInt(String(b.id).slice(1), 10);
const groups = (P) => P.code_groups || {};
const allCodes = (P) => [...(groups(P).active || []), ...(groups(P).deleted || []), ...(groups(P).linked || [])];
const shownCodes = (P, group) => (group === "all" ? allCodes(P) : groups(P)[group] || []);
/** The columns: per year, the proposed one first when that year has one. */
function columns(rows) {
const keys = new Map();
for (const r of rows) keys.set(r.vintage, { vintage: r.vintage, year: r.year, proposed: !!r.proposed });
return Array.from(keys.values()).sort((a, b) => a.year - b.year || (b.proposed ? 1 : 0) - (a.proposed ? 1 : 0));
}
const fmt = (metric, v) => (metric === "pay_nf" ? money(v) : n2(v));
function firstOf(rows, vintage) {
return rows.find((r) => r.vintage === vintage) || null;
}
/** The table: a code row per code, a column per vintage, then CF and Source. */
export function payTable(P, { metric = "pay_nf", group = "all" } = {}, code = "") {
const rows = P.rows || [];
const cols = columns(rows);
const cells = P.cells || {};
const cls = (c, extra = "") => `${extra}${c.proposed ? " pcol" : ""}`.trim();
let h = `<div class="tbl-wrap" id="pay-scroll"><table class="tbl pay-tbl"><thead><tr><th class="stick">Code</th>`;
h += cols.map((c) => `<th class="${cls(c, "r")}">CY${esc(c.year)}<br>${c.proposed ? "proposed" : "final"}</th>`).join("");
h += `</tr></thead><tbody>`;
for (const k of shownCodes(P, group)) {
h += `<tr data-code="${esc(k)}"${k === code ? ' class="sel"' : ""}><td class="mono stick">${esc(k)}</td>`;
for (const c of cols) {
const r = rows.find((x) => x.code === k && x.vintage === c.vintage);
if (!r) {
h += `<td class="${cls(c, "r na")}">—</td>`;
continue;
}
const id = cells[`${k}|${c.vintage}`];
const fact = id ? ` data-fact="${esc(id)}" tabindex="0"` : "";
const v = r[metric];
const unpaid = metric === "pay_nf" && v == null;
h += `<td class="${cls(c, "r num" + (unpaid ? " na" : ""))}" title="${esc(unpaid ? r.status_note : r.label)}"${fact}>${unpaid ? esc(r.status) : esc(fmt(metric, v))}</td>`;
}
h += `</tr>`;
}
h += `<tr><td class="mono small stick">Conv. factor</td>${cols.map((c) => `<td class="${cls(c, "r num")}">${esc(n2((firstOf(rows, c.vintage) || {}).cf))}</td>`).join("")}</tr>`;
h += `<tr><td class="mono small stick">Source</td>${cols
.map((c) => {
const r = firstOf(rows, c.vintage);
const cite = r ? { kind: "rvu_file", label: r.citation, url: r.url, locator: "" } : null;
return `<td class="${cls(c, "r small")}">${citeHtml(cite)}</td>`;
})
.join("")}</tr>`;
return h + `</tbody></table></div>`;
}
const legend = (inner) => `<div class="legend">${inner}</div>`;
/** National non-facility payment for a code: the final line, proposed rings. */
export function payChart(rows, code) {
const mine = rows.filter((p) => p.code === code);
const fin = mine.filter((p) => !p.proposed && p.pay_nf != null).sort((a, b) => a.year - b.year);
const pro = mine.filter((p) => p.proposed && p.pay_nf != null).sort((a, b) => a.year - b.year);
const ys = [...fin, ...pro].map((p) => p.pay_nf);
if (!ys.length) return `<p class="small muted">No RVU-based payment for ${esc(code)} (status ${esc((mine[0] || {}).status || "none on file")}).</p>`;
const years = Array.from(new Set(rows.map((p) => p.year))).sort((a, b) => a - b);
const x0 = years[0];
const x1 = years[years.length - 1];
const W = 640, H = 230, L = 58, R = 64, T = 18, B = 30;
const top = Math.max(...ys);
const step = top > 150 ? 50 : top > 60 ? 25 : 10;
const ymax = Math.ceil((top * 1.08) / step) * step;
const X = (y) => (x1 === x0 ? (L + W - R) / 2 : L + ((y - x0) / (x1 - x0)) * (W - L - R));
const Y = (v) => T + (1 - v / ymax) * (H - T - B);
let s = `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img" aria-label="National non-facility payment for ${esc(code)}, final and proposed">`;
for (let v = 0; v <= ymax + 1e-9; v += step) s += `<line class="grid" x1="${L}" x2="${W - R}" y1="${Y(v)}" y2="${Y(v)}"/><text x="${L - 8}" y="${Y(v) + 4}" text-anchor="end">$${v}</text>`;
for (const y of years) if ((y - x0) % 2 === 0 || y === x1) s += `<text x="${X(y)}" y="${H - 10}" text-anchor="middle">${esc(y)}</text>`;
s += `<line class="ax" x1="${L}" x2="${W - R}" y1="${Y(0)}" y2="${Y(0)}"/>`;
let path = "";
let prev = null;
for (const p of fin) {
path += (prev != null && p.year === prev + 1 ? "L" : "M") + X(p.year).toFixed(1) + " " + Y(p.pay_nf).toFixed(1);
prev = p.year;
}
s += `<path d="${path}" fill="none" stroke="var(--s-final)" stroke-width="2"/>`;
const tip = (p, what) => esc(`${code} · CY${p.year} ${what} · ${money(p.pay_nf)} · CF ${p.cf == null ? "—" : "$" + Number(p.cf).toFixed(4)}`);
for (const p of fin) s += `<circle cx="${X(p.year)}" cy="${Y(p.pay_nf)}" r="4" fill="var(--s-final)" stroke="var(--card)" stroke-width="2" data-tip="${tip(p, "final")}"/>`;
for (const p of pro) s += `<circle cx="${X(p.year)}" cy="${Y(p.pay_nf)}" r="6.5" fill="none" stroke="var(--s-prop)" stroke-width="2" data-tip="${tip(p, "proposed")}"/>`;
const last = fin[fin.length - 1];
if (last) s += `<text x="${Math.min(X(last.year) + 10, W - 4)}" y="${Y(last.pay_nf) + 4}" text-anchor="${X(last.year) + 10 > W - 50 ? "end" : "start"}" style="fill:var(--foreground)">${esc(money(last.pay_nf))}</text>`;
return (
s +
`</svg>` +
legend(`<span><span class="sw" style="background:var(--s-final)"></span>Final (Addendum B × CF)</span><span><span class="sw" style="border:2px solid var(--s-prop);border-radius:50%"></span>Proposed (proposed-rule Addendum B × proposed CF)</span>`)
);
}
/** Medicare allowed services for a code, one bar per year. */
export function volChart(utilization, code) {
const all = utilization || [];
const mine = all.filter((u) => u.hcpcs === code && u.n_services != null);
if (!mine.length) return `<p class="small muted">No national utilization rows for ${esc(code)}.</p>`;
const lo = Math.min(...all.map((u) => u.year));
const hi = Math.max(...all.map((u) => u.year));
const yrs = [];
for (let y = lo; y <= hi; y++) yrs.push(y);
const W = 640, H = 150, L = 58, R = 64, T = 12, B = 26;
const vmax = Math.max(...mine.map((r) => r.n_services));
const mag = Math.pow(10, Math.floor(Math.log10(vmax)));
const step = vmax / mag > 5 ? mag * 2 : vmax / mag > 2 ? mag : mag / 2;
const ymax = Math.ceil(vmax / step) * step;
const bw = (W - L - R) / yrs.length;
const X = (y) => L + (y - lo) * bw;
const Y = (v) => T + (1 - v / ymax) * (H - T - B);
let s = `<svg class="chart" viewBox="0 0 ${W} ${H}" role="img" aria-label="Medicare allowed services for ${esc(code)} by year">`;
for (let v = 0; v <= ymax + 1e-9; v += step) s += `<line class="grid" x1="${L}" x2="${W - R}" y1="${Y(v)}" y2="${Y(v)}"/><text x="${L - 8}" y="${Y(v) + 4}" text-anchor="end">${v >= 1e6 ? (v / 1e6).toFixed(1) + "M" : v >= 1000 ? Math.round(v / 1000) + "k" : v}</text>`;
for (const y of yrs) {
const r = mine.find((x) => x.year === y);
if (r) {
const h = Y(0) - Y(r.n_services);
s += `<path d="M${X(y) + 3} ${Y(0)} V${Y(r.n_services) + Math.min(4, h)} q0 -4 4 -4 H${X(y) + bw - 7} q4 0 4 4 V${Y(0)} Z" fill="var(--s-final)" data-tip="${esc(`${code} · ${y} · ${int(r.n_services)} services`)}"/>`;
}
if ((y - lo) % 2 === 0 || y === hi) s += `<text x="${X(y) + bw / 2}" y="${H - 8}" text-anchor="middle">${esc(y)}</text>`;
}
return s + `<line class="ax" x1="${L}" x2="${W - R}" y1="${Y(0)}" y2="${Y(0)}"/></svg>`;
}
function controls(P) {
const g = groups(P);
const n = (k) => (g[k] || []).length;
let h = `<div class="filters" id="pay-f"><span class="eyebrow">Show</span>`;
h += METRICS.map(([k, label]) => `<button class="fbtn" type="button" data-m="${k}" aria-pressed="${ui.metric === k}">${esc(label)}</button>`).join("");
h += `<span class="eyebrow" style="margin-left:10px">Codes</span>`;
h += `<button class="fbtn" type="button" data-g="all" aria-pressed="${ui.group === "all"}">All ${allCodes(P).length}</button>`;
h += GROUPS.map(([k, label]) => `<button class="fbtn" type="button" data-g="${k}" aria-pressed="${ui.group === k}">${esc(label)} ${n(k)}</button>`).join("");
return h + `</div>`;
}
function charts(P, code) {
return `<div class="charts"><div class="chart-box"><div class="col-h"><h3 id="pay-ch-h">${esc(code)}: national non-facility payment</h3></div><div id="pay-ch">${payChart(P.rows || [], code)}</div></div>
<div class="chart-box"><div class="col-h"><h3 id="vol-ch-h">${esc(code)}: Medicare allowed services</h3></div><div id="vol-ch">${volChart(P.utilization, code)}</div>
<p class="small muted">National totals, all places of service, from CMS's Medicare Physician &amp; Other Practitioners by Geography and Service files.</p></div></div>`;
}
function cfNotes(P) {
const seen = new Set();
const items = [];
for (const c of columns(P.rows || [])) {
const r = firstOf(P.rows, c.vintage);
const note = r && r.cf_note;
if (!note || seen.has(c.vintage + "|" + note)) continue;
seen.add(c.vintage + "|" + note);
items.push(`<li><b>CY${esc(c.year)} ${c.proposed ? "proposed" : "final"}</b> ${esc(note)}</li>`);
}
return items.length ? `<div class="sec"><h3>Conversion factor notes</h3><ul class="gaps">${items.join("")}</ul></div>` : "";
}
const selectedCode = (P, state) => (state && state.code) || (groups(P).active || [])[0] || allCodes(P)[0] || "";
export function render(data, state) {
const P = data.payment;
const code = selectedCode(P, state);
let h = `<div class="col-h"><h2>Payment</h2></div>
<p class="lede">National unadjusted non-facility payment = non-facility total RVUs × conversion factor, for every year on file. Final values come from each final rule's RVU file; proposed values from the proposed rule's file. They sit in separate columns and are never combined.</p>`;
if (!(P.rows || []).length) return h + `<p class="muted">No payment rows captured for this family.</p>`;
h += controls(P);
h += legend(`<span><span class="pill prop">proposed</span> hatched columns</span><span><span class="pill final">final</span> plain columns</span><span class="muted">Select a code to chart it.</span>`);
h += `<div id="pay-tbl">${payTable(P, ui, code)}</div>`;
h += `<p class="small muted">The table opens at the latest years; scroll it sideways for earlier ones. A status letter in place of a dollar value means the status is not paid from RVUs × CF (hover for the reason). A dash means the code is not in that year's file.</p>`;
h += charts(P, code);
h += cfNotes(P);
const facts = P.facts || {};
const un = (P.unplaced || []).map((id) => facts[id]).filter(Boolean).sort(byId);
if (un.length) h += `<div class="sec"><span class="eyebrow">Unplaced payment facts</span><p class="small muted">Facts the table has no cell for. They are listed so none is lost.</p><ul class="facts">${un.map((f) => factHtml(f)).join("")}</ul></div>`;
return h;
}
export function mount(root, data, state, nav) {
const P = data.payment;
const code = selectedCode(P, state);
const tbl = root.querySelector("#pay-tbl");
if (!tbl) return;
const scrollEnd = () => {
const sc = root.querySelector("#pay-scroll");
if (sc) sc.scrollLeft = sc.scrollWidth;
};
scrollEnd();
const bar = root.querySelector("#pay-f");
bar.addEventListener("click", (e) => {
const b = e.target.closest("button");
if (!b) return;
if (b.dataset.m) ui.metric = b.dataset.m;
if (b.dataset.g) ui.group = b.dataset.g;
for (const x of bar.querySelectorAll("[data-m]")) x.setAttribute("aria-pressed", String(x.dataset.m === ui.metric));
for (const x of bar.querySelectorAll("[data-g]")) x.setAttribute("aria-pressed", String(x.dataset.g === ui.group));
const sc = root.querySelector("#pay-scroll");
const left = sc ? sc.scrollLeft : 0;
tbl.innerHTML = payTable(P, ui, code);
const sc2 = root.querySelector("#pay-scroll");
if (sc2) sc2.scrollLeft = left;
});
// a click on a row (not on a value cell, which opens its fact) charts that code
tbl.addEventListener("click", (e) => {
if (e.target.closest("a, button, [data-fact]")) return;
const tr = e.target.closest("tr[data-code]");
if (tr) nav.go({ code: tr.dataset.code }, { push: false });
});
}

View File

@@ -0,0 +1,98 @@
// lex · Payment view.
import { test } from "node:test";
import { equal as eq, ok } from "node:assert/strict";
import { readFileSync } from "node:fs";
import { parseLocation } from "../../infra/gitea/custom/public/assets/dossier/state.js";
import * as payment from "../../infra/gitea/custom/public/assets/dossier/view-payment.js";
const fx = (name) => JSON.parse(readFileSync(new URL(`./fixtures/${name}.json`, import.meta.url), "utf8"));
const H = fx("header");
const P = fx("payment");
const st = (url) => parseLocation(new URL(url, "https://lex.test"));
const count = (s, sub) => s.split(sub).length - 1;
const page = (url = "/payment?family=HOME-VISITS", p = P) => payment.render({ header: H, payment: p }, st(url));
test("payment: every cell fact, a hatched proposed column, the unplaced fact", () => {
const p = page();
for (const [k, id] of Object.entries(P.cells)) ok(p.includes(`data-fact="${id}"`), k);
ok(p.includes('data-fact="F18"') && p.includes("proposed") && p.includes("pcol"));
eq(payment.needs.join(), "header,payment");
ok(p.includes("Unplaced payment facts") && p.includes("Invented orphan payment."));
});
test("payment: the proposed column sits before its year's final column, apart", () => {
const t = payment.payTable(P, { metric: "pay_nf", group: "all" });
const heads = t.match(/<th[^>]*>.*?<\/th>/g);
const i27 = heads.findIndex((h) => h.includes("CY2027"));
ok(heads[i27].includes("pcol") && heads[i27].includes("proposed"));
ok(heads.findIndex((h) => h.includes("CY2023")) < i27);
eq(heads.length, 1 + 3, "code, CY2022, CY2023, CY2027 proposed");
// the proposed cell is in the hatched column, the final one is not
ok(/class="[^"]*pcol[^"]*"[^>]*data-fact="F12"|data-fact="F12"[^>]*class="[^"]*pcol/.test(t));
ok(!/pcol[^>]*data-fact="F11"|data-fact="F11"[^>]*pcol/.test(t));
});
test("payment: every group shows by default, the buttons only filter", () => {
const all = page();
for (const c of ["99341", "99343", "G0318"]) ok(all.includes(`data-code="${c}"`), c);
ok(all.includes("Active 1") && all.includes("Deleted 1") && all.includes("Linked 1"));
const del = payment.payTable(P, { metric: "pay_nf", group: "deleted" });
ok(del.includes('data-code="99343"') && !del.includes('data-code="99341"'));
});
test("payment: metric buttons, the value follows the metric", () => {
const pay = payment.payTable(P, { metric: "pay_nf", group: "all" });
const work = payment.payTable(P, { metric: "work", group: "all" });
const tot = payment.payTable(P, { metric: "total_nf", group: "all" });
ok(pay.includes("$69.30") && !pay.includes(">2.10<"));
ok(work.includes(">1.00<") && !work.includes("$69.30"));
ok(tot.includes(">2.10<"));
const h = page();
ok(h.includes("Payment $") && h.includes("Work RVU") && h.includes("Total RVU"));
});
test("payment: an unpaid status shows its letter with the note, a missing row a dash", () => {
const rows = P.rows.map((r) => (r.code === "99341" && r.year === 2023 ? { ...r, status: "B", pay_nf: null, status_note: "bundled — no separate PFS payment" } : r));
const t = payment.payTable({ ...P, rows }, { metric: "pay_nf", group: "all" });
ok(/title="bundled — no separate PFS payment"[^>]*>B</.test(t));
ok(t.includes(">—<"));
});
test("payment: CF row, source row, CF notes unchanged and escaped", () => {
const rows = P.rows.map((r) => (r.vintage === "CY2027 proposed" ? { ...r, cf_note: "proposed; QP CF $33.1693 <b>", citation: "CY2027 <i>RVU</i>" } : r));
const p = page("/payment?family=HOME-VISITS", { ...P, rows });
ok(p.includes("Conv. factor") && p.includes("Source") && p.includes("33.00"));
ok(p.includes("proposed; QP CF $33.1693 &lt;b&gt;") && !p.includes("<b>\n"));
ok(p.includes("CY2027 &lt;i&gt;RVU&lt;/i&gt;") && !p.includes("<i>RVU"));
ok(p.includes('href="https://example.test/rvu"'));
});
test("payment: the payment chart is a final line with proposed rings", () => {
const c = payment.payChart(P.rows, "99341");
ok(c.includes("<path") && c.includes('fill="none"') && c.includes("var(--s-prop)") && c.includes("<svg"));
ok(c.includes("99341 · CY2027 proposed"));
ok(payment.payChart(P.rows, "99999").includes("No RVU-based payment for 99999"));
const unpaid = P.rows.map((r) => ({ ...r, status: "B", pay_nf: null }));
ok(payment.payChart(unpaid, "99341").includes("status B"));
ok(!payment.payChart(P.rows, '<x>').includes("<x>"));
});
test("payment: the volume chart bars one year each", () => {
const v = payment.volChart(P.utilization, "99341");
eq(count(v, "services\""), 2);
ok(v.includes("<svg") && v.includes("99341 · 2023 · 600 services"));
ok(payment.volChart(P.utilization, "99343").includes("No national utilization rows for 99343"));
});
test("payment: the selected code drives the charts", () => {
ok(page().includes("99341: national non-facility payment"), "default is the first active code");
const p = page("/payment?family=HOME-VISITS#code=99343");
ok(p.includes("99343: national non-facility payment") && p.includes("99343: Medicare allowed services"));
ok(/<tr[^>]*data-code="99343"[^>]*class="sel"|<tr[^>]*class="sel"[^>]*data-code="99343"/.test(p));
});
test("payment: no payment rows is a plain message", () => {
const p = page("/payment?family=HOME-VISITS", { ...P, rows: [], cells: {}, unplaced: [], utilization: [], years: [], code_groups: { active: [], deleted: [], linked: [] } });
ok(p.includes("No payment rows"));
});