diff --git a/app/main.py b/app/main.py index 2799883..cfbb7fa 100644 --- a/app/main.py +++ b/app/main.py @@ -1708,6 +1708,15 @@ def add_credits(email: str, delta: float, reason: str, reference: str | None = N "INSERT INTO credit_ledger (email, delta, reason, reference) VALUES (?, ?, ?, ?)", (email, delta, reason, reference), ) + # Keep `credits_drawn <= credit_balance`. An adjustment that lowers the pack + # below what was already drawn must not swallow FUTURE credits: a new pack + # adds headroom, while consumption beyond the reduced pack is simply + # unbacked. The ledger history itself is never rewritten. + conn.execute( + "UPDATE members SET credits_drawn = MIN(COALESCE(credits_drawn, 0), " + "MAX(0, COALESCE(credit_balance, 0))) WHERE email = ?", + (email,), + ) row = conn.execute( "SELECT credit_balance FROM members WHERE email = ?", (email,) ).fetchone() diff --git a/tests/test_credit_cycle_close.py b/tests/test_credit_cycle_close.py index e89574f..91ee3d1 100644 --- a/tests/test_credit_cycle_close.py +++ b/tests/test_credit_cycle_close.py @@ -32,8 +32,8 @@ for _cand in (os.environ.get("PORTAL_CODE_DIR"), "/app/code", 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, + _prev_month, add_credits, apply_cycle_draw, compute_max_budget, + cycle_start_for_anchor_day, get_credit_balance, get_credits_drawn, get_db, ) failures = 0 @@ -189,6 +189,15 @@ r2 = asyncio.run(m.close_credit_cycles()) check("cap applied once spend resets", applied, [15.0]) check("no second draw on the same cycle", r2["credits_drawn"], 0.0) +# --- lowering a pack below what was drawn must not swallow NEW credits ---- +add_credits("small@example.com", -10.0, reason="admin correction (test)") +check_near("drawn follows the pack down when it is reduced", get_credits_drawn("small@example.com"), 0.0) +check_near("balance reduced to zero", get_credit_balance("small@example.com"), 0.0) +add_credits("small@example.com", 5.0, reason="new pack (test)") +check_near("a new pack is fully available after the correction", + compute_max_budget(15, get_credit_balance("small@example.com"), 0.0, + get_credits_drawn("small@example.com"))["credits_remaining"], 5.0) + print() if failures: print(f"{failures} FAILURE(S)")