#!/usr/bin/env python3 """Regression tests for credit cycle close (issue #12). Runnable: * inside the portal app: PORTAL_CODE_DIR=/app/code python3 /tmp/test_credit_cycle_close.py * from the repo root, on a host that has the app's dependencies WHY THIS EXISTS LiteLLM zeroes a team's `spend` at budget_reset_at and leaves max_budget alone, and nothing ever reduced `credit_balance`. Result: a member who bought a $50 pack and spent it got the $50 back at the next monthly reset — the allowance returned to $65 instead of $15, forever. Covered here: - the cap is allowance + credits STILL AVAILABLE (drawn in closed cycles) - spend inside the CURRENT cycle never shrinks the cap (the inversion bug) - closing a cycle draws the overage once, and a replay draws nothing - a draw is capped by the credits actually available - the issue's worked example end-to-end """ import os import sqlite3 import sys import tempfile from datetime import datetime, timezone _TEST_DB = os.path.join(tempfile.mkdtemp(prefix="creditclose-test-"), "members.db") os.environ["DB_PATH"] = _TEST_DB # must exist BEFORE app.main is imported for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code", os.path.dirname(os.path.dirname(os.path.abspath(__file__)))): if _cand and os.path.isfile(os.path.join(_cand, "app", "main.py")): sys.path.insert(0, _cand) break from app.main import ( # noqa: E402 _prev_month, apply_cycle_draw, compute_max_budget, cycle_start_for_anchor_day, get_credit_balance, get_credits_drawn, get_db, ) failures = 0 def check(name, got, want): global failures ok = got == want if not ok: failures += 1 print(f"[{'PASS' if ok else 'FAIL'}] {name}") if not ok: print(f" got {got!r}\n want {want!r}") def close(a, b): return round(float(a), 6) == round(float(b), 6) def check_near(name, got, want): global failures ok = close(got, want) if not ok: failures += 1 print(f"[{'PASS' if ok else 'FAIL'}] {name}") if not ok: print(f" got {got!r}\n want {want!r}") # --- cycle boundary math --------------------------------------------------- check("_prev_month steps back across a year boundary", _prev_month(datetime(2026, 1, 1, tzinfo=timezone.utc)).isoformat(), datetime(2025, 12, 1, tzinfo=timezone.utc).isoformat()) check("cycle_start_for_anchor_day is the last occurrence at/before now", cycle_start_for_anchor_day(28, datetime(2026, 11, 27, 12, tzinfo=timezone.utc)).isoformat(), datetime(2026, 10, 28, tzinfo=timezone.utc).isoformat()) # --- cap arithmetic -------------------------------------------------------- # allowance $15 + $50 pack, nothing drawn, fresh cycle eff = compute_max_budget(15, 50, 0.0, 0.0) check_near("fresh cycle cap = allowance + pack", eff["max_budget"], 65.0) check_near("fresh cycle credits remaining = pack", eff["credits_remaining"], 50.0) # mid-cycle spend NEVER shrinks the cap (the inversion bug) mid = compute_max_budget(15, 50, 40.0, 0.0) check_near("mid-cycle cap unchanged as credits burn", mid["max_budget"], 65.0) check_near("mid-cycle credits used derived from spend", mid["credits_used"], 25.0) check_near("mid-cycle credits remaining = pack - used", mid["credits_remaining"], 25.0) # after the cycle closes with $50 drawn after = compute_max_budget(15, 50, 0.0, 50.0) check_near("after close cap = allowance only (pack spent)", after["max_budget"], 15.0) check_near("after close credits remaining = 0", after["credits_remaining"], 0.0) # every dollar of purchased credit raises the cap by a dollar check_near("credit add raises the cap 1:1", compute_max_budget(15, 70, 0.0, 50.0)["max_budget"], 35.0) check_near("drawn beyond purchased never goes negative", compute_max_budget(15, 50, 0.0, 80.0)["max_budget"], 15.0) # --- a real (temporary) DB: apply_cycle_draw --------------------------------- conn = get_db() # runs schema + migrations conn.execute( "INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) " "VALUES ('pack@example.com', '', 1, 'member', 15.0, 50.0)" ) conn.commit() conn.close() drawn = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0) check_near("cycle draws the overage ($65 spend - $15 allowance)", drawn, 50.0) check_near("credits_drawn recorded", get_credits_drawn("pack@example.com"), 50.0) check_near("credit_balance still says total purchased", get_credit_balance("pack@example.com"), 50.0) # replay of the same cycle draws nothing again = apply_cycle_draw("pack@example.com", "2026-10-28", spend=65.0, allowance=15.0) check_near("replaying a closed cycle draws nothing", again, 0.0) check_near("credits_drawn unchanged by the replay", get_credits_drawn("pack@example.com"), 50.0) rows = sqlite3.connect(_TEST_DB).execute( "SELECT COUNT(*) FROM credit_ledger WHERE reference = ?", ("cycle-close:pack@example.com:2026-10-28",)).fetchone()[0] check("exactly ONE ledger row for the cycle", rows, 1) # the issue's reproduction: after the reset the cap is the allowance, not $65 after = compute_max_budget(15, get_credit_balance("pack@example.com"), 0.0, get_credits_drawn("pack@example.com")) check_near("issue #12: next cycle cap is $15, not $65", after["max_budget"], 15.0) # a draw cannot exceed what is left conn = get_db() conn.execute( "INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) " "VALUES ('small@example.com', '', 1, 'member', 15.0, 10.0)" ) conn.commit() conn.close() apply_cycle_draw("small@example.com", "2026-10-01", spend=100.0, allowance=15.0) check_near("draw capped by credits available", get_credits_drawn("small@example.com"), 10.0) check_near("cap after capped draw = allowance", compute_max_budget(15, 10, 0.0, 10.0)["max_budget"], 15.0) # spend under the allowance owes nothing conn = get_db() conn.execute( "INSERT INTO members (email, key_token, active, account_type, balance, credit_balance) " "VALUES ('under@example.com', '', 1, 'member', 15.0, 20.0)" ) conn.commit() conn.close() check_near("no overage, no draw", apply_cycle_draw("under@example.com", "2026-10-01", spend=9.0, allowance=15.0), 0.0) check_near("balance untouched", get_credits_drawn("under@example.com"), 0.0) print() if failures: print(f"{failures} FAILURE(S)") sys.exit(1) print("all checks passed")