portal: settle held credits in the sweep, and report the ones nobody can be credited for
ci/woodpecker/push/woodpecker Pipeline was canceled

A credit pack bought while the buyer's membership was inactive is held — correctly,
we must never mint credits for a non-member. The gap was what happened next: the hold
sat until a human noticed (mmoya's $10 waited from 01:45 until they wrote in).

Every sweep now grants any hold that resolves to an ACTIVE member (by email first, then
slug), reusing grant_held_credits() so held:<id> keeps it idempotent; holds with no
active member older than HELD_ALERT_HOURS are emailed to info@. Tests cover grant/hold/
no-double-apply.
This commit is contained in:
inference-admin committed 2026-11-17 04:51:40 +00:00
1 parent 34547075cf
commit e9d0fd259a
2 files changed
+98

No files matched your search

+65
View File
@@ -9048,6 +9048,64 @@ async def admin_allowance(request: Request, mode: str = "report", to: str | None
return await reconcile_allowances(send=False)
HELD_ALERT_HOURS = float(os.environ.get("HELD_ALERT_HOURS", "6") or 6)
async def settle_held_credits(send: bool = True) -> dict:
"""Grant held credit packs that belong to members who are now active.
A pack bought while the buyer's membership was inactive is held on purpose —
this pass must never mint credits for a non-member. The gap it closes is what
happens next: those holds used to stay until an operator noticed them by hand
(a $10 pack sat from 01:45 until the member wrote in). Now every sweep grants
a hold whose buyer resolves to an ACTIVE member, and reports holds older than
HELD_ALERT_HOURS that still have nobody to credit.
"""
conn = get_db()
granted: list[dict] = []
unresolved: list[dict] = []
stale: list[dict] = []
try:
held = conn.execute(
"SELECT id, slug, email, amount, created_at FROM held_credits "
"WHERE status = 'held'").fetchall()
active = {r[0].strip().lower(): (r[1] or "") for r in
conn.execute("SELECT email, slug FROM members WHERE active = 1")}
by_slug = {(sl or "").strip().lower(): em for em, sl in active.items() if sl}
now = datetime.now(timezone.utc)
for hold_id, slug, email, amount, created_at in held:
em = (email or "").strip().lower()
target = em if em in active else by_slug.get((slug or "").strip().lower(), "")
if target:
moved = grant_held_credits(conn, target, slug or "")
if moved:
granted.append({"hold": hold_id, "email": target,
"amount": float(amount or 0)})
continue
when = _parse_ts(created_at)
age_h = ((now - when).total_seconds() / 3600.0) if when else 0.0
row = {"hold": hold_id, "email": email, "slug": slug,
"amount": float(amount or 0), "age_h": round(age_h, 1)}
unresolved.append(row)
if age_h >= HELD_ALERT_HOURS:
stale.append(row)
finally:
conn.close()
notified = False
if stale and send:
lines = "\n".join(
f"- hold #{h['hold']}: ${h['amount']:.2f} from {h['email'] or h['slug']} ({h['age_h']}h old)"
for h in stale)
notified = bool(send_email(
ADMIN_INVITER_EMAIL,
f"{len(stale)} unapplied credit pack(s) waiting",
"These credit packs are held with no active member to credit:\n\n" + lines +
"\n\nGrant one at POST /admin/held-credits/<id>/grant {\"email\": \"...\"}, "
"or link the buyer to a member account.\n"))
return {"held": len(held), "granted": granted, "unresolved": unresolved,
"stale": stale, "notified": notified}
@app.post("/admin/sweep")
@limiter.limit("20/minute")
async def admin_sweep(request: Request):
@@ -9094,6 +9152,13 @@ async def admin_sweep(request: Request):
except Exception as exc: # noqa: BLE001
result["credit_reconcile"] = {"error": str(exc)[:200]}
# Held credit packs: grant any whose buyer is now an active member, and report
# the ones nobody can be credited for. Wrapped so it can never break the sweep.
try:
result["held_credits"] = await settle_held_credits(send=True)
except Exception as exc: # noqa: BLE001
result["held_credits"] = {"error": str(exc)[:200]}
# Paid Open Collective contributors with no portal row — the net for members
# the sweep cannot see (hidden email, org account). Emails info@ only when it
# finds something, and only when the set changes. Was a daily script on the
+33
View File
@@ -0,0 +1,33 @@
import asyncio, os, sys, tempfile
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "settle.db")
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import app.main as m
m.DB_PATH = os.environ["DB_PATH"]
def seed():
conn = m.get_db()
for email, slug, active, credits in (
("active@example.org", "active-slug", 1, 0.0),
("inactive@example.org", "inactive-slug", 0, 0.0),
):
conn.execute("INSERT OR REPLACE INTO members (email, slug, active, credit_balance) VALUES (?,?,?,?)",
(email, slug, active, credits))
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
("active-slug", "active@example.org", "A", 10.0, "oc:active-slug:xyz"))
conn.execute("INSERT INTO held_credits (slug, email, name, amount, oc_reference) VALUES (?,?,?,?,?)",
("inactive-slug", "inactive@example.org", "I", 5.0, "oc:inactive-slug:xyz"))
conn.commit(); conn.close()
def credits(email):
conn = m.get_db(); v = conn.execute("SELECT credit_balance FROM members WHERE email=?", (email,)).fetchone()[0]; conn.close(); return v
seed()
r1 = asyncio.run(m.settle_held_credits(send=False))
print(" run1:", r1["held"], "held |", len(r1["granted"]), "granted |", len(r1["unresolved"]), "unresolved")
assert credits("active@example.org") == 10.0, "active member's hold must be credited"
assert credits("inactive@example.org") == 0.0, "inactive member must NOT be credited"
assert len(r1["granted"]) == 1 and len(r1["unresolved"]) == 1
r2 = asyncio.run(m.settle_held_credits(send=False))
assert credits("active@example.org") == 10.0, "re-run must not double-apply"
assert len(r2["granted"]) == 0, "second run grants nothing"
print("SETTLE HELD CREDITS OK: grants to active, holds for inactive, idempotent")