Member Billing Tracker: the code

Back to the project

Written with Claude Code to my rules. I directed and checked it; I didn't write it. All data is fake.

Code.gs

The Apps Script: a Front desk menu and the 8am fix list email.

/**
 * Member Billing Tracker: Apps Script.
 * All the checks are formulas in the sheet. This script only adds a menu and emails the
 * Fix List to the front desk each morning.
 *
 * Setup: in the Google Sheet, open Extensions > Apps Script, paste this file, save,
 * reload the sheet, then use the "Front desk" menu.
 */

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('Front desk')
    .addItem("Email me today's fix list", 'emailFixList')
    .addItem('Send the fix list every morning', 'turnOnDailyEmail')
    .addToUi();
}

/** Reads the Fix List tab and returns one object per problem. */
function readFixList(sheet) {
  const values = sheet.getRange(5, 1, sheet.getLastRow() - 4, 7).getValues();
  return values
    .filter(r => r[2] !== '')
    .map(r => ({ action: r[0], name: r[1], memberId: r[2], phone: r[3], why: r[4], amount: r[5], ref: r[6] }));
}

/** Builds the plain email text. Kept separate so it can be tested outside Google. */
function buildFixListEmail(items, dateText) {
  if (items.length === 0) {
    return { subject: 'Fix list for ' + dateText + ': nothing to fix', body: 'Nothing on the fix list today.' };
  }
  const lines = items.map((it, i) =>
    (i + 1) + '. ' + it.action + ': ' + it.name + ' (' + it.memberId + ', ' + it.phone + '). ' + it.why + '. $' + it.amount + ' [' + it.ref + ']');
  return {
    subject: 'Fix list for ' + dateText + ': ' + items.length + (items.length === 1 ? ' thing' : ' things') + ' to fix',
    body: 'Good morning! Here is today\'s fix list.\n\n' + lines.join('\n') +
      '\n\nLook members up by ID, never by name. Two members can have the same name.'
  };
}

function emailFixList() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const items = readFixList(ss.getSheetByName('Fix List'));
  const dateText = Utilities.formatDate(new Date(), ss.getSpreadsheetTimeZone(), 'MMM d, yyyy');
  const msg = buildFixListEmail(items, dateText);
  MailApp.sendEmail(Session.getActiveUser().getEmail(), msg.subject, msg.body);
}

/** Creates one daily trigger at about 8am, replacing any earlier one. */
function turnOnDailyEmail() {
  ScriptApp.getProjectTriggers()
    .filter(t => t.getHandlerFunction() === 'emailFixList')
    .forEach(t => ScriptApp.deleteTrigger(t));
  ScriptApp.newTrigger('emailFixList').timeBased().everyDays(1).atHour(8).create();
  SpreadsheetApp.getUi().alert('Done. The fix list will be emailed to you every morning around 8am.');
}

if (typeof module !== 'undefined') module.exports = { readFixList, buildFixListEmail, emailFixList, turnOnDailyEmail };

build.py

Builds the sheet: fake members and payments, the planted mistakes, and every formula.

"""Member Billing Tracker: builds the workbook (fake data + formulas) and the answer key.

Every check is a visible spreadsheet formula. Every lookup uses the member ID, never the name.
Tabs: Fix List (first), Payments, Refunds, Members.
Output: member-billing.xlsx (upload to Google Drive to turn it into a Google Sheet) and answer_key.json.
"""
import json, datetime as dt, random
from openpyxl import Workbook
from openpyxl.styles import Font, PatternFill, Alignment
from openpyxl.formatting.rule import FormulaRule

random.seed(7)
D = dt.date
PLANS = {"Tennis": 189, "Social": 95, "Family": 260}
FIRST = ["Ava", "Ben", "Carla", "Dev", "Ella", "Felix", "Gina", "Hank", "Iris", "Jake", "Kira", "Leo", "Mia",
         "Nate", "Olive", "Paul", "Quinn", "Rosa", "Sam", "Tara", "Uma", "Vic", "Wes", "Xena", "Yara", "Zack",
         "Amir", "Bea", "Cole", "Dana", "Eli", "Faye", "Gus", "Hana", "Ivan", "Jules"]
LAST = ["Ortiz", "Nguyen", "Patel", "Brooks", "Kim", "Reyes", "Hale", "Moreno", "Sato", "Price", "Lund", "Vega",
        "Shaw", "Diaz", "Fox", "Grant", "Hayes", "Iqbal", "Jensen", "Klein", "Lowe", "Mendez", "Novak", "Olsen",
        "Park", "Quint", "Ruiz", "Stone", "Tran", "Udall", "Voss", "West", "Young", "Zane", "Abbott", "Banks"]

# Plain labels used in the sheet (and in the answer key).
DISPUTE, DECLINED = "Member disputed this charge", "Card declined, not retried"
PAUSED, CANCELLED = "Charged after they paused", "Charged after they cancelled"
TWICE, WRONG_CARD = "Charged twice this month", "Paid with another member's card"
NOT_SENT = "Refund approved, never sent"

# ---- Members -------------------------------------------------------------------------------
members = []
cards = random.sample(range(1000, 9999), 36)
for i in range(36):
    plan = random.choice(list(PLANS))
    members.append(dict(id=f"M-{1001 + i}", name=f"{FIRST[i]} {LAST[i]}", dues=PLANS[plan],
                        card=f"Visa {cards[i]}", status="Active", since=D(2025, 1, 1),
                        phone=f"(661) 555-01{i:02d}"))
M = {m["id"]: m for m in members}
# Same-name pair: two different members, both named Chris Morgan.
M["M-1012"].update(name="Chris Morgan", dues=189)
M["M-1031"].update(name="Chris Morgan", dues=95, status="Paused", since=D(2026, 9, 20))
M["M-1015"].update(status="Paused", since=D(2026, 9, 15))
M["M-1030"].update(status="Cancelled", since=D(2026, 8, 20))
M["M-1033"].update(status="Paused", since=D(2026, 9, 10))   # clean case: billing stopped correctly

# ---- Payments ------------------------------------------------------------------------------
pay = []
def add(date, mid, kind, amount, result="Paid", disputed="", card=None):
    pay.append(dict(date=date, mid=mid, type=kind, period=f"{date:%Y-%m}", amount=amount,
                    card=card or M[mid]["card"], result=result, disputed=disputed))

failed_unretried = {("M-1004", 10), ("M-1011", 10), ("M-1019", 9), ("M-1027", 10)}
failed_retried = {("M-1008", 9, 4), ("M-1023", 10, 5)}     # clean cases: retried and paid
for month in (8, 9, 10):
    for m in members:
        mid = m["id"]
        if m["status"] != "Active" and D(2026, month, 1) >= m["since"]:
            if not ((mid == "M-1015" and month == 10) or (mid == "M-1030" and month in (9, 10))
                    or (mid == "M-1031" and month == 10)):
                continue
        if mid == "M-1018" and month == 10:
            continue  # M-1018's October payment got put on M-1017's account (below)
        if (mid, month) in failed_unretried:
            add(D(2026, month, 1), mid, "Dues", m["dues"], result="Declined"); continue
        r = [x for x in failed_retried if x[:2] == (mid, month)]
        if r:
            add(D(2026, month, 1), mid, "Dues", m["dues"], result="Declined")
            add(D(2026, month, r[0][2]), mid, "Dues", m["dues"]); continue
        add(D(2026, month, 1), mid, "Dues", m["dues"])

add(D(2026, 9, 2), "M-1006", "Dues", M["M-1006"]["dues"])                 # charged twice
add(D(2026, 10, 2), "M-1021", "Dues", M["M-1021"]["dues"])                # charged twice
add(D(2026, 10, 3), "M-1017", "Dues", M["M-1018"]["dues"], card=M["M-1018"]["card"])  # wrong account
for p in pay:
    if (p["mid"], p["period"]) in {("M-1013", "2026-08"), ("M-1025", "2026-10")}:
        p["disputed"] = "Yes"
add(D(2026, 10, 12), "M-1003", "Refund", 189, result="Refunded")
add(D(2026, 10, 20), "M-1012", "Refund", 95, result="Refunded")   # the OTHER Chris Morgan's $95 refund
pay.sort(key=lambda p: (p["date"], p["mid"]))
for i, p in enumerate(pay):
    p["txn"] = f"T-{2001 + i}"

refunds = [
    dict(req="R-01", date=D(2026, 10, 10), mid="M-1003", amount=189, reason="Billed during a medical freeze"),
    dict(req="R-02", date=D(2026, 10, 18), mid="M-1012", amount=95, reason="Guest fees charged by mistake"),
    dict(req="R-03", date=D(2026, 10, 22), mid="M-1009", amount=260, reason="Court booking cancelled by club"),
    dict(req="R-04", date=D(2026, 10, 5), mid="M-1031", amount=95, reason="Unused guest passes"),
]

# ---- Answer key (written from the plan above, not from the formulas) -----------------------
def txn(mid, date):
    return next(p["txn"] for p in pay if p["mid"] == mid and p["date"] == date and p["type"] == "Dues")
key = {txn(mid, D(2026, mo, 1)): DECLINED for mid, mo in failed_unretried}
key[txn("M-1015", D(2026, 10, 1))] = PAUSED
key[txn("M-1031", D(2026, 10, 1))] = PAUSED
key[txn("M-1030", D(2026, 9, 1))] = CANCELLED
key[txn("M-1030", D(2026, 10, 1))] = CANCELLED
key[txn("M-1006", D(2026, 9, 2))] = TWICE
key[txn("M-1021", D(2026, 10, 2))] = TWICE
key[txn("M-1017", D(2026, 10, 3))] = WRONG_CARD
key[txn("M-1013", D(2026, 8, 1))] = DISPUTE
key[txn("M-1025", D(2026, 10, 1))] = DISPUTE
key["R-03"] = NOT_SENT
key["R-04"] = NOT_SENT
ACTION = {DISPUTE: "Call", DECLINED: "Retry card", PAUSED: "Refund", CANCELLED: "Refund", TWICE: "Refund",
          WRONG_CARD: "Move payment", NOT_SENT: "Send refund"}

# ---- Workbook -----------------------------------------------------------------------------
HEAD, HFILL = Font(bold=True, color="FFFFFF"), PatternFill("solid", fgColor="4C1D95")
def header(ws, row, cols, widths):
    for i, (c, w) in enumerate(zip(cols, widths), 1):
        cell = ws.cell(row=row, column=i, value=c)
        cell.font, cell.fill = HEAD, HFILL
        ws.column_dimensions[cell.column_letter].width = w
    ws.freeze_panes = ws.cell(row=row + 1, column=1)

def put(ws, r, values):
    for c, v in enumerate(values, 1):
        ws.cell(row=r, column=c, value=v)

wb = Workbook()
ws = wb.active; ws.title = "Fix List"
wp = wb.create_sheet("Payments"); wr = wb.create_sheet("Refunds"); wm = wb.create_sheet("Members")

# Members: A ID, B Name, C Monthly dues, D Card on file, E Status, F Since, G Phone
header(wm, 1, ["Member ID", "Name", "Monthly dues", "Card on file", "Status", "Since", "Phone"],
       [11, 18, 13, 13, 11, 13, 16])
for i, m in enumerate(members):
    put(wm, i + 2, [m["id"], m["name"], m["dues"], m["card"], m["status"], m["since"], m["phone"]])
for r in range(2, len(members) + 2):
    wm[f"C{r}"].number_format = "$#,##0"; wm[f"F{r}"].number_format = "mmm d, yyyy"

NP = len(pay) + 1
mem = lambda col, r, key="$C": f"INDEX(Members!${col}$2:${col}$200,MATCH({key}{r},Members!$A$2:$A$200,0))"
# Payments: A Payment #, B Date, C Member ID, D Name, E Kind, F Month, G Amount, H Card used,
#           I Result, J Disputed?, K Problem, L List #
header(wp, 1, ["Payment #", "Date", "Member ID", "Name", "Kind", "Month", "Amount", "Card used", "Result",
               "Disputed?", "Problem", "List #"], [10, 12, 11, 18, 8, 9, 9, 11, 10, 10, 30, 7])
for i, p in enumerate(pay):
    r = i + 2
    card, status, since = mem("D", r), mem("E", r), mem("F", r)
    paid_dues = f'$E{r}="Dues",$I{r}="Paid"'
    problem = (
        f'=IF($J{r}="Yes","{DISPUTE}",'
        f'IF(AND({paid_dues},$H{r}<>{card}),"{WRONG_CARD}",'
        f'IF(AND({paid_dues},{status}<>"Active",$B{r}>={since}),'
        f'IF({status}="Paused","{PAUSED}","{CANCELLED}"),'
        f'IF(AND({paid_dues},COUNTIFS($C$2:$C{r},$C{r},$F$2:$F{r},$F{r},$E$2:$E{r},"Dues",'
        f'$I$2:$I{r},"Paid",$H$2:$H{r},{card})>1),"{TWICE}",'
        f'IF(AND($E{r}="Dues",$I{r}="Declined",COUNTIFS($C$2:$C${NP},$C{r},$F$2:$F${NP},$F{r},'
        f'$E$2:$E${NP},"Dues",$I$2:$I${NP},"Paid")=0),"{DECLINED}","")))))').replace("'", "'")
    put(wp, r, [p["txn"], p["date"], p["mid"], f'=IFERROR({mem("B", r)},"Unknown ID")', p["type"], p["period"],
               p["amount"], p["card"], p["result"], p["disputed"], problem,
               f'=IF($K{r}="","",COUNTIF($K$2:$K{r},"?*"))'])
    wp[f"B{r}"].number_format = "mmm d, yyyy"; wp[f"G{r}"].number_format = "$#,##0"
wp.conditional_formatting.add(f"A2:L{NP}", FormulaRule(formula=['$K2<>""'], fill=PatternFill("solid", fgColor="FDE2E2")))

NR = len(refunds) + 1
# Refunds: A Request #, B Approved, C Member ID, D Name, E Amount, F Reason, G Sent?, H Problem, I List #
header(wr, 1, ["Request #", "Approved", "Member ID", "Name", "Amount", "Reason", "Sent?", "Problem", "List #"],
       [10, 13, 11, 18, 9, 32, 7, 28, 7])
for i, q in enumerate(refunds):
    r = i + 2
    sent = (f'=IF(COUNTIFS(Payments!$C$2:$C${NP},$C{r},Payments!$E$2:$E${NP},"Refund",'
            f'Payments!$G$2:$G${NP},$E{r},Payments!$B$2:$B${NP},">="&$B{r})>0,"Yes","No")')
    put(wr, r, [q["req"], q["date"], q["mid"], f'=IFERROR({mem("B", r)},"Unknown ID")', q["amount"], q["reason"], sent,
               f'=IF($G{r}="No","{NOT_SENT}","")',
               f'=IF($H{r}="","",COUNTIF(Payments!$K$2:$K${NP},"?*")+COUNTIF($H$2:$H{r},"?*"))'])
    wr[f"B{r}"].number_format = "mmm d, yyyy"; wr[f"E{r}"].number_format = "$#,##0"
wr.conditional_formatting.add(f"A2:I{NR}", FormulaRule(formula=['$H2<>""'], fill=PatternFill("solid", fgColor="FDE2E2")))

# Fix List: one row per problem, pulled from Payments then Refunds by List #.
ws["A1"] = "Today's fix list"; ws["A1"].font = Font(bold=True, size=14)
P = f'COUNTIF(Payments!$K$2:$K${NP},"?*")'
T = f'({P}+COUNTIF(Refunds!$H$2:$H${NR},"?*"))'
ws["A2"] = f'={T}&" things to fix. Look members up by ID, never by name."'
# A Do this, B Member, C Member ID, D Phone, E Why, F Amount, G Find it
header(ws, 4, ["Do this", "Member", "Member ID", "Phone", "Why", "Amount", "Find it"], [14, 18, 11, 16, 34, 9, 9])
def pick(pcol, rcol, r):
    k = f"(ROW()-4)"
    return (f'IF({k}<={P},INDEX(Payments!${pcol}$2:${pcol}${NP},MATCH({k},Payments!$L$2:$L${NP},0)),'
            f'INDEX(Refunds!${rcol}$2:${rcol}${NR},MATCH({k},Refunds!$I$2:$I${NR},0)))')
for r in range(5, 45):
    why = f'IF($C{r}="","",{pick("K", "H", r)})'
    put(ws, r, [
        f'=IF($E{r}="","",IF($E{r}="{DISPUTE}","Call",IF($E{r}="{DECLINED}","Retry card",'
        f'IF(LEFT($E{r},31)="{WRONG_CARD}","Move payment",IF($E{r}="{NOT_SENT}","Send refund","Refund")))))',
        f'=IF($C{r}="","",{mem("B", r, "$C")})',
        f'=IF(ROW()-4>{T},"",{pick("C", "C", r)})',
        f'=IF($C{r}="","",{mem("G", r, "$C")})',
        f'=IF($C{r}="","",IF({pick("K", "H", r)}="{WRONG_CARD}","{WRONG_CARD} ("&'
        f'IFERROR(INDEX(Members!$A$2:$A$200,MATCH({pick("H", "C", r)},Members!$D$2:$D$200,0)),"check")&")",'
        f'{pick("K", "H", r)}))',
        f'=IF($C{r}="","",{pick("G", "E", r)})',
        f'=IF($C{r}="","",{pick("A", "A", r)})'])
    ws[f"F{r}"].number_format = "$#,##0"
    ws[f"A{r}"].font = Font(bold=True)
COLORS = {"Call": "EDE9FE", "Retry card": "FEF3C7", "Refund": "FCE7F3", "Send refund": "FCE7F3", "Move payment": "DBEAFE"}
for label, color in COLORS.items():
    ws.conditional_formatting.add("A5:A44", FormulaRule(formula=[f'$A5="{label}"'], fill=PatternFill("solid", fgColor=color)))
ws.freeze_panes = "A5"

wb.save("/home/user/finances/member-billing/member-billing.xlsx")
json.dump({"answer_key": key, "actions": ACTION,
           "members": {m["id"]: {k: (str(v) if isinstance(v, D) else v) for k, v in m.items()} for m in members},
           "payments": [{k: (str(v) if isinstance(v, D) else v) for k, v in p.items()} for p in pay],
           "refunds": [{k: (str(v) if isinstance(v, D) else v) for k, v in q.items()} for q in refunds]},
          open("/home/user/finances/member-billing/answer_key.json", "w"), indent=1)
print(len(members), "members,", len(pay), "payments,", len(refunds), "refund requests,", len(key), "planted problems")

test_tracker.py

Checks the results against the planted mistakes, a separate copy of the rules, and the same-name tests.

"""Tests for the Member Billing Tracker.

  python3 test_tracker.py                  # answer key vs a separate Python version of the rules
  python3 test_tracker.py results.xlsx     # also check a spreadsheet engine's computed values
                                           # (LibreOffice recalc, or a Google Sheets export)
"""
import json, sys, collections
from openpyxl import load_workbook

data = json.load(open("/home/user/finances/member-billing/answer_key.json"))
KEY, MEM, PAY, REF = data["answer_key"], data["members"], data["payments"], data["refunds"]
ACTION = data["actions"]
import build_labels as L
fails = []
def check(name, ok, detail=""):
    print(("PASS " if ok else "FAIL ") + name + (f"  ({detail})" if detail and not ok else ""))
    if not ok: fails.append(name)

# ---- A separate version of the rules, written in Python -----------------------------------
def rules(by):
    """by='id' looks members up by ID (the real rule). by='name' looks them up by name, first match."""
    first_by_name = {}
    for m in MEM.values(): first_by_name.setdefault(m["name"], m)
    who = (lambda p: MEM[p["mid"]]) if by == "id" else (lambda p: first_by_name[MEM[p["mid"]]["name"]])
    same = (lambda a, b: a["mid"] == b["mid"]) if by == "id" else \
           (lambda a, b: MEM[a["mid"]]["name"] == MEM[b["mid"]]["name"])
    out, seen = {}, collections.Counter()
    for p in PAY:
        m = who(p); dues_paid = p["type"] == "Dues" and p["result"] == "Paid"
        if dues_paid and p["card"] == m["card"]:
            seen[(m["id"], p["period"])] += 1
        if p["disputed"] == "Yes": out[p["txn"]] = L.DISPUTE
        elif dues_paid and p["card"] != m["card"]: out[p["txn"]] = L.WRONG_CARD
        elif dues_paid and m["status"] != "Active" and p["date"] >= m["since"]:
            out[p["txn"]] = L.PAUSED if m["status"] == "Paused" else L.CANCELLED
        elif dues_paid and p["card"] == m["card"] and seen[(m["id"], p["period"])] > 1:
            out[p["txn"]] = L.TWICE
        elif p["type"] == "Dues" and p["result"] == "Declined" and not any(
                same(q, p) and q["period"] == p["period"] and q["type"] == "Dues" and q["result"] == "Paid" for q in PAY):
            out[p["txn"]] = L.DECLINED
    for q in REF:
        sent = any(same(p, q) and p["type"] == "Refund" and p["amount"] == q["amount"] and p["date"] >= q["date"] for p in PAY)
        if not sent: out[q["req"]] = L.NOT_SENT
    return out

def compare(label, got):
    caught = {k for k in KEY if got.get(k) == KEY[k]}
    wrong_label = {k for k in KEY if k in got and got[k] != KEY[k]}
    missed = set(KEY) - set(got)
    extra = set(got) - set(KEY)
    print(f"  {label}: caught {len(caught)} of {len(KEY)} planted, missed {len(missed)}, "
          f"wrong label {len(wrong_label)}, false flags {len(extra)}")
    return caught, missed, wrong_label, extra

def same_name_tests(label, got):
    a = next(p["txn"] for p in PAY if p["mid"] == "M-1012" and p["period"] == "2026-10" and p["type"] == "Dues")
    b = next(p["txn"] for p in PAY if p["mid"] == "M-1031" and p["period"] == "2026-10" and p["type"] == "Dues")
    check(f"{label} same-name 1: active Chris Morgan (M-1012) October charge is not flagged", a not in got)
    check(f"{label} same-name 2: paused Chris Morgan (M-1031) October charge is flagged", got.get(b) == L.PAUSED)
    check(f"{label} same-name 3: M-1031's refund is still owed even though M-1012 got a $95 refund",
          got.get("R-04") == L.NOT_SENT)
    check(f"{label} same-name 4: M-1012's refund counts as sent", "R-02" not in got)
    m31 = [p["txn"] for p in PAY if p["mid"] == "M-1031" and p["period"] != "2026-10"]
    check(f"{label} same-name 5: M-1031's earlier charges are not flagged as another member's card",
          all(t not in got for t in m31))

print("1. Answer key vs the Python version of the rules (lookups by member ID)")
by_id = rules("id")
c, mi, wl, ex = compare("by ID", by_id)
check("python: every planted problem caught with the right label", len(c) == len(KEY))
check("python: no false flags", not ex, ex)
same_name_tests("python", by_id)

print("\n2. What goes wrong if you look members up by name instead (for comparison only)")
by_name = rules("name")
c, mi, wl, ex = compare("by name", by_name)
print("  missed:", sorted(mi), " false flags:", sorted(ex))

if len(sys.argv) > 1:
    path = sys.argv[1]
    print(f"\n3. Spreadsheet results from {path}")
    wb = load_workbook(path, data_only=True)
    got = {}
    for row in wb["Payments"].iter_rows(min_row=2, values_only=True):
        if row[0] and row[10]: got[row[0]] = row[10]
    for row in wb["Refunds"].iter_rows(min_row=2, values_only=True):
        if row[0] and row[7]: got[row[0]] = row[7]
    c, mi, wl, ex = compare("sheet", got)
    check("sheet: every planted problem caught with the right label", len(c) == len(KEY), sorted(mi | wl))
    check("sheet: no false flags", not ex, sorted(ex))
    check("sheet: matches the Python version row for row", got == by_id)
    same_name_tests("sheet", got)
    fl = [r for r in wb["Fix List"].iter_rows(min_row=5, values_only=True) if r[1]]
    check("sheet: fix list has one row per problem", len(fl) == len(KEY), len(fl))
    refs = {r[6]: r for r in fl}
    check("sheet: fix list covers every planted problem", set(refs) == set(KEY), set(KEY) ^ set(refs))
    check("sheet: fix list names and phones come from the member ID",
          all(r[1] == MEM[r[2]]["name"] and r[3] == MEM[r[2]]["phone"] for r in fl))
    check("sheet: every fix list row has the right action (Call, Refund, Retry card...)",
          all(r[0] == ACTION[KEY[r[6]]] for r in fl), [(r[0], r[6]) for r in fl if r[0] != ACTION[KEY[r[6]]]])
    check("sheet: Fix List is the first tab", wb.sheetnames[0] == "Fix List", wb.sheetnames)
    wa = next(r for r in fl if r[0] == "Move payment")
    check("sheet: wrong-account row points to M-1018", wa[4] == L.WRONG_CARD + " (M-1018)", wa[4])
    print("  header line:", wb["Fix List"]["A2"].value)
    print("  sample fix list rows:")
    for r in fl[:15]: print("   ", r)

print("\nRESULT:", "all passed" if not fails else f"{len(fails)} failed: {fails}")
sys.exit(1 if fails else 0)

test_script.js

Tests the Apps Script with stand-ins for Google.

// Tests Code.gs outside Google with simple stand-ins for SpreadsheetApp, MailApp and ScriptApp.
// Reads the fix list rows from a spreadsheet engine's results (exported as JSON by the caller).
const assert = require('assert');
const fs = require('fs');
const rows = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); // Fix List rows from row 5 down
let sent = [], triggers = [], alerts = [];
global.SpreadsheetApp = {
  getActiveSpreadsheet: () => ({
    getSheetByName: () => ({ getLastRow: () => rows.length + 4, getRange: () => ({ getValues: () => rows }) }),
    getSpreadsheetTimeZone: () => 'America/Los_Angeles'
  }),
  getUi: () => ({ alert: m => alerts.push(m) })
};
global.Utilities = { formatDate: () => 'Oct 31, 2026' };
global.Session = { getActiveUser: () => ({ getEmail: () => 'frontdesk@example.com' }) };
global.MailApp = { sendEmail: (to, subject, body) => sent.push({ to, subject, body }) };
const mk = name => ({ getHandlerFunction: () => name });
global.ScriptApp = {
  getProjectTriggers: () => triggers,
  deleteTrigger: t => { triggers = triggers.filter(x => x !== t); },
  newTrigger: name => ({ timeBased: () => ({ everyDays: d => ({ atHour: h => ({ create: () => triggers.push(Object.assign(mk(name), { d, h })) }) }) }) })
};
const S = require('./Code.gs.js');
let n = 0; const ok = (c, m) => { assert(c, m); n++; console.log('PASS ' + m); };

S.emailFixList();
const filled = rows.filter(r => r[2] !== '').length;
ok(sent.length === 1, 'sends exactly one email');
ok(sent[0].subject === `Fix list for Oct 31, 2026: ${filled} things to fix`, 'subject has the count: ' + sent[0].subject);
ok(sent[0].body.split('\n').filter(l => /^\d+\. /.test(l)).length === filled, 'one line per problem');
ok(sent[0].body.includes('Chris Morgan (M-1031'), 'same-name member is listed with their ID');
ok(/^\d+\. (Call|Refund|Retry card|Move payment|Send refund): /m.test(sent[0].body), 'each line starts with what to do');
ok(!/Chris Morgan \(M-1012/.test(sent[0].body), 'the other Chris Morgan (M-1012) is not on the list');
ok(S.buildFixListEmail([], 'Nov 1, 2026').subject.endsWith('nothing to fix'), 'empty list gets a clear subject');
triggers = [mk('emailFixList'), mk('somethingElse')];
S.turnOnDailyEmail(); S.turnOnDailyEmail();
ok(triggers.filter(t => t.getHandlerFunction() === 'emailFixList').length === 1, 'turning it on twice leaves one daily trigger');
ok(triggers.some(t => t.getHandlerFunction() === 'somethingElse'), 'other triggers are left alone');
ok(triggers.find(t => t.getHandlerFunction() === 'emailFixList').h === 8, 'trigger runs at 8am');
console.log(`\n${n} script checks passed\n--- sample email ---\n${sent[0].subject}\n${sent[0].body}`);

test-results.txt

The latest test run: LibreOffice, Google Sheets and the Apps Script.

# Test run 2026-11-10

## Formulas recalculated by LibreOffice
1. Answer key vs the Python version of the rules (lookups by member ID)
  by ID: caught 15 of 15 planted, missed 0, wrong label 0, false flags 0
PASS python: every planted problem caught with the right label
PASS python: no false flags
PASS python same-name 1: active Chris Morgan (M-1012) October charge is not flagged
PASS python same-name 2: paused Chris Morgan (M-1031) October charge is flagged
PASS python same-name 3: M-1031's refund is still owed even though M-1012 got a $95 refund
PASS python same-name 4: M-1012's refund counts as sent
PASS python same-name 5: M-1031's earlier charges are not flagged as another member's card

2. What goes wrong if you look members up by name instead (for comparison only)
  by name: caught 13 of 15 planted, missed 1, wrong label 1, false flags 2
  missed: ['R-04']  false flags: ['T-2031', 'T-2067']

3. Spreadsheet results from out/member-billing.xlsx
  sheet: caught 15 of 15 planted, missed 0, wrong label 0, false flags 0
PASS sheet: every planted problem caught with the right label
PASS sheet: no false flags
PASS sheet: matches the Python version row for row
PASS sheet same-name 1: active Chris Morgan (M-1012) October charge is not flagged
PASS sheet same-name 2: paused Chris Morgan (M-1031) October charge is flagged
PASS sheet same-name 3: M-1031's refund is still owed even though M-1012 got a $95 refund
PASS sheet same-name 4: M-1012's refund counts as sent
PASS sheet same-name 5: M-1031's earlier charges are not flagged as another member's card
PASS sheet: fix list has one row per problem
PASS sheet: fix list covers every planted problem
PASS sheet: fix list names and phones come from the member ID
PASS sheet: every fix list row has the right action (Call, Refund, Retry card...)
PASS sheet: Fix List is the first tab
PASS sheet: wrong-account row points to M-1018
  header line: 15 things to fix. Look members up by ID, never by name.
  sample fix list rows:
    ('Call', 'Mia Shaw', 'M-1013', '(661) 555-0112', 'Member disputed this charge', 189, 'T-2013')
    ('Retry card', 'Sam Jensen', 'M-1019', '(661) 555-0118', 'Card declined, not retried', 95, 'T-2055')
    ('Refund', 'Dana Udall', 'M-1030', '(661) 555-0129', 'Charged after they cancelled', 95, 'T-2066')
    ('Refund', 'Felix Reyes', 'M-1006', '(661) 555-0105', 'Charged twice this month', 189, 'T-2073')
    ('Retry card', 'Dev Brooks', 'M-1004', '(661) 555-0103', 'Card declined, not retried', 189, 'T-2078')
    ('Retry card', 'Kira Lund', 'M-1011', '(661) 555-0110', 'Card declined, not retried', 189, 'T-2085')
    ('Refund', 'Olive Fox', 'M-1015', '(661) 555-0114', 'Charged after they paused', 260, 'T-2089')
    ('Call', 'Yara Park', 'M-1025', '(661) 555-0124', 'Member disputed this charge', 189, 'T-2098')
    ('Retry card', 'Amir Ruiz', 'M-1027', '(661) 555-0126', 'Card declined, not retried', 189, 'T-2100')
    ('Refund', 'Dana Udall', 'M-1030', '(661) 555-0129', 'Charged after they cancelled', 95, 'T-2103')
    ('Refund', 'Chris Morgan', 'M-1031', '(661) 555-0130', 'Charged after they paused', 95, 'T-2104')
    ('Refund', 'Uma Lowe', 'M-1021', '(661) 555-0120', 'Charged twice this month', 95, 'T-2109')
    ('Move payment', 'Quinn Hayes', 'M-1017', '(661) 555-0116', "Paid with another member's card (M-1018)", 95, 'T-2110')
    ('Send refund', 'Iris Sato', 'M-1009', '(661) 555-0108', 'Refund approved, never sent', 260, 'R-03')
    ('Send refund', 'Chris Morgan', 'M-1031', '(661) 555-0130', 'Refund approved, never sent', 95, 'R-04')

RESULT: all passed

## Formulas recalculated by Google Sheets (file converted in Google Drive, then exported)
3. Spreadsheet results from out/google-sheets-export.xlsx
  sheet: caught 15 of 15 planted, missed 0, wrong label 0, false flags 0
PASS sheet: every planted problem caught with the right label
PASS sheet: no false flags
PASS sheet: matches the Python version row for row
PASS sheet same-name 1: active Chris Morgan (M-1012) October charge is not flagged
PASS sheet same-name 2: paused Chris Morgan (M-1031) October charge is flagged
PASS sheet same-name 3: M-1031's refund is still owed even though M-1012 got a $95 refund
PASS sheet same-name 4: M-1012's refund counts as sent
PASS sheet same-name 5: M-1031's earlier charges are not flagged as another member's card
PASS sheet: fix list has one row per problem
PASS sheet: fix list covers every planted problem
PASS sheet: fix list names and phones come from the member ID
PASS sheet: every fix list row has the right action (Call, Refund, Retry card...)
PASS sheet: Fix List is the first tab
PASS sheet: wrong-account row points to M-1018
  header line: 15 things to fix. Look members up by ID, never by name.
  sample fix list rows:
    ('Call', 'Mia Shaw', 'M-1013', '(661) 555-0112', 'Member disputed this charge', 189, 'T-2013')
    ('Retry card', 'Sam Jensen', 'M-1019', '(661) 555-0118', 'Card declined, not retried', 95, 'T-2055')
    ('Refund', 'Dana Udall', 'M-1030', '(661) 555-0129', 'Charged after they cancelled', 95, 'T-2066')
    ('Refund', 'Felix Reyes', 'M-1006', '(661) 555-0105', 'Charged twice this month', 189, 'T-2073')
    ('Retry card', 'Dev Brooks', 'M-1004', '(661) 555-0103', 'Card declined, not retried', 189, 'T-2078')
    ('Retry card', 'Kira Lund', 'M-1011', '(661) 555-0110', 'Card declined, not retried', 189, 'T-2085')
    ('Refund', 'Olive Fox', 'M-1015', '(661) 555-0114', 'Charged after they paused', 260, 'T-2089')
    ('Call', 'Yara Park', 'M-1025', '(661) 555-0124', 'Member disputed this charge', 189, 'T-2098')
    ('Retry card', 'Amir Ruiz', 'M-1027', '(661) 555-0126', 'Card declined, not retried', 189, 'T-2100')
    ('Refund', 'Dana Udall', 'M-1030', '(661) 555-0129', 'Charged after they cancelled', 95, 'T-2103')
    ('Refund', 'Chris Morgan', 'M-1031', '(661) 555-0130', 'Charged after they paused', 95, 'T-2104')
    ('Refund', 'Uma Lowe', 'M-1021', '(661) 555-0120', 'Charged twice this month', 95, 'T-2109')
    ('Move payment', 'Quinn Hayes', 'M-1017', '(661) 555-0116', "Paid with another member's card (M-1018)", 95, 'T-2110')
    ('Send refund', 'Iris Sato', 'M-1009', '(661) 555-0108', 'Refund approved, never sent', 260, 'R-03')
    ('Send refund', 'Chris Morgan', 'M-1031', '(661) 555-0130', 'Refund approved, never sent', 95, 'R-04')

RESULT: all passed

## Apps Script (Code.gs) with stand-ins for Google services, using the Google Sheets fix list
PASS sends exactly one email
PASS subject has the count: Fix list for Oct 31, 2026: 15 things to fix
PASS one line per problem
PASS same-name member is listed with their ID
PASS each line starts with what to do
PASS the other Chris Morgan (M-1012) is not on the list
PASS empty list gets a clear subject
PASS turning it on twice leaves one daily trigger
PASS other triggers are left alone
PASS trigger runs at 8am

10 script checks passed